Grails « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Grails ’ Category

Node.js: Unit Testing with Jasmine framework

Posted by on May 14th, 2013

Jasmine is a framework which is used for testing node.js code or javascript code.

Installation

To install the latest official version, use NPM:

npm install jasmine-node -g

Write the specifications for your code in *.js and *.coffee files in the spec/ directory

Execution

After installing the npm package, you can run it with:

jasmine-node spec/filename.js
jasmine-node spec/filename.coffee

For executing multiple test files you can provide multiple filenames as an argument to jasmine-node command.


Key features :

  1. Behavior driven.
  2. It does not require DOM for testing.
  3. Clean and obvious syntax.

Test Cases :

SUITES
Call to a global function ‘describe’ which takes arguments a String and function. The function is a block of code that implements the suite.The String describes the title for the suit.

SPECS
Call to global Jasmine function ‘it’, which like ‘describe’ takes a string and a function. The string is a title for this spec and the function is the spec, or test. A spec contains one or more expectations that examine the state of the code under test,their can be as many ‘it’ functions in describe block.

EXPECTATION
Expectation in jasmine is an assertion which results either true or false. Their can be as many assertions in a spec. Expectations are genrated with the function ‘expect’ which takes an argument which is the actual value. It is chained with a Matcher function, which takes the expected value.

MATCHERS

Each matcher implements the Boolean comparison between actual and expected value. Matchers are used to compare both the values and if all matchers matches or return true only then test is considered as passed else it is considered as failure. Some of the matchers functions are ‘toBe’, ‘toBeTruthy’ etc.
Some examples are as follows:

expect(x).toEqual(y); // compares objects or primitives x and y and passes if they are equivalent
expect(x).toBe(y); // compares objects or primitives x and y and passes if they are the same object
expect(x).toMatch(pattern); //compares x to string or regular expression pattern and passes if they match

beforeEach() and afterEach()

Function ‘beforeEach’ performs task that is to be performed before test begins and ‘afterEach’ performs task that is to be performed after test finished execution.

Sample test

describe("A suite", function() {
var a;

it("A spec", function() {
a = true;

expect(a).toBe(true);
expect(a).not.toBe(false);
});
});

Sahil Chitkara
Software Trainee
Intelligrape Software

Using Ftp with Grails

Posted by on April 4th, 2013

In one of my Grails project I need to drop files over ftp server. Using JSch one can easily transfer files over sftp. Just follow the below steps.
1. Add the below dependency to Grails project “grails-app/conf/BuildConfig.groovy” file

dependencies {
        compile 'com.jcraft:jsch:0.1.49'
    }

2. Create a class for adding ftp credentials information. e.g. “FtpCredentail”

class FtpCredential {

    String server
    String username
    String password
    String remoteBaseDir
    Integer port
}

3. Create a service named “FtpService” and add the following code into it

import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session

class FtpService {
    def grailsApplication

    static transactional = true

    def save(InputStream inputStream, String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.put inputStream, fileName
        }
    }

    def load(String fileName, FtpCredential ftpCredential) {
        connect(ftpCredential, { ChannelSftp sftp ->
            File outputFile = File.createTempFile(fileName,'')
            outputFile?.newOutputStream() << sftp.get(fileName)
            outputFile
        }, false)
    }

    def delete(String fileName, FtpCredential ftpCredential) throws Throwable {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.rm fileName
        }
    }

    def makeDir(String directoryName, FtpCredential ftpCredential) {
        connect(ftpCredential) { ChannelSftp sftp ->
            sftp.mkdir directoryName
        }
    }

    private def connect(FtpCredential ftpCredential, Closure c, boolean disconnectOnFinish = true) {
        Session session = null
        ChannelSftp sftp = null
        try {
            JSch jSch = new JSch()
            session = jSch.getSession username, ftpCredential?.server, ftpCredential?.port
            session.setConfig "StrictHostKeyChecking", "no"
            File keyFile = new File("${grailsApplication.config.pathToKeyFile}")
            if (ftpCredential?.password) {
                session.password = ftpCredential?.password
            } else {
                jSch.addIdentity(keyFile?.absolutePath)
            }
            session.connect()
            Channel sFtpChannel = session.openChannel "sftp"
            sFtpChannel.connect()
            sftp = sFtpChannel as ChannelSftp
            sftp.cd ftpCredential?.remoteBaseDir
            c.call sftp
        } catch (Exception ex) {
            ex.printStackTrace()
        } finally {
            if (disconnectOnFinish) {
                sftp?.exit()
                session?.disconnect()
            }
        }
    }
}

Note: In the above code at line number 44.

File keyFile = new File("${grailsApplication.config.pathToKeyFile}")

The code looks for private key provided by ftp server for password-less log in. One should define the property named “pathToKeyFile” in “grails-app/conf/Config.groovy” with value equals to the path of key file.

Now you are ready to use the newly created FtpService service methods. Such as:

  1. save(inputStream, fileName, ftpCredential) for saving file over ftp.
  2. load(fileName, ftpCredential) for getting file from ftp.
  3. delete(fileName, ftpCredential) for deleting file over ftp.
  4. makeDir(directoryName, ftpCredential) for creating directory over ftp.

Example

For saving file over ftp one can use FtpService save method as shown below

 File file = File.createTempFile("temp","txt")
 FtpCredential ftpCredential = new FtpCredential(server: <server>, username: <username>, password: <password>, port: <server_port>, remoteBaseDir: <remote_base_directory>)
 InputStream inputStream = new BufferedInputStream(new FileInputStream(file))
 ftpService.save(inputStream, "fileNameToBeSavedOverFTPServer", ftpCredential)

Please share your feedback and suggestions.


Click here to read more JSch examples »



Puneet Behl
puneet.behl@intelligrape.com
https://twitter.com/puneetbhl
http://in.linkedin.com/in/puneetbhl

Posted in Grails

Groovy: Ways to represent String

Posted by on April 2nd, 2013
  • Compared to Java we have a lot of  ways to represent strings : GString, single quote, double quotes, slashy and dollar slashy.

 
1.GString: A GString is just like a normal String, except that it evaluates expression that are embedded with in string in the form ${..}.

String demo="Brother"
String doubleQuotes= "Hello ${demo}"
println doubleQuotes   //Output:Hello Brother

String slashy= /Hello ${demo}/
println slashy   //Output:Hello Brother

String dollarSlashy= $/Hello ${demo}/$
println dollarSlashy   //Output:Hello Brother

2.Single Quote:Groovy Treats a String created using single quotes as a pure literal.

String demo="World"
println 'Hello "${demo}"'   //Output: Hello "${demo}"

//To expand an expression Groovy uses double quotes, slashy and dollar slashy.

String multiLine='''With three  Single Quotes
In Groovy we can write
Multi-Line-String'''

3.Double Quotes:These are often used to define String expression.

int value=12
println "He bought ${value} egg "   //Output: He bought 12 egg

println "He paid \$${value} for that"   //Output: He paid $12 for that

//I have used the escape  character to print $ symbol since groovy uses that for embedding expressions.you don't have to escape $ if you use slashes, as you'll see soon.

String multiLine="""With three  Double Quotes
In Groovy we can write
Multi-Line-String"""

4.Slashy:These are often used for regular expression.


int value=12
String demo=/he paid $${value} for that/
println demo   //Output: he paid $12 for that

//Look here we don't have to escape $ symbol

String multiLine=/With slashy string
In Groovy we can write
Multi-Line-String/

5.Dollar Slashy:It is almost same as slashy string but with slightly different escaping rules .The biggest advantage of this is that we don’t even have to escape slash(‘/’) which results in a much cleaner regular expressions but you can use ‘$$’ to escape a ‘$’ or ‘$/’ to escape a slash if needed.


int value=12
String demo=$/he paid $ ${value} for one orange/$
println demo   // Output :he paid $ 12 for one orange

String demo1=$/he paid $$ ${value} for one orange/$
println demo1   // Output: he paid $ 12 for one orange

String demo2=$/Here evaluation will not take place $${value}, as we have escaped $ with $ /$
println demo2  
// Output: Here evaluation will not take place ${value}, as we have escaped $ with $

String demo3=$/what would you like to have tea/coffee/$
println demo3   //Output:what would you like to have tea/coffee

String demo4=$/what would you like to have tea$/coffee/$
println demo4   //Output:what would you like to have tea/coffee

//you can see that we can have a much cleaner Regex using dollar-slashy string.

String multiLine=$/With dollar-slashy string
In Groovy we can write
Multi-Line-String/$

I hope it helps, feel free to ask if you have any queries

Posted in Grails

Groovy : tokenize() vs split()

Posted by on March 14th, 2013
  1. The split() method returns a string [] instance and the  tokenize() method returns a List instance
  2.  tokenize() ,which returns a List ,will ignore empty string (when a delimeter appears twice in  succession) where as split() keeps such string.
    String testString = 'hello brother'
    assert testString.split() instanceof String[]
    assert ['hello','brother']==testString.split() //split with no arguments
    assert['he','','o brother']==testString.split('l')
    // split keeps empty string
    assert testString.tokenize() instanceof List
    assert ['hello','brother']==testString.tokenize() //tokenize with no arguments
    assert ['he','o brother']==testString.tokenize('l')
    //tokenize ignore empty string
    
  3. The tokenize() method uses each character of a String as delimeter where as split()  takes the entire string as  delimeter
    String  testString='hello world'
    assert ['hel',' world']==testString.split('lo')
    assert ['he',' w','r','d']==testString.tokenize('lo')
    
  4. The split()  can take regex as delimeter  where as  tokenize does not.
    String testString='hello world 123 herload'
    assert['hello world ',' herload']==testString.split(/\d{3}/)
    

    I hope it helps, feel free to ask if you have any queries

Posted in Grails

Script to display Git commits for creating time sheet.

Posted by on February 27th, 2013

We use “git log” many times a day while using Git in our projects. Sometimes we need to list Git commits between specific dates. Although, Git provides command to do this but the syntax is too long to type.

So I created a script named timesheet, which facilitates us to display Git commits between two specific dates or after a specified date in prettified one line format for a specific author via very simple syntax. Below is the timesheet script:

   #!/bin/bash

   TODAY=`date +%Y%m%d`
   EXPECTED_ARGS=1
   E_BADARGS=65
   AUTHOR_NAME_REGEX=".*"
   DATE_REGEX="[1-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]"
   DAY_REGEX="[0-3][0-9]"
   if [ $# -lt $EXPECTED_ARGS ]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short
   fi

   if [[ $# -eq $EXPECTED_ARGS && $1 =~ $AUTHOR_NAME_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --author=$1
   fi

   if [[ $# -eq $EXPECTED_ARGS && $1 =~ $DATE_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1}
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 2 && $1 =~ $DATE_REGEX && $2 =~ $AUTHOR_NAME_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1} --author=$2
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 2 && $1 =~ $DATE_REGEX && $2 =~ $DATE_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1} --before={$2}
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 3 && $1 =~ $DATE_REGEX && $2 =~ $DATE_REGEX && $3 =~ $AUTHOR_NAME_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1} --before=${2} --author=$3
   fi

   if [[ $# -eq $EXPECTED_ARGS && $1 =~ $DAY_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1-%m-%Y}
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 2 && $1 =~ $DAY_REGEX && $2 =~ $DAY_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1-%m-%Y} --before={$2-%m-%Y}
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 2 && $1 =~ $DAY_REGEX && $2 =~ $AUTHOR_NAME_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1-%m-%Y} --author=$2
   fi

   if [[ $# -gt $EXPECTED_ARGS && $# -eq 3 && $1 =~ $DAY_REGEX && $2 =~ $DAY_REGEX && $3 =~ $AUTHOR_NAME_REGEX ]]
   then
       git log --pretty="short" --format=%Cblue%h%' 'Cgreen%an[%ad]%' 'Creset%s%n --date=short --after={$1-%m-%Y} --before={$2-%m-%Y} --author=$3
   fi

Installation
In case of Ubuntu

  1. Open the terminal.
  2. Open the file .gitconfig in your home directory using your favorite text editor. (e.g: gedit, vim, vi)
  3. Check that the script file has executable permissions. (if not change via chmod command)
  4. Create an alias for the script in .gitconfig as shown below:
    [alias]
    timesheet = ! <PATH_TO_SCRIPT_FILE>/timesheet
     

Usage
Some of the usages are given below:

   git timesheet
   git timesheet <START_DAY_OF_CURRENT_MONTH>
   git timesheet <START_DAY> <END_DAY>
   git timesheet <START_DATE>
   git timesheet <START_DATE> <END_DATE>
   git timesheet <AUTHOR_NAME>
   git timesheet <START_DAY> <AUTHOR_NAME>
   git timesheet <START_DAY> <END_DAY> <AUTHOR_NAME>
   git timesheet <START_DATE> <AUTHOR_NAME>
   git timesheet <START_DATE> <END_DATE> <AUTHOR_NAME>

Example

git timesheet 15 17
or
git timesheet 2013-02-15 2013-02-17
or
git timesheet 15 17 <AUTHOR_NAME>

Note: One can specify dates as 15 or 17 only for current month otherwise dates should be in yyyy-mm-dd (2013-02-15) format.

Please share your feedback and suggestions.


Read more about timesheet script on GitHub »



Puneet Behl
puneet.behl@intelligrape.com
https://twitter.com/puneetbhl
http://in.linkedin.com/in/puneetbhl

Posted in git, Grails, Linux

JavaScript: Hex String To Int64 conversion (similar to Int64.parse)

Posted by on December 30th, 2012

Recently in our Node.js application we had a task where we needed to convert the Windows hexadecimal Live Id (lid) to sighed 64 bit Integer such that it can be used in the API calls. But there was no direct way to convert that in JavaScript, but here i will discuss the workaround we took.

 

The problem with 64 bit Integer in JavaScript

Though javaScript numbers are 64 bit but they only use 53 bits to store the real value(mantissa), rest bits are used for exponent. Hence this makes holding of 64bit integer impossible in JavaScript.

 

The workaround Solution

The workaround is to use String/Arrays to hold large numbers and perform arithmetic operations on that. The final result has to be saved in a string as we can never save it as number data type. I know it is dirty, but that’s the only way.

 

Example: Converting hex windows live id to Integer Live Id (Signed 64bit Integer)

Following code will convert the received hex lid to intLid:

var lidHex = "b4fb0acfc47086c1"; //The Input Hex Number.
var lid64 = new HexStringToInt64StringConverter(true).convert(lidHex);  //"true" is passed for Signed Conversion.
console.log(lid64); // output: -5405715040257931583

Note: Implementation of HexStringToInt64StringConverter is discussed below.

 

Example: Converting hex number to Integer (Unsigned 64bit Integer)

Following code will convert the received hex lid to intLid:

var intHex = "b4fb0acfc47086c1"; //The Input Hex Number.
var int64 = new HexStringToInt64StringConverter(false).convert(intHex);  //"false" is passed for UnSigned Conversion.
console.log(int64); // output: 13041029033451620033

Note: Implementation of HexStringToInt64StringConverter is discussed below.

 

Implementation: HexStringToInt64StringConverter

This converter is implemented with following points in mind:

  1. 2′s Complement Signed Representation
  2. Number represented in Array for arithmetic manipulations.
  3. All Powers of 2 which are impossible to calculate in JavaScript are pre-calculated and hard coded for faster conversions.
  4. Output number to be represented as a string.
  5. Both signed and unsigned conversions.

 

function HexStringToInt64StringConverter(signed) {
    var hexCode = {
        '0':"0000",
        '1':"0001",
        '2':"0010",
        '3':"0011",
        '4':"0100",
        '5':"0101",
        '6':"0110",
        '7':"0111",
        '8':"1000",
        '9':"1001",
        'a':"1010",
        'b':"1011",
        'c':"1100",
        'd':"1101",
        'e':"1110",
        'f':"1111"
    };
    var preComputedLongMath = {
        "20":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        "21":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
        "22":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
        "23":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8],
        "24":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6],
        "25":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2],
        "26":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 4],
        "27":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 8],
        "28":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 6],
        "29":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 1, 2],
        "210":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 4],
        "211":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 4, 8],
        "212":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 9, 6],
        "213":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1, 9, 2],
        "214":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 3, 8, 4],
        "215":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 7, 6, 8],
        "216":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 5, 5, 3, 6],
        "217":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 0, 7, 2],
        "218":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 2, 1, 4, 4],
        "219":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 4, 2, 8, 8],
        "220":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 4, 8, 5, 7, 6],
        "221":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 9, 7, 1, 5, 2],
        "222":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 9, 4, 3, 0, 4],
        "223":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 3, 8, 8, 6, 0, 8],
        "224":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 7, 7, 7, 2, 1, 6],
        "225":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 5, 5, 4, 4, 3, 2],
        "226":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 1, 0, 8, 8, 6, 4],
        "227":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 4, 2, 1, 7, 7, 2, 8],
        "228":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 6, 8, 4, 3, 5, 4, 5, 6],
        "229":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 3, 6, 8, 7, 0, 9, 1, 2],
        "230":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 3, 7, 4, 1, 8, 2, 4],
        "231":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 4, 7, 4, 8, 3, 6, 4, 8],
        "232":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 9, 4, 9, 6, 7, 2, 9, 6],
        "233":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 5, 8, 9, 9, 3, 4, 5, 9, 2],
        "234":[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 1, 7, 9, 8, 6, 9, 1, 8, 4],
        "235":[0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 5, 9, 7, 3, 8, 3, 6, 8],
        "236":[0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 7, 1, 9, 4, 7, 6, 7, 3, 6],
        "237":[0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 7, 4, 3, 8, 9, 5, 3, 4, 7, 2],
        "238":[0, 0, 0, 0, 0, 0, 0, 0, 2, 7, 4, 8, 7, 7, 9, 0, 6, 9, 4, 4],
        "239":[0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 9, 7, 5, 5, 8, 1, 3, 8, 8, 8],
        "240":[0, 0, 0, 0, 0, 0, 0, 1, 0, 9, 9, 5, 1, 1, 6, 2, 7, 7, 7, 6],
        "241":[0, 0, 0, 0, 0, 0, 0, 2, 1, 9, 9, 0, 2, 3, 2, 5, 5, 5, 5, 2],
        "242":[0, 0, 0, 0, 0, 0, 0, 4, 3, 9, 8, 0, 4, 6, 5, 1, 1, 1, 0, 4],
        "243":[0, 0, 0, 0, 0, 0, 0, 8, 7, 9, 6, 0, 9, 3, 0, 2, 2, 2, 0, 8],
        "244":[0, 0, 0, 0, 0, 0, 1, 7, 5, 9, 2, 1, 8, 6, 0, 4, 4, 4, 1, 6],
        "245":[0, 0, 0, 0, 0, 0, 3, 5, 1, 8, 4, 3, 7, 2, 0, 8, 8, 8, 3, 2],
        "246":[0, 0, 0, 0, 0, 0, 7, 0, 3, 6, 8, 7, 4, 4, 1, 7, 7, 6, 6, 4],
        "247":[0, 0, 0, 0, 0, 1, 4, 0, 7, 3, 7, 4, 8, 8, 3, 5, 5, 3, 2, 8],
        "248":[0, 0, 0, 0, 0, 2, 8, 1, 4, 7, 4, 9, 7, 6, 7, 1, 0, 6, 5, 6],
        "249":[0, 0, 0, 0, 0, 5, 6, 2, 9, 4, 9, 9, 5, 3, 4, 2, 1, 3, 1, 2],
        "250":[0, 0, 0, 0, 1, 1, 2, 5, 8, 9, 9, 9, 0, 6, 8, 4, 2, 6, 2, 4],
        "251":[0, 0, 0, 0, 2, 2, 5, 1, 7, 9, 9, 8, 1, 3, 6, 8, 5, 2, 4, 8],
        "252":[0, 0, 0, 0, 4, 5, 0, 3, 5, 9, 9, 6, 2, 7, 3, 7, 0, 4, 9, 6],
        "253":[0, 0, 0, 0, 9, 0, 0, 7, 1, 9, 9, 2, 5, 4, 7, 4, 0, 9, 9, 2],
        "254":[0, 0, 0, 1, 8, 0, 1, 4, 3, 9, 8, 5, 0, 9, 4, 8, 1, 9, 8, 4],
        "255":[0, 0, 0, 3, 6, 0, 2, 8, 7, 9, 7, 0, 1, 8, 9, 6, 3, 9, 6, 8],
        "256":[0, 0, 0, 7, 2, 0, 5, 7, 5, 9, 4, 0, 3, 7, 9, 2, 7, 9, 3, 6],
        "257":[0, 0, 1, 4, 4, 1, 1, 5, 1, 8, 8, 0, 7, 5, 8, 5, 5, 8, 7, 2],
        "258":[0, 0, 2, 8, 8, 2, 3, 0, 3, 7, 6, 1, 5, 1, 7, 1, 1, 7, 4, 4],
        "259":[0, 0, 5, 7, 6, 4, 6, 0, 7, 5, 2, 3, 0, 3, 4, 2, 3, 4, 8, 8],
        "260":[0, 1, 1, 5, 2, 9, 2, 1, 5, 0, 4, 6, 0, 6, 8, 4, 6, 9, 7, 6],
        "261":[0, 2, 3, 0, 5, 8, 4, 3, 0, 0, 9, 2, 1, 3, 6, 9, 3, 9, 5, 2],
        "262":[0, 4, 6, 1, 1, 6, 8, 6, 0, 1, 8, 4, 2, 7, 3, 8, 7, 9, 0, 4],
        "263":[0, 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8],
        "264":[1, 8, 4, 4, 6, 7, 4, 4, 0, 7, 3, 7, 0, 9, 5, 5, 1, 6, 1, 6],
        "265":[3, 6, 8, 9, 3, 4, 8, 8, 1, 4, 7, 4, 1, 9, 1, 0, 3, 2, 3, 2]
    };
    if (typeof(signed) != 'boolean') signed = false;
    function toBinary(hex) {
        hex = hex.toLowerCase();
        var binary = "";
        for (var i = 0; i < hex.length; i++) {
            binary += hexCode[hex[i]];
        }
        return binary;
    }

    function to1nsComplement(binary) {
        var compliment = "";
        for (var i = 0; i < binary.length; i++) {
            compliment += (binary.charAt(i) == "1" ? "0" : "1");
        }
        return compliment;
    }

    function arrayAdd(a, b) {
        var carry = 0;
        var number = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = 19; i >= 0; i--) {
            number[i] = a[i] + b[i] + carry;
            if (number[i].toString().length > 1) {
                carry = parseInt(number[i].toString().substring(0, number[i].toString().length - 1), 10);
                number[i] = parseInt(number[i].toString().substring(number[i].toString().length - 1), 10)
            } else {
                carry = 0;
            }
        }
        return number;
    }

    function removeZeroPad(number) {
        var lock = false;
        var output = [];
        for (var i = 0; i < number.length; i++) {
            if (lock) {
                output.push(number[i]);
            } else {
                if (number[i] != 0) {
                    lock = true;
                    output.push(number[i]);
                }
            }
        }
        return output;
    }

    function binaryToDec(binary) {
        var negative = false;
        if (signed && (binary.charAt(0) == 1)) {
            negative = true;
        }
        if (signed) {
            binary = binary.substring(1);
            if (negative) {
                binary = to1nsComplement(binary);
            }
        }
        var pos = 0;
        var number = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = binary.length - 1; i >= 0; i--) {
            if (binary.charAt(i) == 1) {
                number = arrayAdd(number, preComputedLongMath["2" + pos])
            }
            pos++;
        }
        if (negative) {
            number = removeZeroPad(arrayAdd(number, preComputedLongMath["20"]));
            number.splice(0, 0, "-");
        } else {
            number = removeZeroPad(number);
        }
        return number.join("");
    }

    this.convert = function (hex) {
        var binary = toBinary(hex);
        return binaryToDec(binary);
    };
}

Hope it helps!!
Regards
Kushal Likhi

Posted in Grails

Using Category in groovy

Posted by on November 30th, 2012

In one of my projects, I needed to save file from a particular url. I found a groovier way of doing this using category.

class FileBinaryCategory {
    def static leftShift(File file, URL url) {
        url.withInputStream {is ->
            file.withOutputStream {os ->
                def bs = new BufferedOutputStream(os)
                bs << is
            }
        }
    }
}

Here, I created a category class and created a static method named leftShift inside it. Here is how I used the category to download the file.

File download(String address) {
        def file = File.createTempFile(address.encodeAsMD5(), ".zip")
        use(FileBinaryCategory) {
            file << address.toURL()
        }
        return file
}

A category class consists of static methods. The first argument of the method defines the type to which that method is applied. In my case, the first argument is of type File.
The advantage of using category is that it can be applied to a specific part of the code by using the use keyword.

In line 4, the static method leftShift is called and a temporary file is passed as first argument and address.toURL() is passed as the second argument. The leftShift method simply copies the content from given address to the file.

Grails provides @Category annotation to achieve the same. You can find more about it here.

Raj Gupta
raj.gupta@intelligrape.com
@rajdgreat007

Posted in Grails, Groovy

4 Principles of well-designed web UI

Posted by on November 30th, 2012

Web Designing is nowadays not only just the way to promote our product & services, but is designed and coded to make the website user friendly. It guides user to learn and enjoy what they are doing which makes user to visit your website regularly and explore what you have to share.

Here are few points :

  1. Placements : Placement of content is one of the most important part of designing which makes user attract or ignore your web page.  A good design is with heading, subheadings, paragraph, bullets etc. and their proper usage.
  2. Proper Vocabulary : The heading, subheading, forms, menu, links should be named according to users understanding  with the most common terms, and should not be named according to user’s likes and creativity.
  3. Typography and Whitespace : The usage of fonts and whitespace is the most important thing on the webpage, which makes the user comfortable/uncomfortable with your webpage. Your fonts should have sufficient whitespace according to your design, so that things don’t become hoch-poch and user simply gets what your website speaks.
  4. Flow : The other most important thing is flow of your page, like how your content is placed. For example – if you are working with an NGO site, the donate button should be placed on the first half of your page from the top, and should be highlighted.

Thanks.
Rajan Shergill
rajan@intelligrape.com
https://twitter.com/RajanShergill3

Create game Leaderboard using sqlProjection

Posted by on November 8th, 2012

Recently I was working on a Facebook game application using Grails 2.0 and Postgres database. The use case was to show the game leaderboard with ranks of the players. Players with same score should be given same rank and next player rank should be incremented rank of last player. Here is the sample data for players and expected result:
game score

There is a rank() function in Postgres which solved my problem. Here is the sample query :

select rank() over(order by score desc) as rnk, name, score from player

The good news is that Grails 2.2 supports sqlProjection where you can use native sql projections like this :

Player.createCriteria().list{
  projections {
      sqlProjection ('rank() over(order by score desc) as rnk',
                     ['rnk'], [org.hibernate.Hibernate.INTEGER])
       property('name')
       property('score')
    }
  }
.each {  println "${it[0]} \t ${it[1]} \t ${it[2]}"}

If you are using older version of Grails then you can go with following alternatives:

  • Using sessionFactory bean and createSQLQuery
  • String query="select rank() over(order by score desc) as rnk, name, score from player"
    //inject sessionFactory bean object (def sessionFactory)
    sessionFactory.currentSession.createSQLQuery(query).list()
    .each {  println "${it[0]} \t ${it[1]} \t ${it[2]}"}
    
  • Using hibernate criteria query
  • /* import org.hibernate.Hibernate
    import org.hibernate.type.Type
    import org.hibernate.criterion.Projections
    import org.hibernate.criterion.Restrictions */
    
    sessionFactory.currentSession.createCriteria(Player)
                    .setProjection(Projections.projectionList()
                    .add(Projections.sqlProjection(
                                     "rank() over(order by score desc) as rnk",
                                     ["rnk"] as String[], 
                                     [Hibernate.INTEGER] as Type[]))
                    .add(Projections.property("name"))
                    .add(Projections.property("score")))
             .list()
             .each {println "${it[0]} \t ${it[1]} \t ${it[2]}"}
    

I have not been able to find a solution to find rank of specific user without loading all the records/rows and doing a groovy find on the result. The rank function assigns rank to each row based on the final result set returned by the query. So if you add a restriction to select only specific player’s rank, it will be always 1 (as the final result set will have only one record).

Hope you will share a better way to find rank of specific user :)

Cheers!
~~Bhagwat Kumar~~
bhagwat(at)intelligrape(dot)com
http://twitter.com/bhagwatkumar
http://in.linkedin.com/in/bhagwatkumar

Posted in Database, GORM, Grails

Grails GSP tag: grep

Posted by on October 31st, 2012

The other day I was reading the Grails docs and I came across a useful GSP tag: grep. I have been using Grails for over 3 years now but just recently got to see this new tag which has eased my life a bit in situations where the list of objects have to be filtered and iterated at the same time to perform some operations on them. The GSP ‘grep’ tag (equivalent to the ‘grep’ method in Groovy) filters the list on a given condition and iterates over the filtered list allowing you to do some operations on the objects (or whatever you want to do with the filtered objects).

I will give you a small example: Suppose we have a list of Person objects. You want to display the names starting with A, B, C and so on in different color schemes. How would you do it?

One implementation is to send different lists from the controllers (this would mean sending 26 lists i.e. one list for each character in the English alphabet) and render them in different color schemes. The other way would be to iterate over the Persons list in the GSP and have  different <g:if>…<:g:elseif> statements (for each character).

There is another smarter way: you could also use the ‘findAll‘ method of the List in the GSP <g:each> tag’s ‘in’ attribute i.e <g:each in=${personList.findAll {it.name.startsWith(‘A’)}} var=”person”> … </g:each>.

Similarly, we can use ‘grep’ tag here. We can filter out the list like this: <g:grep in=”${personList.name}” filter=”~/^A.*/”> … </g:grep>.

Notice the use of ‘name‘ field of the Person object in the ‘in‘ attribute of the grep tag. Also, the attribute ‘filter’ takes many forms of filter options; here we are using regex to filter the persons with the name starting with ‘A’.

I am not saying that this tag provides some new functionality which we could not have achieved by any other means but this tag makes it easier to filter out the lists on some specific parameters.

You can read more about this tag here. Also you can read about the Groovy GDK’s grep method usage here to see how and in what scenarios you can use this tag.

Hope this helps !!

- Abhishek Tejpaul
abhishek@intelligrape.com

Posted in Grails