package com.pritom.kumar; import java.io.PrintWriter; import java.io.StringWriter; /** * Created by pritom on 18/01/2016. */ public class ExceptionToString { public static String convertExceptionToString(Throwable throwable) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); return sw.toString(); } catch (Exception ex) { ex.printStackTrace(); return null; } } }
Monday, January 18, 2016
Convert Exception Details To String Using Java
Thursday, December 3, 2015
Grails Error Handling With Custom Http Status Code
First need to create a trait Groovy file as follows under src/groovy:
trait CustomExceptionHandler { /* Handle common exception */ def handleException(Exception e) { handleCustomException(new CustomException(e.getMessage())) } /* Handle defined custom exception */ def handleCustomException2(CustomException2 e) { handleCustomException(e) } /* Handle defined custom exception */ def handleCustomException(CustomException e) { if (!CommonUtils.request) { // do something } else { CommonUtils.currentResponse.status = 220 (Custom response code) if(e.getStatusCode()) { CommonUtils.currentResponse.status = e.getStatusCode() } if (CommonUtils.request.xhr) { def error = [ type: "error", message: e.getMessage() ] render error as JSON } else { render(view: "/error/error", model: [exception: e]) } } } }
Create a groovy class under src/groovy:
import org.springframework.web.context.request.RequestContextHolder class CommonUtils { public static def getRequest() { def request = RequestContextHolder.getRequestAttributes() return request ? request.request : null } public static HttpServletResponse getCurrentResponse() { return WebUtils.retrieveGrailsWebRequest().getCurrentResponse() } }
Exception Types (Reside in src/groovy):
class CustomException extends RuntimeException { } class CustomException2 extends CustomException { }
How controller can use this feature:
class Controller1 implements CustomExceptionHandler { def index() { throw new Exception("Common exception") } def index2() { throw new CustomException("Defined custom exception") } def index3() { someService.index3() } def index4() { someService.index4() } }
Exception thrown from service bahave same as from controller
class SomeService { def index3() { throw new Exception("Common exception") } def index4() { throw new CustomException("Defined custom exception") } }
Java Code To Check Repeated Character In String
import java.util.regex.Pattern; import java.util.regex.Matcher; class RepeatedCharacterCheck { public static void main (String[] args) throws java.lang.Exception { String stringToMatch = "abccdeeefenonn"; Pattern p = Pattern.compile("(\\w)\\1+"); Matcher m = p.matcher(stringToMatch); while (m.find()) { System.out.println("Duplicate character " + m.group(0)); } } }
Output
Duplicate character ccDuplicate character eee
Duplicate character nn
Friday, October 16, 2015
Using a CASE Statement/If Condition in HQL select query
SELECT name,
CASE WHEN name = 'Name' then 'Name is Name' else 'Name is not Name' end From Domain
Wednesday, October 14, 2015
HQL Use MySQL Functions By Implementing Custom Dialect
Datasource.groovy File
hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory' cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider' format_sql = false use_sql_comments = false } grails.cache.config = { cache { name 'org.hibernate.cache.UpdateTimestampsCache' eternal true maxEntriesLocalHeap 500 persistence { strategy localTempSwap } } } /* environment specific settings */ environments { development { dataSource { pooled = true url = "jdbc:mysql://localhost/db_name?useUnicode=yes&characterEncoding=UTF-8" driverClassName = "com.mysql.jdbc.Driver" username = "root" password = "" dialect = "com.pkm.custom.CustomMySQLDialect" dbCreate = "update" properties { maxActive = 1000 maxIdle = 100 minIdle = 50 initialSize = 1 minEvictableIdleTimeMillis = 60000 timeBetweenEvictionRunsMillis = 60000 numTestsPerEvictionRun = 3 maxWait = 10000 testOnBorrow = true testWhileIdle = true testOnReturn = true validationQuery = "SELECT 1" minEvictableIdleTimeMillis = 1800000 timeBetweenEvictionRunsMillis = 1800000 } logSql = false loggingSql = false } } test { dataSource { } } production { dataSource { } } } log4j = { debug 'org.hibernate.SQL' trace 'org.hibernate.type.descriptor.sql.BasicBinder' }
Custom Dialect (.groovy) Used In Datasource
import org.hibernate.dialect.MySQL5InnoDBDialect import org.hibernate.dialect.function.SQLFunctionTemplate import org.hibernate.dialect.function.StandardSQLFunction import org.hibernate.type.IntegerType import org.hibernate.type.StringType import org.hibernate.type.TimestampType class CustomMySQLDialect extends MySQL5InnoDBDialect { public CustomMySQLDialect() { super() /* convert_tz('2015-01-01', '+00:00', '+10:00') = '2015-01-01 10:00' */ /* convert_tz('2015-01-01 00:00', '+00:00', '+10:00') = '2015-01-01 10:00' */ /* convert_tz('2015-01-01 20:00', '+00:00', '-10:00') = '2015-01-01 10:00' */ registerFunction("convert_tz", new StandardSQLFunction("convert_tz")) /* group_concat(name) = 'a,b,c,c,d' */ registerFunction("group_concat", new StandardSQLFunction("group_concat", new StringType())) /* group_concat_unique(name) = 'a,b,c,d' */ registerFunction("group_concat_unique", new SQLFunctionTemplate(new StringType(), "group_concat(DISTINCT ?1)")) /* date_add_interval('2015-01-01', DAY, 10) = '2015-01-11' */ /* date_add_interval('2015-01-20', DAY, -10) = '2015-01-10' */ registerFunction("date_add_interval", new SQLFunctionTemplate(TimestampType.INSTANCE, "date_add(?1, INTERVAL ?3 ?2)")) /* index_of('am', 'i am good') = 3 */ /* index_of('asm', 'i am good') = 0 */ registerFunction("index_of", new SQLFunctionTemplate(new IntegerType(), "LOCATE(?1, ?2)")) /* format(number, decimal_place, locale) = format(200.343, 2, 'en_AU') = '200.34' */ registerFunction("format", new StandardSQLFunction("format", new StringType())) } @Override public String transformSelectString(String select) { select = super.transformSelectString(select); return select; } }
Wednesday, September 30, 2015
Myob Cloud Integration: Use Filter In Myob Integration
Equal Method (String) {domain}/{cf guid}/Sale/Invoice/?$filter=PaymentDetails/Method eq 'Cash' Equal Method (UID) {domain}/{cf guid}/Sale/Invoice/?$filter=Customer/UID eq guid'd61a6a86-453a-48bf-9402-6eb6b4ea23cf' Equal Method (Boolean) {domain}/{cf guid}/Contact/?$filter=IsIndividual eq true Filtering in List {domain}/{cf guid}/Contact/Customer/?$filter=Addresses/any(x: x/Email eq null) Equal Method (Date) {domain}/{cf guid}/Purchase/Bill/?$filter=Date ge datetime'2014-07-01' and Date le datetime'2014-09-24'
Sunday, August 30, 2015
Grails Get/Use Http Session In Service Or Util Class
import org.codehaus.groovy.grails.web.util.WebUtils import javax.servlet.http.HttpSession HttpSession httpSession = WebUtils.retrieveGrailsWebRequest().request.session
Subscribe to:
Posts (Atom)