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

Amit Jain

http://www.IntelliGrape.com

Posts by Amit Jain:

  • JQuery : create URL query string from JSON/Array

    04 May 2011 in Javascript/Ajax/JQuery

    Hi Friends,

    Read the rest of this entry »

    • Share/Bookmark
  • 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

    • Share/Bookmark
  • 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

    • Share/Bookmark
  • 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

    • Share/Bookmark
  • 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

    • Share/Bookmark
  • 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/

    • Share/Bookmark
  • 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

    • Share/Bookmark
  • 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/

    • Share/Bookmark
  • jQuery: Floating message box which disappears in few seconds

    14 Sep 2010 in Javascript/Ajax/JQuery

    Hi Friends,

    Recently in one of the project I was working on, had a long web page and updates used to happen only through ajax calls that means no page refresh. The status messages used to appear on the top of the page, the user had no way but to scroll up to see the status message. There we thought of using floating message that always appears on the top and floats as and when page is scrolled and also disappears itself after specified amount of time. I found one blog by Roshan that helped a lot, which I tweaked a little as given below.

    CSS code to be added :

    #message_box {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1000;
        background: #ffc;
        padding: 5px;
        border: 1px solid #CCCCCC;
        text-align: center;
        font-weight: bold;
        width: 99%;
    }

    Html code containing message : :-

    <div id="message_box">Your message goes here</div>

    Call setupMessageBox() when message is available.

    <script type="text/javascript">
      var updateTimer = 0;
      function setupMessageBox(){
        showMessage(); //displays message on page load
        jQuery(window).scroll(function() {
           showMessage();
        });    
        clearTimeout(updateTimer);
        activateTimer();
      });
     
      function activateTimer() {
        updateTimer = setTimeout('jQuery("#message_box").remove()', 5000);
      }
     
      function showMessage(){
          jQuery('#message_box').animate({top:jQuery(window).scrollTop() + "px" }, {queue: false,duration:350});
      }
    </script>

    Hope this helped!

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

    http://www.intelligrape.com

    • Share/Bookmark
  • Grails : load proxy domain objects

    26 Jul 2010 in Grails

    Hi Friends,

    I was going through grails docs, encountered a method called load(), found it really useful thought would share with you. What load() does is, it creates a proxy object and doesn’t retrieve the record from the database until property other than id is accessed.
    Let us consider a scenario, where we have id of a Object “subject” and students of that subject needs to be listed. So we would generally do something like as given below:

    Subject subject = Subject.get(subjectId)
    Student.findBySubject(subject)

    In the above code, we had to load subject unnecessarily where its ‘id’ should have been sufficient. Now, with load no extra queries are required.

    Subject subject = Subject.load(subjectId)  //creates a proxy object, not retrieved from database 
    Student.findBySubject(subject)

    And same when used with criteria queries

    Student.list{
      eq('subject', Subject.load(subjectId))
      ...
    }

    Thanks to the grails development team for all their efforts!

    Cheers!!

    ~~Amit Jain~~
    amit@intelligrape.com

    http://www.IntelliGrape.com

    • Share/Bookmark