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

Amit Jain

http://www.IntelliGrape.com

Posts by Amit Jain:

  • jQuery : Associate data with dom element

    21 Sep 2012 in Javascript/Ajax/JQuery

    There are times when we need to associate data with the DOM element say td, li, div etc. I used to sometimes provide attribute ‘rel’ to html tag, then access it using $(‘divId’).attr(‘rel’). This worked when we want to associate only one property, but doesn’t work so well when there are multiple properties to be associated with the same element. And I personally never liked this approach as there was no name given to the type of data attached.

    Recently I found that jQuery provides a method called data(), which can be used to associate multiple data with the same element. Lets take a look at the example given below :

    <div id='studentDetail' data-age='24' data-name='amit'>
    ......
    </div>
    
    <script type="text/javascript">
    
     $('#studentDetail').data('age')  // output : 24
     $('#studentDetail').data('name')  // output : amit
    
     $('#studentDetail').data('course', 'MCA')  // Associate new data to the element
     $('#studentDetail').data('course')  // output : MCA
    
     $('#studentDetail').data('course-duration', '3 Years')  // Associate new data to the element
     $('#studentDetail').data('course-duration')  // output : 3 Years
    </script>
    
    

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

  • Cool Spock Ignore/IgnoreRest annotations

    31 Aug 2012 in Grails&Groovy&Test

    While writing a test case, we are generally interested in executing only the one we are working on. With JUnit test case in grails we could say “grails test-app <ClassName>.<currentTestCase>”.  However it doesn’t work with spock specification’s.
    Spock framework provides multiple cool annotations,  following two annotations can be used to speed up writing/executing test case in question :

    1. @IgnoreRest : Ignores all feature methods not carrying this annotation. Useful for quickly running just a single method.
    2. @Ignore : Ignores a feature method.

    So while writing specification I prefer @IgnoreRest instead of giving even the class name to be tested and remove it later once I am done with the specification. Similarly If there is a specification that takes good time to execute and doesn’t need to be tested right now, we can annotate it with @Ignore, to save some time.


    ~~Amit Jain~~

    amit@intelligrape.com

  • JQuery : create URL query string from JSON/Array

    04 May 2011 in Javascript/Ajax/JQuery

    Hi Friends,

    Read the rest of this entry »

  • Groovy: Few ways to convert string into enum

    15 Apr 2011 in Groovy

    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

  • Remote-pagination : support for javascript events added

    14 Mar 2011 in Grails

    Hi Friends,

    I have released the version 0.2.5 of Remote-Pagination, which now provides the support for all the events as supported by grails tags like remote-link.  Events supported are listed below :

    1. onSuccess  – The javascript function to call if successful
    2. onFailure  – The javascript function to call if the call failed
    3. on_ERROR_CODE – The javascript function to call to handle specified error codes (eg on404=”alert(‘not found!’)”). With Prototype, this prevents execution of onSuccess and onFailure.
    4. onUninitialized  – The javascript function to call the a ajax engine failed to initialise
    5. onLoading  – The javascript function to call when the remote function is loading the response
    6. onLoaded  – The javascript function to call when the remote function is completed loading the response
    7. onComplete  – The javascript function to call when the remote function is complete, including any updates.

    Version 0.2.5  fixes the jira issue GRAILSPLUGINS-2804.

    For any new feature request or a bug please raise a jira here.

    Thanks for all your support!

    ~~Amit Jain~~

    amit@intelligrape.com

    http://www.IntelliGrape.com

  • Using groovy execute bash scripts

    15 Feb 2011 in Groovy

    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

  • Grails criteria query : ‘createAlias’ made it easy

    17 Jan 2011 in Grails

    Hello friends,

    In my grails project, I was finding it difficult to write a query using criteria which can be read as ‘list all customers whose current account balance is more than minimum account balance of that customer’. The simplified form of the domain is given below :

    class Customer {
       String name
       Account account
       BigDecimal minAccountBalance
       ...
    }
    
    class Account {
       BigDecimal currentBalance
       ...
    }
    

    As far as my understanding goes, criteria provides comparison between the fields in the same domain but I needed to compare values between two domains. After spending some time on it, I could make it work using ‘createAlias’ statement. Before you go through the query, please have a look at one of the nice blog written by Rob Fletcher which is available here to understand what ‘createAlias’ does.

    Here is the query :

    Customer.createCriteria().list(){
          createAlias('account', 'acc')
          gtProperty('acc.currentBalance', 'minAccountBalance')
        }
    

    Hope this helped!

    Cheers!

    ~~Amit Jain~~
    amit@intelligrape.com

    http://www.IntelliGrape.com

  • Database Backup Script for windows

    14 Dec 2010 in Database

    In one of the project I am working on, the application needs to be deployed on windows server. To take the database backup, I wrote the script which does the following :

    1. Takes database dump and copy it to the backup folder.
    2. Zip that backup file and rename it to the format “YYYYMMDD_HHMMSS”
    3. Removes  all the backups older than 30 days.

    I used mysqldump command to take database backup. To zip the backup file using the command line, I found 7-zip (download) which is freely available.  We need to have forfiles.exe (download) which enables us to remove old backup files (say older than 30 days).

    @echo off
    CLS
    set hour=%time:~0,2%
    if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
    set min=%time:~3,2%
    if "%min:~0,1%" == " " set min=0%min:~1,1%
    set secs=%time:~6,2%
    if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
    set year=%date:~-4%
    set month=%date:~3,2%
    if "%month:~0,1%" == " " set month=0%month:~1,1%
    set day=%date:~0,2%
    if "%day:~0,1%" == " " set day=0%day:~1,1%
    set datetimef=%year%%month%%day%_%hour%%min%%secs%
    "MYSQL_BIN_PATH\mysqldump" --user=root --password=MY_PASSWORD MY_DATABASE_NAME > "BACKUP_FOLDER_PATH\backup.sql"
    "7ZIP_EXE_PATH\7z" a -tzip "BACKUP_FOLDER_PATH\"%datetimef%".zip" "BACKUP_FOLDER_PATH\backup.sql"
    del "BACKUP_FOLDER_PATH\backup.sql"
    "FORFILES_EXE_PATH\forfiles.exe" /p BACKUP_FOLDER_PATH /s /m *.* /d -30 /c "cmd /c del /q @path
    

    Prerequisites for the above script to work would be :-

    1. Mysql and 7zip installed.
    2. Forfiles.exe is downloaded
    3. All the Path’s in script are replaced correctly.

    I also used a background job to run this script automatically every hour on the working days. Though same can be achieved with windows scheduler too.

    Hope this helped.

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

    http://intelligrape.com/

  • Jquery : map and grep functions

    15 Nov 2010 in Javascript/Ajax/JQuery

    Hi friends,

    I was going through some utility funcitons being provided by jQuery. Found few methods like grep, map very userful that saves me from writing loops. I could relate them with grep, collect respectively as provided by Groovy, thought would share with you.

    I will be taking examples with JSON objects say Student.
    grep()

    var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
    jQuery.grep(students,function(student){ return student.id>1});
    
    //Output :  [{'id':2, 'name':'ankit'}]
    
    jQuery.grep(students,function(student){ return student.id>1}, true) // invert the results
    
    //Output : [ {'id':1, 'name':'amit'}]
    
    

    map()

     var students = [ {'id':1, 'name':'amit'},{'id':2, 'name':'ankit'}];
    jQuery.map(students,function(student){ return student.name=student.name.toUpperCase()});
    
    //Output : ["AMIT", "ANKIT"]
    //Updated students list :  [ {'id':1, 'name':'AMIT'},{'id':2, 'name':'ANKIT'}];
    
    
    jQuery.map(students,function(student){ return student.greetings="HELLO " + student.name});
    
    //Output : ["HELLO AMIT", "HELLO ANKIT"]
    //Updated students list : [ {'id':1, 'name':'AMIT', 'greetings' : 'HELLO AMIT'},{'id':2, 'name':'ANKIT', 'greetings' : 'HELLO ANKIT'}]
    

    Hope this helped.

    ~~Amit Jain~~
    amit@intelligrape.com

  • Grails Liquibase plugin: dbDiff tool workaround

    12 Oct 2010 in Database&Grails

    The current project I am working on, is going through QA. At the same time development of the new features and bug fixing is on and we couldn’t afford to loose the test data. So synchronizing the state of the QA database with the development was becoming a pain. So we decided to use grails liquibase plugin.

    I found one great article by Jackob Kulzer. As explained by Jackob Kulzer, dbDiff tool in the plugin is hard coded to compare development and test environment databases. The other option available was to write every changeset manually. But I was afraid, what if I forget to update even a single changeset.

    I decided to write the script, which would overwrite my test database with the schema of the QA database. QA database was on another server. So I had to write multiple scripts to make it work. But once done it made my job really easy.

    Following are the scripts to be created:

    1. qaSchemaDump.sh (To be created on the development machine):

    
    #SSH to the server and execute generateSchema shell script.
    #Note: I had created password less login to the server.
    ssh amit@qa.myserver.net /home/amit/Scripts/generateSchema.sh
    
    #Copy QA Database schema to the development machine
    scp apg@qa.myserver.net:/home/amit/Scripts/qaDBSchema.sql /home/amit/Scripts/liquibase/qaDBSchema.sql
    
    #Import QA Database schema to test database using createTestDBFromQASchema.sql
    mysql -u root --password=myPassword < /home/amit/Scripts/liquibase/createTestDBFromQASchema.sql
    exit
    
    

    2. generateSchema.sh (To be created on the Server):

    
    /* Creates QA database schema */
    mysqldump --no-data --tables -u root --password=myPassword myQADatabase > /home/amit/Scripts/qaDBSchema.sql
    
    

    3. createTestDBFromQASchema.sql (To be created on the development machine):

    /* drop, create and then use the test database.*/
    drop database myTestDB; create database myTestDB;
    use myTestDB;
    
    /*Import the QA database schema to the newly created test database*/
    source /home/amit/Scripts/liquibase/qaDBSchema.sql
    exit
    
    

    Once all the above mentioned scripts are created, we just need to run ‘qaSchemaDump.sh’ and followed by ‘grails dbDiff’ and the changeset would be available to us on the console. Then copy this changeset, append it to changeLog.xml and commit it to the repository.

    With all this done, login to your QA/production server, take database backup and now we can run grails migrate-sql to confirm the sql that would be generated and then finally run ‘grails migrate’ to update QA/Production database.

    Thanks to Jackob Kulzer and Nathan Voxland (author of the plugin)

    Hope this helped!

    ~~Amit Jain~~
    amit@intelligrape.com

    http://www.IntelliGrape.com/