Groovy « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Groovy ’

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

Encode Content to MD5 Using GROOVY or GRAILS – with Webhook example

Posted by Salil on November 12th, 2010

Recently I was working on webhooks (which are getting quite popular for sending notifications to other applications using HTTP POST methods). MD5 encoded content is heavily used in webhooks for security concern.

My purpose of writing this blog is neither to explain MD5 nor webhooks. But just to show you -
1. a quicker way in Java/Groovy/Grails – How to encode a String (or Content) using MD5 algorithm.
2. Receive Webhook request (containing MD5 encoded certificate)

      // Below is the content (received in http post request body)
      String contentRecievedInRequest = "StringcontentneedtobeverifiedbaseduponMD5algorithm"
      // Below is your secret key - this is not in request - but something that you and trust-party know only)
      String yourSecretKey = "kfkdjfxx8r7kdf"
      // Now Mix your secret key with the content received in http post request
      String claimedContent = "StringcontentneedtobeverifiedbaseduponMD5algorithmkfkdjfxx8r7kdf"
      // following is usually a hexa value - find in the same http-request-header
      String certificate = '3df5786adfe37430d8a8d72cb9e7fe56c'

Now, what we need to do here is – Encode claimedContent as MD5.

1. Using Groovy/Java

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(claimedContent.getBytes());
        BigInteger hash = new BigInteger(1, md5.digest());
        String hashFromContent = hash.toString(16);

2. Using Grails (Single line solution)

        String hashFromContent = claimedContent.encodeAsMD5();

Now what ? Just see if encoded content matches with the certificate received in request-header. If it matches that means it’s valid request (not hacked one).

        if(hashFromContent == certificate){
            println "GOOD REQUEST -- Content Verified"
        }else{
            println "BAD REQUEST"
        }

I hope it might help you somewhere.

Salil Kalia
salil [at] intelligrape [dot] com

  • Share/Bookmark
Posted in Grails, Groovy

Grails way for rendering the GSP templates: The tmpl namespace.

Posted by Chandan Luthra on October 1st, 2010

Today while working on a project, I paired up with my colleague (Uday)  and we found that we can render a gsp template in a different manner also. Grails provide us a “tmpl” namespace for rendering the GSP templates.


The old way that we use to render a gsp template

<g:render template="templateName" model="[books:books, authors:authors]"/>

The other way for  rendering the template.

<tmpl:templateName books=${books}  authors="${authors}"/>

Like me, you also must be wondering that if the template is in some other path like some shared folder “/shared/templateName” then how this <tmpl/> would work?

e.g.

<g:render template="/shared/templateName" model="[books:books, authors:authors]"/>

The answer is: <tmpl:/shared/templateName/>

<tmpl:/shared/templateName books=${books}  authors="${authors}"/>

* you can find the documentation for this on http://www.grails.org/doc/latest/guide/single.html


Concerns, comments or suggestions are always welcome.
Cheers!!!!!
~Chandan Luthra~
chandan(aT)intelligrape(dOt)com
http://in.linkedin.com/in/luthrachandan/

  • Share/Bookmark
Tags: , ,
Posted in Grails, Groovy

Handling Password Protected Pdf with PdfReader

Posted by Hitesh Bhatia on August 19th, 2010

In one of our grails project , we had to attach cover to Pdf file . But since some of pdf’s uploaded were password protected.

To handle this scenario we added bouncyCastle.jar , so our version of iText was able to handle password protected pdf .
And Then to check whether pdf is password protected or not , we used “Boolean isOpenedWithFullPermission()” method.

PdfReader pdf = PdfReader("filePath")
Boolean editable = pdf.isOpenedWithFullPermissions()
 
if(editable){
//attach Cover
}else {
//skip  cover
}

As “isOpenedWithFullPermissions()” returns a Boolean variable ,
it was easy for us to recognize whether we would be able to edit (i.e attach cover in our case) depending on its output. (i,e true or false)
 

_________________________________
Hitesh Bhatia
Mail
LinkedIn,Facebook,Twitter
_________________________________

  • Share/Bookmark
Posted in Grails, Groovy

Unique closure on more than one field.

Posted by Hitesh Bhatia on August 2nd, 2010

In one of my recent grails project, I had requirement to get unique objects from list based on more than one field. Now this can be done by passing list to closure unique .

I had list of dates of couple of years ,and what I needed was unique combination of month and year.

List<Date>  dates 
date.unique{[it.month,it.year]}

_________________________________
Hitesh Bhatia
Mail
LinkedIn,Facebook,Twitter
_________________________________

  • Share/Bookmark
Posted in Grails, Groovy

Open Pdf in Google Docs using Time Based Cache in Grails

Posted by Hitesh Bhatia on June 23rd, 2010

Recently, we had a requirement where secure URLs were to be made accessible to Google.

Our implementation was to send a url with token valid for 10 seconds. The token expired automatically after 10 seconds. We used time based cache for this as described here: http://snippets.dzone.com/posts/show/2360

T set max time to 10 seconds , I set default MaxAge to 10 millis in above file only which could have also been done easily using its constructor.

Here’s how we did it ,

class AbcController {
    static TimedMap timedMap = new TimedMap()
 
   //  while calling "addDocumentUrl" path of document was passed as params attachmentPath
    def addDocumentUrl = {
 	        String attachmentPath = params.attachmentPath
 	        String token = UUID.randomUUID().toString()
 	        timedMap.put(uniqueIdentification,attachmentPath)
 	        redirect(url: getGoogleUrl(token))          // this will  make google hit specified url
 	    }
 
     String getGoogleUrl(String token) {
 	        String absoluteUrl = ConfigurationHolder.config.builder.absoluteURL
                String GOOGLE_URL="http://docs.google.com/viewer?embedded=true&amp;url="
 	        String googlePath = GOOGLE_URL + absoluteUrl + "/abc/someAction/" + token
 	        return googlePath
 	    }
}

Action someAction was made public so that Google was able to access it. And when Google hits this action it gives token as id.

   def someAction = {
        String key = params.id.toString()
        try {
            String attachmentPath = timedMap.get(key)
            File file = new File(attachmentPath)
            response.setHeader("Content-disposition", "attachment; filename=pdf")
            response.setContentType("application/pdf")
            response.setContentLength(file.size().toInteger());
            OutputStream out = response.getOutputStream();
            out.write(file.readBytes());
            out.flush()
            out.close();
        } catch (Exception e) {
            e.printStackTrace()
        }
    }

_______________________________
Hitesh Bhatia
hitesh@intelligrape.com

http://in.linkedin.com/in/bhatiahitesh

_______________________________

  • Share/Bookmark
Posted in Grails, Groovy, Java tools

Password validation with certain conditions

Posted by Amit Jain on June 14th, 2010

Hi Friends,

I needed to validate password for certain conditions. As per the requirements, any valid must password must pass the following conditions:

  1. Minimum of 7 characters
  2. Must have numbers and letters
  3. Must have at least a one special characters- “!,@,#,$,%,&,*,(,),+”

I wrote the following method to meet the requirements:

import java.util.regex.*
 
boolean validatePassword(String password) {
   def pattern = /^.*(?=.{7,})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%*&+()]).*$/
    def matcher = password =~ pattern
    return matcher.getCount() ? true : false
}

I couldn’t make the single regular expression to make it work, so used two. If somebody knows better way of doing it the please share.

Thanks to Imran for helping me in writing the regular expression.

Hope this helped!
~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Posted in Groovy

Working With Soap Calls

Posted by Sachin on June 8th, 2010

Hey,

SOAP is one of the popular ways of working with web-services (another being REST(another of my blog)), while working with any of the SOAP based API, you will get a WSDL (web services description/definition language) describing what all methods are supported by the web service. Its a rather complicated XML document.
A few days back I was working on consuming SOAP based web services. I could not use Groovy WS as the soap calls I needed to make were little complicated, So I used the old httpclient libraries to make the calls. Here is a very simple snippet of the code I was using.

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
class SoapcallController {
 
    def index = {
    def url = "https://www.paymentsample.biz/Gateway.asmx"
    def payload ='
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" 
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" 
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" 
xmlns:tns="http://tempuri.org/" 
xmlns:s="http://www.w3.org/2001/XMLSchema" 
xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" 
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" 
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<SOAP-ENV:Body>
<tns:GetPrimaryPaymentSubTypes xmlns:tns="http://tempuri.org/">
<tns:paymentType>ACH</tns:paymentType>ACH</tns:GetPrimaryPaymentSubTypes>
</SOAP-ENV:Body></SOAP-ENV:Envelope>'
def method = new PostMethod(url)
    def client = new HttpClient()
 
    payload = payload.trim()
    method.addRequestHeader("Content-Type","text/xml")
    method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
    method.setRequestEntity(new StringRequestEntity(payload))
    def statusCode = client.executeMethod(method)
    println "STATUS CODE : ${statusCode}"
    def resultsString = method.getResponseBodyAsString()
    method.releaseConnection()
    //println new XmlSlurper().parseText(resultsString).toString()
    println resultsString
    }
}

In this code we are hitting the “url” with “payload” and getting the response back in the resultsString which itself will be an XML. The payload will change depending upon the WSDL provided.

To generate the payload XML using your own WSDL you can use http://www.soapclient.com/soaptest.html. Its a rather nice tool to use and play before using the web service in your application.

And of course rather than working with XML it is always better to work with objects and method calls,search for wsdl2java or better still Axis2 on google for generating classes from wsdl. I will put a blog on generating classes from WSDL using axis2 api in intelliJ IDEA shortly. :)

Sachin Anand
sachin@intelligrape.com
Intelligrape Software (P) Ltd.

  • Share/Bookmark
Tags: , ,
Posted in Groovy