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

kushal

http://kushal.likhi.me

Posts by kushal:

  • Closure Caching For Increased Performance (.memoize())

    29 Dec 2011 in Grails& Groovy

    Well This is something awesome and can increase the performance of the project when used wisely. using the groovy .memoize() we can ask closures to perform kind of caching. This can boost up the performance of the system.

     

    _

    Note: This feature is available in groovy 1.8+

    Well Let me Explain this Using Examples

    Now suppose i have a function “distance” which calculates distance between two points.
    Hence for it instead of writing a function(Method) lets write a closure for it.

            def distance = {x1, y1, x2, y2 ->
                sleep(200)  //just to add a delay for demo purposes
                Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
            }
    
           //To Call It 5 Times
           5.times {
                def t1 = System.currentTimeMillis()
                println distance(100, 20, 400, 10)
                println "took: ${System.currentTimeMillis() - t1} milliseconds to execute"
            }
    

    Now if we will Run this the Output will be as follows:

    300.1666203960727
    took: 201 milliseconds to execute
    300.1666203960727
    took: 200 milliseconds to execute
    300.1666203960727
    took: 201 milliseconds to execute
    300.1666203960727
    took: 201 milliseconds to execute
    300.1666203960727
    took: 201 milliseconds to execute
    

    Each time this closure is called all statements are executed again and hence re-computation. But if set of inputs are same then technically output should be same. hence a type of caching will help.
    Also if several users are acessing the app then for each user if something is done again and again though the inputs are same then that is again a overhead, this issue can also be solved by memoizeing. :)

    Now lets Do it with .memoize()

            def distance = {x1, y1, x2, y2 ->
                sleep(200)  //just to add a delay for demo purposes
                Math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
            }.memoize() //Note now closure is memoized 
    
           //To Call It 5 Times
           5.times {
                def t1 = System.currentTimeMillis()
                println distance(100, 20, 400, 10)
                println "took: ${System.currentTimeMillis() - t1}"
            }
    

    Now the result is:

    300.1666203960727
    took: 202 milliseconds to execute
    300.1666203960727
    took: 1 milliseconds to execute
    300.1666203960727
    took: 1 milliseconds to execute
    300.1666203960727
    took: 0 milliseconds to execute
    300.1666203960727
    took: 0 milliseconds to execute
    

    We can definitely see the difference between time taken to execute.
    AND HURRAY, ALL REPETITIVE CALLS WITH SAME INPUT DATA ARE NOW CACHED AND HENCE INCREASED PERFORMANCE.

     

    Hope it helped
    Regards
    Kushal Likhi

    • Share/Bookmark
  • How to get Google Indexed Pages Count, and/or do Google searches through AJAX/programmatically

    Hi,
    Recently i had to get the count of the Pages Google has Indexed for a perticular web Site progmatically.
    In the process i found that Google offers an AJAX Search API to perform Google Searches.
    .
    Hence i Implemented a Class which does the same for me easily(Ajax Search in Google).
    And this Solution Does Google Searches programmatically and Also Give us the Indexed Pages Count.
    Note: Its Groovy Implementation, Similar can be done in JavaScript using Ajax though intent will remain the same.
    The class has been named GoogleAjaxSearch because it uses the Google AJAX Search API ;)

    Use Cases Are As Follows:

    //Case 1 Simple Search
    String searchQuery = "my search Query"
    GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
    println googleAjaxSearch.results //Type List<Expando>, Just print it to see available properties
    

    //Case 2: Get Number Of Indexed Pages in Google
    String searchQuery = "site:intelligrape.com"
    GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
    println googleAjaxSearch.estimatedResultCount
    

    //Case 3: Redo a search with same SearchQuery or a different Search Query
    String searchQuery = "search string"
    GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
    googleAjaxSearch.redo() //Re-Search with same query
    googleAjaxSearch.redo("New Query") // Re-Search With New Query
    

    //Case 4: All Details Available
    String searchQuery = "site:intelligrape.com"
    GoogleAjaxSearch googleAjaxSearch = new GoogleAjaxSearch(searchQuery)
    println googleAjaxSearch.estimatedResultCount //Gives the result count, indexed pages count
    println googleAjaxSearch.currentPageIndex    //Search result server side pagination - current page
    println googleAjaxSearch.results  //List<Expando> containing results
    println googleAjaxSearch.responseStatus //HTTP Status Code
    println googleAjaxSearch.responseDetails //Details for response, if any
    println googleAjaxSearch.searchQuery     //Search Query
    println googleAjaxSearch.moreResultsUrl // Url to hit for next Page of results
    println googleAjaxSearch.jsonResult // Complete raw JSON Result from google
    println googleAjaxSearch.pages  // Pagination Pages Details
    

    The Class Code Is As Follows:


    package myPackage.googleSearch
    
    import grails.converters.JSON
    
    class GoogleAjaxSearch {
    
        public String searchQuery
        public String responseDetails
        public String moreResultsUrl
        public String jsonResult
    
        public Integer responseStatus
        public Integer currentPageIndex
        public Integer estimatedResultCount
    
        public def pages
    
        public List<Expando> results = []
    
        private static final String ajaxSearchTarget = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=###SEARCHQUERY###&filter=0"
    
        public GoogleAjaxSearch(String searchQuery) {
            this.searchQuery = searchQuery
            search()
        }
    
        public GoogleAjaxSearch() {
            this(null)
        }
    
        public void redo() {
            search()
        }
    
        public void redo(String newSearchQuery) {
            this.searchQuery = newSearchQuery
            search()
        }
    
        private void search() {
            if (searchQuery) {
                URL url = new URL(ajaxSearchTarget.replace('###SEARCHQUERY###', searchQuery))
                URLConnection connection = url.openConnection()
                connection.setDoInput(true)
                InputStream inStream = connection.getInputStream()
                BufferedReader searchResultContent = new BufferedReader(new InputStreamReader(inStream))
                jsonResult = searchResultContent.getText()
                parseJsonAndPopulateObject()
            }
        }
    
        private void parseJsonAndPopulateObject() {
            def jsonArray = JSON.parse(jsonResult)
            this.responseStatus = Integer.parseInt(jsonArray.responseStatus as String, 10)
            this.responseDetails = jsonArray.responseDetails
            this.moreResultsUrl = jsonArray.responseData.cursor.moreResultsUrl
            this.currentPageIndex = Integer.parseInt(jsonArray.responseData.cursor.currentPageIndex as String, 10)
            this.pages = jsonArray.responseData.cursor.pages
            this.estimatedResultCount = Integer.parseInt(jsonArray.responseData.cursor.estimatedResultCount as String, 10)
            results = jsonArray.responseData.results.collect {
                new Expando(
                        content: it.content,
                        GsearchResultClass: it.GsearchResultClass,
                        titleNoFormatting: it.titleNoFormatting,
                        title: it.title,
                        cacheUrl: it.cacheUrl,
                        unescapedUrl: it.unescapedUrl,
                        url: it.url,
                        visibleUrl: it.visibleUrl
                )
            }
        }
    }
    

    Hope That Helps :)
    Regards
    Kushal Likhi

    • Share/Bookmark
  • Fast DB Management Through IDEA- Increase Productivity

    16 Sep 2011 in Grails

    Hi,

    well we can run SQL Queries and browse database through IDEA with a good GUI interface.

    It Just Requires Two Steps:
    1) Setup (One time)
    2)Usage (how to)


    A: Setup


    PART I
    1) Download the Database Navigator Tool From Intellij Repo -> Download Tool
    2) Then Execute in the Directory containing the downloaded file

    unzip DBN_9912.zip; cp -rfvp DBNavigator /opt/idea/plugins/

    assuming “/opt/idea” is the idea installation directory, Feel free to change this as required. :)
    3) Restart IDEA
    PART II
    4) Now in your IDEA Left Dock Bar You will see the DB Browser Tab(As shown in the image below)

    5) Click On That Tab
    6) Now in DBNavigator window click on Settings Button(The Last Button on the tools menu)
    7) On Connections Tab, Click on the “+” button to add the connection. Do the settings(One Time Step), Sample settings is shown below:

    ALL DONE :)


    B: USAGE


    Using is very simple,
    You can RUN SQL Queries with Auto-complete(hav’t tried this yet though).. :P
    See Database Schema and Content Inside Idea through a very Intiutive Interface. :)

    Here are the Screenshots for what all you can do:













    More Screen shots:

    Regards

    Kushal

    • Share/Bookmark
  • Increasing Productivity With The Right Hardware

    05 Sep 2011 in System

    Recently i upgraded my laptop to increase the productivity and to make it butterSmooth to work on even with the most demanding applications.
    so here is what i did:

    1) New High Speed Solid State Hard Drive

    2) Increased RAM.

    .

    why SSD???

    CPUs and GPUs thrive on being fed massive amounts of data in parallel, our hard drives aren’t so appreciative of our multitasking demands. And this is where SSDs truly shine.

    SSD’s have high Read/Write speeds, which just makes the FILE I/O operations lightning fast.

    It also helps in best utilization of your CPU, as it quenches the CPU’s thirst for data to be processed.

    Why RAM??

    I used to experience that if you run a grails application and open few instances of IDEA in your 64bit system, it used to go on swap, hence a couple of Gigs of extra RAM will not harm .. ;)

    .

    Hardware Aquired:

    1) OCZ Vertex 2 40GB SSD – Rs.5000/-

    2) 4GB DDR-3 Kingston Laptop RAM: Rs.1300/-

    3) 2.5″ External SATA Casing: Rs.200/-

    .

    Installation:

    its Petty simple, Just 2 steps procedure.

    1) Remove the old Ram and HDD

    2) Install the new Ones.. ;)

    And the Extracted 500GB HDD from my Laptop is converted into an External USB 500GB HDD using the 2.5″ HDD Casing. Hurray… ;)

    .

    The Exact Steps are as follows:

    1) Open the Laptop Back Cover

    2) Remove HDD mounting screws

    3) Remove OLD HDD

    4) install the new SSD

    5) Remove one existing 2GB RAM if no empty RAM slot present

    6) Install new 4GB Ram

    7) Close the Lid

    8) All Done.. install requires OS/Softwares to your new SSD

    Here are the illustrations:

    .

    P.S: My Laptop runs Like its been blessed with the alien technology.. :)

    Regards

    Kushal Likhi

    • Share/Bookmark
  • Zen Coding in IntelliJ IDEA

    26 Aug 2011 in Grails

    Recently i Found this cool thing(Zen Coding) which is also supported by IntelliJ IDEA.

    Long story short, Zen Coding is a shorthand notation for writing HTML/CSS, Few Examples are as Follows:

    Ex-1 Writing a nested Markup Quickly
    Now in IDEA lets open any gsp/html page and write:

    div#mainDivId>p+h1+p.classForP (After Writing this press TAB)
    

    AND You Will Get…….

    <div id="mainDivId">
        <p></p>
        <h1></h1>
        <p class="classForP"></p>
    </div>
    

    Magic…..
    The Zen Code string is self explanatory and also easy to desipher after looking at the output.. ;)

    Ex-2 Repeating Elements
    Now lets try this In gsp/html page,

    li*5 (Then press TAB as Before)
    

    And We Will Get…..

    <li></li><li></li><li></li><li></li><li></li>
    

    i.e: li is repeated 5 times, hence multiplying with a number ‘n’ repeates it ‘n’ number of times.

    EX-3 Assigning variable Id/Classes/anything
    Note:Item numbering with $ character: li.item$*3 will output ‘li’ tag three times, replacing $ character with item number.

    li.item$*3 (Press TAB as Always)
    

    And We Will Get…

    <li class="item1"></li><li class="item2"></li><li class="item3"></li>
    

    Note: Multiple ‘$’ characters in a row are used as zero padding, i.e.: li.item$$$ → li.item001
    Lets try this:

     li.item$$$*3 (Tab Again..)
    

    And We will Get…

    <li class="item001"></li><li class="item002"></li><li class="item003"></li>
    

    and So on…… Lots of possibilities here.. ;)

    Ex-4 Assigning class and id both together

    div#page.section.main
    

    And we will get…

    <div id="page" class="section main"></div>
    

    Ex-5: Custom Attributes
    lets try this…

    td[colspan=2]
    

    And we will get….

    <td colspan="2"></td>
    

    Ex-6: Abbreviation groups with unlimited nesting
    Lets try this…

    div#page>(div#header>ul#nav>li*4>a)+(div#page>(h1>span)+p*2)+div#footer
    

    And we will get..

    <div id="page">
             <div id="header">
                 <ul id="nav">
                     <li><a href=""></a></li>
                     <li><a href=""></a></li>
                     <li><a href=""></a></li>
                     <li><a href=""></a></li>
                 </ul>
             </div>
             <div id="page">
                <h1><span></span></h1>
                <p></p>
                <p></p>
            </div>
        <div id="footer"></div>
    </div>
    

    You can literally write a full document markup with just a single line. :) Awesome..

    Ex-7: Another Example Incorporating All we learnt :)
    Lets Try this…

    div#page>div.logo+ul#navigation>li*5>a
    

    And we will get…..

    <div id="page">
        <div class="logo"></div>
        <ul id="navigation">
                  <li><a href=""></a></li>
                  <li><a href=""></a></li>
                  <li><a href=""></a></li>
                  <li><a href=""></a></li>
                  <li><a href=""></a></li>
        </ul>
    </div>
    

    Regards
    Kushal Likhi
    Intelligrape Softwares

    • Share/Bookmark
  • Editable Label Tag and introduction to Effects Tag Lib

    Lately i had some spare time, hence decided to utilise it for developing some cool GUI elements.

    What is effects tag lib??

    It is just a new tag lib which is intended to contain some cool grails tags for GUI manipulations.
    new tags will be added to it on timely basis, this is the first post regarding this tag lib.

    Editable Lable

    this is the first tag in this tag lib. It is a cool GUI label which can be edited realtime.

    Features:
    1) Post-able as a form element.
    2) easy value manipulation and extraction.
    3) Tool Tip support.
    4) Validate-able using, just assign class as you assign to any text field for validation.
    5) style-able using css
    6) Default value and blank handling
    7) easy to use.

    Details about the tag
    tag usage:-

    <etl:editableLable />

    you can treat this tag as an input text field, it gives you similar behaviour

    attributes:
    1) name: for form support, the value is posted with the form with param.
    2) class: class to be applied, for styling and validation.
    3) id: id given to the input feild
    4) value: value to be displayed on the lable
    5) default: the value to be displayed in case user enters blank in the edit mode
    6) size: the size of the input feild
    7) tooltip: text to be displayed in tool tip. if nothing specified default tooltip text will be displayed. i.e. “click to edit”
    8] tooltipclass: class assigned for styling the tooltip as per the page needs
    NOTE: All attributes are not required.

    DEMO:-

    here is the demo to the tag:

    Next Addition

    # Image scroller filmstrip tag
    # vertical image slider tag
    # Editable paragraph tag
    # safe string tag
    # Drawable rounded border without images tag
    # auto sizing-resizing tag
    # relative positioning
    # image slider normal
    # picker tab(3X3) tag
    # tool tip provider tag
    # progress bar tag
    # slider tag
    # modal window
    # modless window
    # progress bar
    # more/less box
    # pie graph
    # bar graph
    keep looking………

    Download:

    Link coming soon!! within few days.. waiting for some more tags to be completed.

    Regards
    Kushal Likhi
    www.intelligrape.com

    • Share/Bookmark
  • GNOME GUI Integration w.r.t IDEA GUI Launcher

    13 Feb 2011 in Linux& System

    One of the important part of any Installer is integrating and defining launchers for GUI. This post will demonstrate adding entries in menu bar and panel, using scripts in context of creating a GUI launcher for IDEA IDE.

    currently IDEA does not come with any GUI Launcher but this does not mean that we cant have one. How cool it would be if we had an icon on the top panel to launch IDEA in Terminal mode.

    IDEA LAUNCHER IN PANEL ->


    Similarly an entry is also created in menu: application->programming->Idea
    Download: idea_desktop_Integration.tar.gz Check the installation guide below to see how to install

    PROBLEM STATEMENT:
    A program will be created to do IDEA GNOME GUI Integration, which launches IDEA in TERMINAL such that we can see whats happening in the background, that too with the ease of GUI one click quick launch. It requires following subtasks:

    1. Building Launch Environment for idea.sh: idea.sh is designed to launch in terminal with all PATH variables set for various SDK’s. if we try to launch it in a standalone terminal it will not work as environment is required. In this step we will generate the launch environment
    2. Adding Menu Bar Entry: in this we will add an entry to menu: application->programming->Idea using scripts, automated.
    3. Adding entry to panel: here we will add an entry for launcher in the quickLaunch panel on top of the screen.

    Building Launch Environment
    whenever terminal is launched it runs the .bashrc file which have the PATH variables to be set.
    but we cant execute .bashrc in standalone terminals i.e terminals with no command point as GUI always launches applications in standalone terminals.
    so the other option is:- extract all the PATH variables from .bashrc and create your own setup script for the terminal.
    this can be achieved by simple commands:-

    grep "export" ~/.bashrc |tee ~/.IDEALauncher

    this will extract all exported variables and make a file containing all of them in the home folder with the name .IDEALauncher
    and we can execute this script to set the path via command:

    chmod 777 ~/.IDEALauncher
    . ~/.IDEALauncher

    Now it has set all the path variables needed for the launch.

    the above mentioned task is stored in a file klaunch.sh and is the launcher start point. file is as follows:
    Note: UI and echo’s have been removed here to make it more readable, in attached file lot other stuff is there.

    # IDEA Launcher Script for gnome desktop integration.
    # By Kushal Likhi
    
    #GET settings of enviornment variables and create a shell script for those
    grep "export" ~/.bashrc |tee ~/.IDEALauncher
    
    #set enviornment variables
    chmod 777 ~/.IDEALauncher
    . ~/.IDEALauncher
    
    #launch IDEA
    `idea.sh`
    

    Setup Process
    adding menu bar entries and panel entries is a part of setup process and is as follows:

    “Everything in LINUX is a file”

    yes, and using the above saying all we have to do is: create/edit/add some files
    FOR Menu Entry we have to create a file: /usr/share/applications/idea.desktop and update cache to be safe
    the Script is as follows for the setup file:

    #IDEA Desktop integration setup file
    # (c) Kushal Likhi
    #Ver 1.0
    
    #clear screen for good clean looks
    clear
    
    #welcome message
    echo "-------------------WELCOME----------------------"
    echo ""
    echo " SETUP Program for IDEA GNOME Integration"
    echo " by: kushal likhi"
    echo ""
    echo "------------------------------------------------"
    
    #read IDEA installation dir path
    echo ""
    read -p "Enter IDEA Bin Location, press enter to keep default(/opt/idea/bin/), note: end path with '/':" ideahome
    
    if [ -z "$ideahome"]
    then
    	ideahome=/opt/idea/bin/
    else
    	echo "path set!"
    fi
    
    echo ""
    echo "Path set to: "$ideahome 
    
    #copy files
    echo ""
    echo "Generating launcher...."
    sudo cp -fv klaunch.sh $ideahome
    echo ""
    echo "copying Icons...."
    sudo cp -fv icon.png $ideahome
    echo ""
    
    #add menu entries
    echo "checking for /usr/share/applications"
    
    if [ -d "/usr/share/applications" ]
    then
    #found cache file
    echo "found"
    echo "Adding Entries...."
    
    #NOTE: echo here is used to create files, NOT display on console, '>' creates a file, and '>>' appends to it.
    sudo echo "[Desktop Entry]" > /usr/share/applications/idea.desktop
    sudo echo "Type=Application" >> /usr/share/applications/idea.desktop
    sudo echo "Encoding=UTF-8" >> /usr/share/applications/idea.desktop
    #sudo echo "Version 1.0" >> /usr/share/applications/idea.desktop
    sudo echo "Name=IDEA IDE" >> /usr/share/applications/idea.desktop
    sudo echo "Comment=Launcher for IDEA by Kushal" >> /usr/share/applications/idea.desktop
    sudo echo "Categories=Development;" >> /usr/share/applications/idea.desktop
    sudo echo "Exec="$ideahome"klaunch.sh" >> /usr/share/applications/idea.desktop
    sudo echo "Icon="$ideahome"icon.png" >> /usr/share/applications/idea.desktop
    sudo echo "Terminal=true" >> /usr/share/applications/idea.desktop
    echo ""
    echo "updating /usr/share/applications/desktop.en_US.UTF8.cache"
    sudo echo "[idea]" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Name=IDEA IDE" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Comment=Launcher for IDEA by Kushal" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Categories=Development;" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Exec="$ideahome"klaunch.sh" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Icon="$ideahome"icon.png" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Terminal=true" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "Type=Application" >> /usr/share/applications/desktop.en_US.UTF8.cache
    sudo echo "" >> /usr/share/applications/desktop.en_US.UTF8.cache
    echo ""
    echo "adding pannel entry......"
    
    #/usr/lib/gnome-panel/gnome-panel-add --launcher=/usr/share/applications/idea.desktop
    chmod 777 panel
    
    bash ./panel
    
    echo ""
    echo "Menu set..... Enjoy!!"
    echo ""
    echo "------> YOU WILL FIND ENTRY IN (Applications -> Programming) MENU"
    echo ""
    echo "NOTE: Run command ./panel to add panel entry explicitly. was unable to add panel in sudo mode"
    else
    # file not found
    echo "ERROR! Does not exist! this setup works for GNOME only"
    exit 1
    fi
    

    now here we have added menu entry.

    Adding Panel Entry:
    Ubuntu has made this task easy by providing us with a python script to manipulate panels.
    so all we have to do is use that script.. :D
    so the code is as follows for the panel file:-

    echo "adding panel......"
    /usr/lib/gnome-panel/gnome-panel-add --launcher=/usr/share/applications/idea.desktop --panel=top_panel_screen0
    echo "panel entry added... "
    

    you can also add to the bottom panel with the switch –panel=bottom_panel_screen0 , now the launch button will appear next to show desktop icon at the botton left corner.
    we can also align them to left or right, all is documented in the script usage guide.

    Installation Guide
    installation is very simple, just follow the following steps:

    1. STEP 1: Download the files: idea_desktop_Integration.tar.gz
    2. STEP 2: Extract the files to a directory.
    3. STEP 3: go in the root of the extracted files and issue command
      sudo ./setup
      

      then when asked enter idea path if it is different from the mentioned, if its same as mentioned just press enter.

    4. STEP 4: issue command:
      ./panel
      

      this has to be issued seperate because the ubuntu script for panel does not work in sudo mode

    5. STEP 5: all set Enjoy!! now whenever you have to launch IDEA just click on the icon and it will launch gracefully

    ~~Kushal Likhi~~
    http://www.intelligrape.com

    • Share/Bookmark