Groovy « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Groovy ’

Grails:Domain Design Via Intellij Idea’s Diagrams

Posted by Hitesh Bhatia on November 23rd, 2011

Here is an example of how to design Grails domain class with Intellij Idea.For this we need to have blank domain classes. So lets say we created  three Domain Classes Company,Book,Author

  1. To see relationship diagram, Selected Domain Class, and selected tab Domain Class Dependencies.It should look like this
    image
  2. Lets assume the relation that publication has many books. So I drag mouse from Company to Books. Which invokes a popup asking about relationship between the domains and type and name of the field.
    image
  3. On Selecting ok from previous popup. Their relation is defined in domain and in diagram. Similarly, lets define
    1. Book hasMany Authors,
    2. Authors hasMany Books,
    3. Book belongsTo Author
    4. And Diagram looked like this.

    image

  4. Next Step – Lets add fields to Domain Class all by Intellij Idea’s UI. Select package of domain class and pressshft+ctrl+alt+u. It’ll open package diagram of app.
    image
  5. Now lets add field name to domain Author. For that we’ll need to select domain author,right click and select fields. It’ll invoke a popup asking details about field.
    image
    Similarly we add field name to Author and published on to Book.
  6. Now lets add a method to named “publishedBefore” to Book which takes a date and return list of books published before that date.For this we need to right click on domain and select method.And it’ll invoke popup asking details.Select create and its done.
    image

This was a simple and easy way to create structure of grails app in Intellij Idea.

_________________________________
Hitesh Bhatia
Mail,LinkedIn,Facebook,Twitter
_________________________________
  • Share/Bookmark
Posted in GORM, Grails

Groovy : Find Index of Element in Map

Posted by Hitesh Bhatia on November 10th, 2011

Groovier way of finding index of element from Map. It can be obtained with findIndexOf Method, which accepts closure as argument.


Map map=["groovy":1,"grails":2,"index":3,"element":4]
assert 3 == map.findIndexOf{it.key=="element"}
assert 0 == map.findIndexOf{it.value==1}
  • Share/Bookmark
Posted in Groovy

Grails: Dynamically create instance of a POGO class

Posted by roni on June 15th, 2011

Hi guys,

Recently on a project, I was creating a number of command objects to accept incoming parameters from a POST call from an iPhone with which I needed to sync data. I created a parent class for all command object classes to accept the common properties and created individual command object classes to accept any additional parameters.

The use case was that the name of the command object class was being created dynamically from the URL. Now, when I was trying to create a new instance of a command object in a controller using the following code, I got a ClassNotFoundException to my utter surprise:

DefaultGrailsApplication grailsApplication = ApplicationHolder.application.mainContext.getBean("grailsApplication")
def clazz = grailsApplication.getClassForName("com.intelligrape.co.sync.SyncCO").newInstance()

So I tried going through the Java style of fetching a class instance as follows:

def clazz = Class.forName("com.intelligrape.co.sync.SyncCO").newInstance()

Needless to say, I ran into the same problem again. After a lot of searching on the Internet and headbanging, I realized that classes in the src/groovy or src/java are not available to the grails class loader and they are loaded by the URLClassLoader which is a subclass of Java’s ClassLoader. Along with Uday’s help and a nabble post, I realized that I needed to use the three parameter Class.forName() method to create a new instance of a POGO or a POJO.

I ended up using the following syntax which worked for me in this case:

def clazz = Class.forName("com.intelligrape.co.sync.SyncCO", true, Thread.currentThread().getContextClassLoader()).newInstance()

The above code gets a reference of the current executing thread’s root class loader to fetch an instance of all classes loaded in the current executing application. Documentation for the method is located here: Class.forName()

I hope this helps any lost soul who has tried and failed at creating a new instance of a POGO.

Cheers
Ron
roni[at]intelligrape[dot]com

  • Share/Bookmark
Tags: , ,
Posted in Grails

Groovy: Few ways to convert string into enum

Posted by Amit Jain on April 15th, 2011

Many at times, we have a string which needs to be converted into Enum. I will be sharing few options as stated by Mr.Haki, Isa Goksu and in the last the one I discovered during the process. Lets say we have a Enum AccountType as given below :


enum AccountType {
     CHECKING,
     SAVING
}

assert AccountType.CHECKING == "CHECKING" as AccountType

assert AccountType.CHECKING == AccountType.valueOf("CHECKING")
def className = AccountType.class
assert AccountType.CHECKING == Enum.valueOf(className, "CHECKING")

assert AccountType.CHECKING == AccountType["CHECKING"]
String type = "CHECKING"
assert AccountType.CHECKING == AccountType[type]

Cheers!
~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Posted in Groovy

Handling Instance Based Security

Posted by Imran Mir on April 6th, 2011

In my current project, we were required to implement Instance Based Security. The idea was to find a clean solution separate from the main business logic of the application. We took a clue from the Spring Security Plugin to use the Annotations to do our job. All we wanted to do was to develop annotations for actions, which could help to decide what type of access verification needs to be done on a particular request, inside some Filter. So we proceeded like this :

We created an Abstract Class from which our User domain Class extended. All our Access Verifying functions would remain in this class. The class provides a single entry function (by the name evaluateExpression) to all other Access Verifying functions. This helped us to keep the Filter class clean. The Class looks like :

abstract class MyAppSecure {

  public Boolean evaluateExpression(String methodName, Map params = [:]) {
    this."$methodName"(params.id?.toLong())
  }

  // One of the many functions to be used to verify valid access
  public Boolean hasUserAccessById(Long id) {
    return id ? (this.id == id.toLong()) : true
  }

}

So our User domain class looks like:

class User extends MyAppSecure {

}

Now, the idea is to:

  1. Intercept a request in the filter.
  2. Get the annotation expression placed on top of the respective Controller Action. (The expression(s) would be name of the MyAppSecure method(s) used to verify the access)
  3. Call a corresponding method in MyAppSecure to verify access
  4. Take appropriate action corresponding to a result

So let us delve into the implementation:

First step would be to enable the annotations. To do this create an interface in src/java (or you can do it in src/groovy as well):

@Documented
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MySecured {
    String[] expressions();
}

Now we are good to go for using annotations. Let us assume an action edit inside AccountController:

class AccountController{

@MySecured(expressions = ["hasUserAccessToAccount"])
 def edit = {
    User user = params.id ? User.get(params.id) : user
    render(view: "edit", model: [user: user])
  }
}

Note: We can also give multiple expressions (to evaluate multiple access rules), seperated by a commas inside the list.

Now we need to implement a method by the name hasUserAccessToAccount in MyAppSecure:

abstract class MyAppSecure {

public Boolean evaluateExpression(String methodName, Map params = [:]) {
    this."$methodName"(params)
}

public Boolean hasUserAccessToAccount(Map params) {
// SAMPLE LOGIC.
    Integer count = Account.createCriteria().get {
      projections {
        count("id")
      }
      eq('id', params.id.toLong())
      eq('user', this)
    }
    return (count > 0)
  }
 }
}

We would also need some logic to get and parse annotations in MyAppSecure. We wrote something like this :

public Boolean hasAccess(Class controllerClazz, String actionName,  Map params) { def field = controllerClazz.declaredFields.find {it.toString().indexOf(controllerClazz.name + '.' + actionName) != -1}
 // get the annotation on a Controller action (account/edit in our case)
    def securedAnnotation = field.getAnnotation(AdlSecured)
    return (securedAnnotation ? this.evaluateEveryExpression (params, securedAnnotation)
  }

 // Evaluate every expression and combine the result using AND (or we can use OR as well)
  private Boolean evaluateEveryExpression(Map params, def securedAnnotation) {
    Boolean hasAccess = securedAnnotation.expressions().every {String securedExpression ->
      this.hasAccessForExpression(securedExpression, params)
    }
    return hasAccess
  }

  //Evaluate expression
  private Boolean hasAccessForExpression(String expressionToBeEvaluated, Map params) {
    return this.evaluateExpression(expressionToBeEvaluated, params)
  }

Now in you Filter you can write something like this:

mySecureFilter(controller: "*", action: "*") {
      before = {
          User user = someSecurityService.currentUser
          if (user) {
          // gets the controller class for a controllerName
            Class controllerClazz = getControllerClass(controllerName)

            if (!user.hasAccess(controllerClazz, actionName, params)) {
                redirect(controller: 'accessController', action: 'unauthorized')
                }
              }
              return false
            }
          }

That is all that we need to do. I hope you would find this useful. Any suggestions will be welcomed.

  • Share/Bookmark

Using groovy execute bash scripts

Posted by Amit Jain on February 15th, 2011

Hi Friends,

Recently I had to execute bash script using groovy on a windows server. Though I could easily make the similar script run on linux, but on windows it just didn’t work as it was unable to recognize the internal DOS commands like cp, rm etc.

On linux the following code worked but not on windows:

 File script = new File('<My_Script_Path>')
 script.getText().execute()
 

So after trying few options, I found that we can call execute method on script path also apart from calling it directly on commands and which worked for both windows and linux, as given below :

  "<My_Script_Path>".execute()

To see the output of the script on the console, we can use the following command :

 println "<My_Script_Path>".execute().text

Hope this helped!

Cheers!
~~Amit Jain~~
amit@intelligrape.com

http://intelligrape.com

  • Share/Bookmark
Posted in Groovy

Groovy: Sort list of objects on the basis of more than one field

Posted by Salil on January 25th, 2011

Usually, when we deal with databases, we don’t face such kind of situation because we query database to get result-set in required order.

But let’s say you have a List of objects that you want to sort on the basis of two fields. Let’s discuss it with an example.


I have a list of Tasks (with date and priority fields). I want to sort these tasks ordered by Date and priority-wise (as second level sorting).

Here, I gonna use Expando class, so I can directly run this in my groovyConsole. But definitely you can use some ‘Task’ class.

Expando a = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:1)
Expando b = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:2)
Expando c = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-02'), priority:1)
Expando d = new Expando(date: Date.parse('yyyy-MM-dd','2011-01-01'), priority:3)

def list = [a,d,c,b]

If sorting was required on the basis of date only, it was very simple.

list.sort(it.date)

But as per our requirements – order by date (first level sorting) and priority (second level sorting). We can do something like following.

list.sort{x,y->
  if(x.date == y.date){
    x.priority <=> y.priority
  }else{
    x.date <=> y.date
  }
}

Well, there could be some better way. If you know please put your comments. But it worked well in my case.



Cheers!
Salil Kalia
Salil [at] IntelliGrape [dot] com
Twitter LinkedIn

  • Share/Bookmark

Curried Closures in groovy

Posted by gautam on January 15th, 2011

There’s a feature that adds spice to Groovy—it’s called Curried Closures.
The term curry is taken from Haskell Curry, the mathematician who developed the concept of partial functions. Currying refers to taking multiple arguments into a function that takes many arguments, resulting in a new function that takes the remaining arguments and returns a result.
When we curry( ) a closure, we are asking the parameters to be prebound. That is, We are assigning value to the parameters of a closure. This can help remove redundancy or duplication in our code.
When calling the curry() method we need not supply the full complement of actual parameters. The curried call gives rise to the partial application of the closure. The partial application of a closure is another Closure object in which some values have been fixed.
For Example:-

def tellFortunes(closure)
{
Date date = new Date("12/16/2010" )
postFortune = closure.curry(date) 
//postFortune = {  fortune -> println "Fortune for Thu Dec 16 00:00:00 UTC 2010 is '${fortune}'"}
postFortune "This is the second parameter"     // implicit call
postFortune "They're features, not bugs"         // implicit call
}
 
//Call tellFortunes with a closure
tellFortunes() { date, fortune ->
println "Fortune for ${date} is '${fortune}'"
}
output:
Fortune for Thu Dec 16 00:00:00 UTC 2010 is 'This is the second parameter'
Fortune for Thu Dec 16 00:00:00 UTC 2010 is 'They're features, not bugs'

We have a function named tellFortunes that takes a closure. This closure has 2 parameters Date and fortune. Inside tellFortune Function we are prebound a closure parameter Date and assign it’s reference to a variable postFortune. Now we call postFortune with only 1 parameter which assign this value to the “fortune” parameter.

curry() assign values to the parameters from left to right. In order to assign the value from right to left we use rcurry() method.
For Example:-

def divide = { a, b -> a / b }
def  assignValueToParameterStartFromRightPosition  = divide.rcurry(2)
assignValueToParameterStartFromRightPosition(8)
output:
4
Example:
def sum = { a, b,c ->
println "a=" + a
println "b=" + b
println "c=" + c
}
def assignValueToParametersStartFromRightPosition = sum.rcurry(80,40)
assignValueToParametersStartFromRightPosition(20)
output:
a=20
b=80
c=40

In order to support for Closure currying at a given index, we use ncurry() method. Parameters are supplied from index position “n”
(index start from 0).
Below, we have a closure which is assigned to variable “divide”. Using ncurry() we assign the value to the parameter, which is at index “0″,in this case “a” is being assigned a value 80.

def divide = { a, b -> a / b }
def assignValueToParameterAtNthPosition = divide.ncurry(0,80)
assignValueToParameterAtNthPosition(8)
output:
10
Example:
def printParameters = { a, b, c ->
println "a=" + a
println "b=" + b
println "c=" + c
}
def assignValueToParameterAtNthPosition = printParameters.ncurry(1,80)
assignValueToParameterAtNthPosition(20,40)
output:
a=20
b=80
c=40

Closure composition
One of the important characteristics of closures is composition, wherein you can define one closure whose purpose is to combine other closures. Using composition, two or more simple closures can be combined to produce a more elaborate one.

Example:-
def multiply = { x, y -> return x * y }    
// closure
def triple = multiply.curry(3)            
// triple = { y -> return 3 * y }
def quadruple = multiply.curry(4) 
// quadruple = { y -> return 4 * y }
def composition = { f, g, x -> return f(g(x)) }
def twelveTimes = composition.curry(triple, quadruple)
def threeDozen = twelveTimes(3)
println "threeDozen: ${threeDozen}"		 
// threeDozen: 36

Use-Case:
Consider the problem of computing the net price of a specific Book item, taking into account the shop discount and any governmental taxes such as a value added tax. If we include this logic as part of the Book class, the resulting solution would probably be a hard-wired one. Because the bookshop could change the value of its discount or apply it to only a selection of its stock, such a solution would likely be too rigid.
Changing such rules are readily accommodated using Curried Closures.
We can use a set of simple closures to represent individual rules and then combine them in various ways using compositions. Finally, Map them to collections using computation patterns.

class Book {
    String name
    String author
    BigDecimal price
    String category
}
 
def book = new Book(name:'Groovy', author:'KenB', price:25, category:'CompSci')
def discountRate = 0.1
def taxRate = 0.17
//  book closures
def rMultiply     = { y, x -> return x * y }
def calcDiscountedPrice = rMultiply.curry(1 - discountRate)
def calcTax = rMultiply.curry(1 + taxRate)
def composition   = { f, g, x -> return f(g(x)) }
def calcNetPrice = composition.curry(calcTax, calcDiscountedPrice)
//  now calculate net prices
def netPrice = calcNetPrice(bk.price)
println "netPrice: ${netPrice}"		// netPrice: 26.325

The closure rMultiply is a partial application that adapts the binary multiplication to be a unary closure by using a constant second operand. The two book closures calcDiscountedPrice and calcTax are instances of the rMultiply closure with set values for the multiplier value. The closure calcNetPrice is the algorithm to compute the net price by first calculating the discounted price and then the sales tax on top of that. Finally, calcNetPrice is applied to the price of the book.

References:
http://www.ibm.com/developerworks/java/library/j-pg08235/index.html
http://groovy.codehaus.org/Closures+-+Formal+Definition

Hope it helps!

Gautam Malhotra
gautam@intelligrape.com

  • Share/Bookmark
Posted in Grails

Request Mocking to use groovyPagesTemplateEngine in backend threads

Posted by Vivek Krishna on December 27th, 2010

We have a setup where a backend thread, fired by the Spring Events, does some processing, generates a PDF and emails the result to the user.
The code we were using to generate the HTML from a GSP to be converted to a PDF using iText was as follows :

        def webRequest = RequestContextHolder.getRequestAttributes()
        def originalOut = webRequest.out
        try {
            def sw = new StringWriter()
            def pw = new PrintWriter(sw)
            webRequest.out = pw
            groovyPagesTemplateEngine.createTemplate("path_to_gsp").make([model:model]).writeTo(pw)
            return sw.toString()
        } finally {
          webRequest.out = originalOut
        }

There was the obvious fallibility of this code that there was no Current Request associated with the backend thread!

After doing some googling around it, I came across a few threads and posts which talked about Request Mocking, which has been used in Grails Template Engine Plugin.  We overcame this by using the code snippet given below to mock the web request

def webRequest = RequestContextHolder.getRequestAttributes()
if(!webRequest) {
          def servletContext  = ServletContextHolder.getServletContext()
          def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
          webRequest = grails.util.GrailsWebUtil.bindMockWebRequest(applicationContext)
}

However, things didn’t end there. This code broke while working on a WAR environment. The problem was that the MockWebRequest class was part of the “org.springframework:org.springframework.test:3.0.3.RELEASE” jar and had to be included in the BuildConfig.groovy as


dependencies{

runtime 'org.springframework:org.springframework.test:3.0.3.RELEASE'

}

Ensure that the line


mavenCentral()

is not commented in BuildConfig.groovy

We were working on Grails 1.3.4

 

Hope this helps.
Vivek

http://in.linkedin.com/in/svivekkrishna

  • Share/Bookmark
Posted in Grails

Using Groovy MOP and Closure to prevent expression evaluation in logger.debug()

Posted by Mohd Farid on December 13th, 2010

Generally in our code, we have lots of debug statements that prints the intricate details of the state of the program. Infact, the debug statements are meant for doing this. Sometimes, these debug statements may contain a call to some other method to evaluate what is to be logged.

//Logging statement calling some function to get what is to be logged
logger.debug myVeryBigFunc()

def myVeryBigFunc()
{
   //Do something big...
   // Take lot of time and resources
   //
   return “SUCCESSFUL IN THE BIG TASK”
}

If the logger level is set to DEBUG. The above code would log "SUCCESSFUL IN THE BIG TASK“.

Once our application graduates to production we might not really care to see those debug statements. We just need to see something of priority WARN or higher. We would set logger level to WARN. Now, the above code would not print anything. But, still it will execute the myVeryBigFunc()   in order to pass the result as an argument to logger.debug().

The decision to log the message or not is taken inside the logger.debug() method only after getting its  arguments. This is clearly an overhead to evaluate the arguments which are to be ignored later.

Can we really do something to avoid this???

In old java days, we used to fix this by using logger.isDebugEnabled() method.

if(logger.isDebugEnabled())
{
	logger.debug myVeryBigFunc()
}

Now, the myVeryBigFunc() would not be called at all because our ‘if’ statement is making sure that logger.debug() is called only when the logging level is atleast DEBUG. This seems to be a pretty cool fix at the moment.  But this becomes very dirty as the log statements increase.

So, how can we achieve this without being at the risk of looking dirty.

The solution is with the Closure and MOP feature of Groovy which enables us to create an overloaded function for debug which takes a Closure as an argument. This Closure is evaluated only after checking for logging level.

The following piece of code does just the same.

We have overloaded the Logger’s debug(), info(), error(),warn() and fatal() methods to accept Closure as an argument.
In the overloaded versions we first check for logging levels and if the logging level permits the current method to log, only then the closure is evaluated.

class Log4jEnhancerMOP
{
   static void addClosureOverloadsToLoggerDynamically()
   {
      ['debug', 'info', 'warn', 'error', 'fatal'].each{ logLevel ->
            println "Defining metaclass method for logging level $logLevel"
            Logger.metaClass."${logLevel}" = {Closure clos ->
            if (delegate.invokeMethod("isEnabledFor", Level."${logLevel.toUpperCase()}"))
            {
                println "logging is enabled for $logLevel"
                delegate.invokeMethod("$logLevel", clos.call())
            }
            else
            {
                println "logging is not enabled for $logLevel"
            }
        }
     }
  }

  public static void main(String[] args)
  {
     addClosureOverloadsToLoggerDynamically()
     Logger logger = Logger.getRootLogger()

     //setting the logger level to WARN
     logger.level = Level.WARN
     logger.addAppender(new ConsoleAppender(new PatternLayout("%-5p [%t]: %m%n ")))

     //calling the regular debug() method myVeryBigFunc() would get called even if the logger level is set to WARN
     logger.debug(myVeryBigFunc("DEBUG MESSAGE"))

     //calling the overloaded debug() method. myVeryBigFunc() would not be called as is present in a closure. The closure
     //is executed by the overloaded method only if the logger level has debug enabled.
     logger.debug {myVeryBigFunc("DEBUG MESSAGE")}

     logger.error {myVeryBigFunc("ERROR MESSAGE")}
     logger.fatal {myVeryBigFunc("FATAL MESSAGE")}
     logger.info {myVeryBigFunc("INFO MESSAGE")}

 }

 static String myVeryBigFunc(String msg)
 {
    println "invoked myVeryBigFunc... $msg"
    return 'SUCCESSFUL IN THE BIG TASK'
 }
}

Hope this helps!!!

Any suggestions or corrections are most welcome.

Thanks & Regards
Mohd Farid
Intelligrape Software

  • Share/Bookmark
Posted in Groovy, logging