gautam « Intelligrape Groovy & Grails Blogs
Subscribe via E-Mail:

gautam

Posts by gautam:

  • Curried Closures in groovy

    15 Jan 2011 in Grails

    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
  • Regex in grails CreateCriteria

    14 Oct 2010 in Grails

    Sometimes we need to retrieve the result on the basis of some regular expression pattern which could be applied to a column. In such situations its better to use a rlike method provided by Grails CreateCriteria. Using rlike method it’s easy to retrieve Result based upon the Required Pattern.
    rlike Method is Similar to like, but uses a regex. Only supported on Oracle and MySQL.

    Syntax: rlike(“columnName”,/Regular Expression/)
    e.g.:
    rlike(“holderFirstName”,/Steph.+/)

    .     :  Checks the matched expression for 0 or 1 Characters/Numerics
    +    :  Checks the matched expression for 1 or More Characters/Numerics
    *     :  Checks the matched expression for 0 or More Characters/Numerics
    [0-9]: Checks the matched expression for 1 or more Numeric(Between 0 to 9)
    [a-z]: Checks the matched expression for 1 or more Character(Between a to z or A to Z)
    ^     :    Checks that the matched expression should start with the letters/numbers following it 
    $     :    Checks that the matched expression should end with the letters/numbers before it

    Example1:

    def userList=User.createCriteria().list{
            projections {
                    property("firstName")
                          }
          //check for pattern that start with F and has 5 letters in it and ends with digit
         rlike("firstName",/^F.....[0-9]$/)
     }
    Output: [First10, First11]

    Example2:If we replace rlike in Example1 with this:

     //check for pattern that start with F and has 0 or more letters in it and ends with digit
    rlike("firstName",/^F.*[0-9]$/)
    Output:[First0, First1, First2, First3,First10, First11]

    Example3:If we replace rlike in Example1 with this:

     //check for pattern that start with L and has 0 or more letters in it and ends with digit
    rlike("lastName",/^L*[0-9]$/)
    Output: []

    This Expression won’t works. It will return an Empty List.

    Example4:If we replace rlike in Example1 with this:

     //check for pattern that start with First and has 1 or more letters in it
    rlike("firstName",/First.+/)
    Output:[First0, First1, First2, First3,First10, First11]

    Example5:

    def  userList=User.createCriteria().list{
            projections {
                    property("firstName")
                    property("lastName")
             }
      rlike("lastName",/^L.*[0-9]$/)       //  rlike("lastName",/^L.*[0123456789]$/)
      }
    Output:[[First0, Last 0], [First1, Last 1], [First2, Last 2], [First3, Last 3],
    [First10, Last 10], [First11, Last 11]]

    For more information you can visit this site:
    http://www.grails.org/doc/latest/ref/Domain%20Classes/createCriteria.html

    Hope it Helps!!!

    Regards,
    Gautam Malhotra
    Intelligrape Software

    http://www.intelligrape.com/

    • Share/Bookmark
  • Handling of Different Injection Attacks in Grails

    13 Sep 2010 in Grails

    While implementing Security in my Sample Application I have read various types of Injection attacks that an application may suffer.

    Reference: Grails In Action

    1. SQL Injection Attack:

    def username="gautam"
    Post.findAll(" from Post as post WHERE post.user.username='${username}' ")

    This Query uses a local username property to control which posts are returned.

    Try this Query in Grails Console.

    An attacker can modifies the URL of the request so that the username parameter has the value :

    def username = " ' or ' test' = ' test"
    Post.findAll(" from Post as post WHERE post.user.username='${username}' ")

    The Query is Same, but this time username doesn’t look like  an Id at all. Look what happens when we substitute the value into the query:

    .. WHERE post.user.username = ' '  or  ' test' = ' test'

    Now all Post are returned, which will bring your server to a grinding halt.

    By escaping input values before inserting it into the query, you can foil the attack.

    The modified version of the HQL query that safe from the attack by escaping the value of username:

    def username = " ' or ' test' = ' test"
    Post.findAll(" from Post as post WHERE post.user.username=? ", [username])

    This is the Hibernate equivalent of a JDBC parameterized query.

    2. Cross-Site Scripting (XSS) Attack

    Another form of injection attack which targets HTML and javascript is when user Post this message

    <script type="text/javascript">alert("alert")</script>

    A dialog pops up showing the message “alert”. Now every time you refresh your page, that message will pop up.

    The solution of this is either:

    - you can call the encodeASHTML() method on the text you want to display,

    "${username.encodeASHTML()}"

    But the implementation of the Grails tags like textField tag does the equivalent of encodeASHTML() method.
    i.e,

    <g:textField name="username" value="${post.user.username}">

    is  equivalent of this:

    attrs["value"].encodeASHTML()

    An alternative is to use the defaultCodec page directive to enable HTML escaping on a page-by-page basis:

    <%@ defaultCodec="html" %>

    OR

    -by adding/changing this entry in grails-app/conf/Config.groovy:

    grails.views.default.codec="html"

    By setting the default codec Grails uses to encode data in GSP views to HTML, you can ensure all GSP expression are HTML
    escaped by default (This makes the Setting Global)

    URL Escaping

    <a href="/gTunes/albums?title=${params.title}">Show Album</a>

    Simply by fiddling with the title parameter in a GET request an attacker could perform an XSS attack.To avoid this you can use encodeASURL() method on any data to be included in the URL.

    <a href="/gTunes/albums?title=${params.title?.encodeASURL()}">Show Album</a>


    3. Other Form of Vulnerable Attack:

    Alternative approach is to find out what platform the web application is based on. If you know that then you can narrow your hacking attempts to know the vulnerabilities of the platform.
    There might be some other weakness in the Application like, try pointing your browser at this URL while your application is up and Running:

    http://localhost:8080/application-name/path/unknown

    Any Attacker knows that the application is a java web application running on Jetty/Apache. Also,If application throws an exception,Grails will display its standard error page. Then attacker also knows that your application uses Grails.

    Solution to this Problem is mapping response codes to controllers like:

    class UrlMappings{
    "404" (controller:"errors",action:"notFound")
    "500" (controller:"errors",action:"internalError")
    }

    But this mechanism can be bypassed, if you hard-coded to display the view like error.GSP if an exception is thrown by a GSP page, then it will declare to the user that your application is implemented with Grails.
    You can modified your GSP to send a “500″ error if environment is set to PRODUCTION:

    <%@page import="grails.util.Environment"%>
     
    ${Response.sendError(500)}


    Hope it Helps!!!

    Regards,
    Gautam Malhotra
    Intelligrape Software
    http://www.intelligrape.com/

    • Share/Bookmark