Closure closureTest = { def args1 = null, def args2 = null -> /* do something you wish */ } /* Call above closure as like: */ closureTest.call() /* It will pass args1 & args2 both null */ closureTest("value_args1") /* It will pass args2 null */ closureTest(null, "value_args2") /* It will pass args1 null */ closureTest("value_args1", "value_args2") /* It will pass both args1 & args2 value */ /* You can check number of parameters accept by a closure as like: */ closureTest.maximumNumberOfParameters
Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts
Thursday, August 11, 2016
Groovy call a closure with parameters
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") } }
Friday, July 31, 2015
Grails Add New Resources To MessageSource Dynamically
First create a groovy file with the following contents
package com.pkm.message.test import grails.util.Environment import javax.servlet.ServletContext class MessageSourceCreator { public static def grailsApplication = null public static def servletContext = null public static def messageSource = null private static final String MESSAGE_FILE_DIR = "/WEB-INF/resources/messages" /** * @param fileName "some.message.properties" */ public static void addNewMessageFile(String fileName) { String basePath = servletContext.getRealPath("/") fileName = fileName.substring(0, fileName.lastIndexOf(".")) String relativeFilePath = "${MESSAGE_FILE_DIR}/${fileName}" if (Environment.isWarDeployed()) { messageSource.pluginBaseNames.add(0, relativeFilePath) } else { String separator = Environment.current == Environment.TEST ? "/" : "" messageSource.pluginBaseNames.add(0, basePath + separator + relativeFilePath) } } public static void initialize(def ga, def sc, def ms) { grailsApplication = ga servletContext = sc messageSource = ms } }
From BootStrap, need to call first initialize & then addNewMessageFile
/** * From BootStrap, need to call first initialize & then addNewMessageFile */ import com.pkm.message.test.MessageSourceCreator class BootStrap { def grailsApplication def servletContext def messageSource def init = { servletContext -> MessageSourceCreator.initialize(grailsApplication, servletContext, messageSource) MessageSourceCreator.addNewMessageFile("some.message.properties") } def destroy = { } }
Saturday, July 5, 2014
Grails default version=false to all domain classes
Need to write the following line of code Config.groovy:
grails.gorm.default.mapping = { version false }
Monday, May 5, 2014
Setting default value for fields in Grails Domain Class
class MyDomainClass { Date myDate = new Date(); Boolean myBoolean = false; String myString = ""; static mapping = { myDate defaultValue: "now()" myBoolean defaultValue: "false" myString defaultValue: "" } }
You can use sql now() method rather than Java/Groovy new Date()
Wednesday, February 19, 2014
Groovy template engine
Included with Groovy are several template engines:
Output
File content
Output
SimpleTemplateEngine
- for basic templatesGStringTemplateEngine
- stores the template as writable closures (useful for streaming scenarios)XmlTemplateEngine
- works well when the template and output are valid XML
SimpleTemplateEngine
import groovy.text.SimpleTemplateEngine def text = 'Dear ${contact.firstName} ${contact.lastName}${contact.nickName? " " + contact.nickName: ""}.\n${time} is good.' def binding = ["time":"this evening", month: "February", "contact": ["firstName": "Pritom", "lastName": "Mondal", age: 27]] def engine = new SimpleTemplateEngine() def template = engine.createTemplate(text).make(binding) println template.toString();
Dear Pritom Mondal. this evening is good.
GStringTemplateEngine
import groovy.text.GStringTemplateEngine File templateFile = new File("web-app/test.txt"); def templateEngine = new GStringTemplateEngine(); def templateObject = templateEngine.createTemplate(templateFile).make(binding); println templateObject.toString();
Dear ${contact.firstName} ${contact.lastName}, So nice to meet you in <% out << (time == "this evening" ? "\"${time}\"" : "\"this morning\"") %>. So nice to meet you in <% out << (time == "this evening" ? "\"this morning\"" : time) %>. See you in ${month?: ""}
Dear Pritom Mondal, So nice to meet you in "this evening". So nice to meet you in "this morning". See you in February
Tuesday, October 8, 2013
Groovy Goodness: Sorting a List of Map by specific Key
Sorting a Map by value with Groovy is very simple, due to the added ‘sort’ method on the Map interface.
def hashMap = "fields": {
"field_3": {
"order": 4
},
"field_2": {
"order": 3
},
"field_1": {
"order": 2
},
"field_0": {
"order": 6
}
}
hashMap.sort { a , b -> a.value.order <=> b.value.order }
def hashMap = "fields": {
"field_3": {
"order": 4
},
"field_2": {
"order": 3
},
"field_1": {
"order": 2
},
"field_0": {
"order": 6
}
}
hashMap.sort { a , b -> a.value.order <=> b.value.order }
Thursday, October 3, 2013
Grails Groovy dynamically invokeMethod with empty/single/multi parameters
You need to first get bean object of your service class.
Create a service like below and get your required service by calling:
serviceFinderService.getServiceByName("serviceName");
If you have a service named "StudentService.groovy" then replace "serviceName" with "Student" or "student".
Now check and invoke the method if a specific method existing by such way:
Create a service like below and get your required service by calling:
serviceFinderService.getServiceByName("serviceName");
If you have a service named "StudentService.groovy" then replace "serviceName" with "Student" or "student".
package com.pritom.services import org.codehaus.groovy.grails.web.context.ServletContextHolder import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes class ServiceFinderService { private static HashMap beanList = new HashMap(); private def grailsApplication; private static def ctx; def serviceMethod() { } public def getServiceByName(String bean) throws Exception { if(!ctx) { ctx = ServletContextHolder.servletContext.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT) } bean += "Service"; bean = bean[0].toLowerCase() + bean.substring(1); if(beanList.containsKey(bean)) { return beanList.get(bean); } beanList.put(bean, ctx.getBean(bean)); if(beanList.containsKey(bean)) { return beanList.get(bean); } throw new Exception("Invalid service"); } }
Now check and invoke the method if a specific method existing by such way:
def studentService = ServiceFinderService.getServiceByName("Student"); if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) { def result = studentService.invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]); } /* If your method is static then call it by: */ if(studentService.metaClass.respondsTo(studentService, "methodName", [Integer, String, Boolean] as Object[]) { def result = studentService.metaClass.getTheClass().invokeMethod("methodName", [1, "Pritom K Mondal", true] as Object[]); }
Monday, September 23, 2013
Groovy Check If Method or Property is Available
In Groovy we can easily see if a method or property is available for an object. We can use the
respondsTo()
and hasProperty()
methods to see if the method or property can be invoked or accessed. We
can not check for methods or properties which are added by overriding
the methodMissing()/propertyMissing()
or invokeMethod()/getProperty()
methods.Assume a service: TestService.groovy:
class TestService { String someProperty; def serviceMethod() { } def printString(String str) { println "String: " + str; } def printString(String str, Integer count, Integer map) { println "String: " + str; } }
Now test if specific method existing:
TestService testService = new TestService(); println testService.metaClass.respondsTo(testService, "noMethodExists") ? "Exists: noMethodExists()" : "Not Exists: noMethodExists()"; println testService.metaClass.respondsTo(testService, "printString", String) ? "Exists: printString()" : "Not Exists: printString()"; ArrayList arrayList = new ArrayList(); arrayList.push(String); arrayList.push(Integer); def args = arrayList as Object[]; println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer)" : "Not Exists: printString(String, Integer)"); arrayList = new ArrayList(); arrayList.push(String); arrayList.push(Integer); arrayList.push(Integer); args = arrayList as Object[]; println (testService.metaClass.respondsTo(testService, "printString", args) ? "Exists: printString(String, Integer, Integer)" : "Not Exists: printString(String, Integer, Integer)");
And output will be as:
Not Exists: noMethodExists() Exists: printString() Not Exists: printString(String, Integer) Exists: printString(String, Integer, Integer)
Now check specific property exists:
TestService testService = new TestService();
if(testService.metaClass.hasProperty(testService, "someProperty")) { println "Property: someProperty exists"; } else { println "Property: someProperty not exists"; }
if(testService.metaClass.hasProperty(testService, "someName")) { println "Property: someName exists"; } else { println "Property: someName not exists"; }
And output will be as:
Property: someProperty exists Property: someName not exists
Thursday, September 19, 2013
Grails access something.properties settings under conf directory in BuildConfig.groovy
Create a file named 'config.properties' under conf direcotry with the following properties:
dataSource.driverClassName = com.mysql.jdbc.Driver
dataSource.username = root
tomcatVersion = 2.2.4
Write the following code in 'BuildConfig.groovy' file:
def props = new Properties(); new File("grails-app/conf/config.properties").withReader { props.load(it); } def conf = new ConfigSlurper().parse(props); println conf;
println conf.dataSource.driverClassName;
println conf.dataSource.username;
println conf.tomcatVeriosn;
And output will be as:
[dataSource:[driverClassName:com.mysql.jdbc.Driver, username:root], tomcatVersion: 2.2.4] com.mysql.jdbc.Driver root
2.2.4
Then you can use this settings in your 'BuildConfig.groovy' files like this (highlighted yellow):
plugins { runtime ":hibernate:2.2.4" runtime ":jquery:1.8.3" runtime ":resources:1.2" // Uncomment these (or add new ones) to enable additional resources capabilities //runtime ":zipped-resources:1.0" //runtime ":cached-resources:1.0" //runtime ":yui-minify-resources:0.1.5" build ":tomcat:"+conf.tomcatVersion
/* OR USE */
build ":tomcat:${conf.tomcatVersion}"
runtime ":database-migration:1.3.2"
compile ':cache:1.0.1' }
Grails Access Config.groovy settings in BuildConfig.groovy
Include the following lines in 'BuildConfig.groovy' file
def directory = new File(getClass().protectionDomain.codeSource.location.path).parent; def config = new ConfigSlurper(grailsSettings.grailsEnv).parse(new File(directory + File.separator + "Config.groovy").toURI().toURL()) println "| Tomcat Version (API): " + config.grails.tomcat.version;
Include the following lines in 'Config.groovy'
grails.tomcat.version = "2.2.4"Then when run the program it prints like:
| Tomcat Version (API): 2.2.4Then you can use this settings in your 'BuildConfig.groovy' files like this (highlighted yellow):
plugins { runtime ":hibernate:2.2.4" runtime ":jquery:1.8.3" runtime ":resources:1.2" // Uncomment these (or add new ones) to enable additional resources capabilities //runtime ":zipped-resources:1.0" //runtime ":cached-resources:1.0" //runtime ":yui-minify-resources:0.1.5" build ":tomcat:"+config.grails.tomcat.version runtime ":database-migration:1.3.2" compile ':cache:1.0.1' }
Subscribe to:
Posts (Atom)