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

himanshu

http://www.IntelliGrape.com

Groovy, Grails Practitioner and Agile Enthusiast

Posts by himanshu:

  • Grails Spring Security Plugin: User Switcher

    14 Nov 2011 in Grails

    If you are using Grails Spring Security in your application, one killer functionality that we can easily provide is a simple user switcher
    Add this to your admin layout:

    <sec:ifAllGranted roles='ROLE_ADMIN'>
        <form action='/j_spring_security_switch_user' method='POST'>
            Switch: <g:select from="${users}" optionKey="username" optionValue="displayInfo"
                              name='j_username'/>&nbsp;<input type='submit' value='Switch'/>
        </form>
    </sec:ifAllGranted>
    <sec:ifSwitched>
        <a href='${request.contextPath}/j_spring_security_exit_user'>
            Resume as <sec:switchedUserOriginalUsername/>
        </a>
    </sec:ifSwitched>
    

    In Config.groovy, add the following:

    grails.plugins.springsecurity.useSwitchUserFilter = true

    So, in two easy steps we can provide the application admin to impersonate other users. This also checks if the current user is actually an impersonation and if it is, it provides a link to go back to the original user.

    Very neat indeed :)

    More detailed info available here

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • Grails: Find number of queries executed for a particular request

    07 Nov 2011 in Grails
    When response time of a page is slow, we might be interested in viewing database queries executed on that page. Enabling SQL Logging shows all queries but we are interested in queries for that particular request only.
    We can get this information by just simply adding the following filter to our application(Filters in Grails)
    	        logHibernateStats(controller: '*', action: '*') {
    		        before = {
    				Statistics stats = sessionFactory.statistics;
    				if(!stats.statisticsEnabled) {stats.setStatisticsEnabled(true)}
                           }
    
    			afterView = {
    				Statistics stats = sessionFactory.getStatistics()
    				double queryCacheHitCount  = stats.getQueryCacheHitCount();
    				double queryCacheMissCount = stats.getQueryCacheMissCount();
    				double queryCacheHitRatio = (queryCacheHitCount / ((queryCacheHitCount + queryCacheMissCount) ?: 1))
    				log.info """
    ######################## Hibernate Stats ##############################################
    Transaction Count:${stats.transactionCount}
    Flush Count:${stats.flushCount}
    Total Collections Fetched:${stats.collectionFetchCount}
    Total Collections Loaded:${stats.collectionLoadCount}
    Total Entities Fetched:${stats.entityFetchCount}
    Total Entities Loaded:${stats.entityFetchCount}
    Total Queries:${stats.queryExecutionCount}
    queryCacheHitCount:${queryCacheHitCount}
    queryCacheMissCount:${queryCacheMissCount}
    queryCacheHitRatio:${queryCacheHitRatio}
    ######################## Hibernate Stats ##############################################
    """
    				stats.clear()
    			}
    
            }
    

    There are a bunch of other stats that we can get to do more analysis  If you see a large amount of queries, you can simply turn sql logging on for the particular action in this way

    Gotchas:

    1. Since we are getting the stats from sessionFactory, they just do not pertain to any particular request. So this will not work in a multiuser enviornment(prod/qa)
    2. Also these stats may not be correct if you have any background jobs running simultaneously

    This is basically one of the things that we do when we want to ‘tune’ the performance of an application.

    PS: Performance tuning comprises of many more things. Peter ledbrook gave an excellent session on it in last year’s SpringOne2GX. You can find a summary here

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • Criteria Query with Left Outer Join

    01 Nov 2011 in GORM&Grails

    When using criteria queries, we often find cases for Outer joins. Lets take an example. We have two domain classes with us:

    class Blog {
    
    	String title
    	String content
    
    	static hasMany = [comments: Comment]
    
        static constraints = {
        }
    }
    

    and

    class Comment {
    
    	String text
    
    	static belongsTo = [blog: Blog]
    
        static constraints = {
        }
    }
    

    Now, lets say, we want get the title of all the blogs along with the count of the comments on it. The query that we try is:

    List blogStats = Blog.createCriteria().list {
    		createAlias('comments', 'c')
                	projections {
                    	groupProperty('id')
                    	groupProperty('title')
    			count('c.id')
                }
    }
    

    Interestingly, we do not get what we want. We do get a list of list of id, title and comments count, but only for those blogs for which comments exist. So, with creating an alias, we just created a join but what we need is a left outer. As always, stackoverflow had the answer. The createAlias method can take another parameter to specify that we want the join to be a Left outer join.

    We’ll need to add the following import:

    import org.hibernate.criterion.CriteriaSpecification

    And the our query looks like:

    List blogStats = Blog.createCriteria().list {
          createAlias('comments', 'c', CriteriaSpecification.LEFT_JOIN)
          projections {
    		         groupProperty('id')
                    	groupProperty('title')
             		count('c.id')
          }
    }
    

    Looks pretty simple now that I know it :)

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • Organizing “.bashrc”

    17 Aug 2011 in Linux

    I have been working on Linux for almost 3 years now and have grown to love it a lot.

    As with every linux user, the .bashrc file becomes cumbersome and difficult to maintain over a period of time, since there are a lot of project specific aliases, paths, etc

    So after working on a couple of projects, I started maintaining separate files for my environment settings. So I just had to create a separate project setting file:

    ~/.myProjectSettings
    alias myAlias1='cd /to/project/dir'
    alias projectqa='ssh to@qa'
    alias projectDb='mysql -u<username> -p<password> <project_db_name>'
    

    So, everytime I had to add more project specific settings or separate my settings, I had to create a new settings file and then source it in my .bashrc by adding this line

    . ~/.myProjectSettings

    As you can guess, after doing this a couple of times, even this was becoming very tedious.

    So, I tried to follow the golden rule of convention over configuration.

    In my .bashrc, I added the following function :

    function sourceAllMySettings(){
    	FOLDER_TO_BE_SOURCED=~/.mySettings/
    	for i in `find $FOLDER_TO_BE_SOURCED -type f`; 
    	do 
    		. $i
    	done;
    }
    ##don't forget to execute the function
    sourceAllMySettings
    

    and placed all my setting files into the folder :

    ~/.mySettings/

    So, now if I have to add more settings to my .bashrc, I just create a new executable file in this folder and it gets automatically sourced.

    Goodbye messy .bashrc, welcome organized (segregated) settings :)

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • Modifying Grails Scaffolded templates – I

    10 Feb 2011 in Grails

    In one of the sessions in SpringOne2GX, there was a session on Uber-Scaffolding by Jean Barmarsh. The session was quite incredible and opened up a world of possibilities. We all know that the scaffolded code generated by grails is modifiable if we install the base templates. This is done simply by saying:

    grails install-templates

    The above command will create the following directory structure in the application’s src folder


    As we can see, there are 3 main directories here :

    1. Artifacts: This directory contains all the base files for creating various artifacts. For example, if you say “grails create-domain-class packageName.className”, then the file “src/artifacts/DomainClass.groovy” is taken as the template for creating this file. Same goes for other artifacts like filters, taglibs, controllers, etc.
    2. Scaffolding: This directory contains the template files that are used for generating scaffolded code(controllers and views).
    3. War : This just contains the web.xml file. If you need to add some configuration block(e.g. session-timeout, etc)

    Now there are a lot of things that we may need to modify in the grails templates, the pagination size being one. So, the first change that I did was made the “max” parameter in controller be Config driven simply by replacing :

    
    params.max = Math.min(params.max ? params.int('max') : 10, 100)
    
    

    by

    
    int pageSize = grailsApplication.config.grails.scaffolds.pageSize ?: 10
    params.max = Math.min(params.max ? params.int('max') : pageSize, 100)
    
    

    This was the simplest thing that was done.

    In order to use the changed scaffolding, there are two ways of doing this:

    1. grails generate-all MyDomainClass
    2. Create an empty controller, and put the following code in it :
      def scaffold = MyDomainClass

    Note: When playing around with grails templates, be very careful not to format this code using an IDE. The formatting will add unwanted spaces and the grails create-*/generate-* commands will start failing or produce wrong/unusable files.

    Will be back with more :)

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • SpringOne2GX : Peter Ledbrook’s session on Performance Tuning

    21 Oct 2010 in Grails

    Peter Ledbrook took an amazing session on tuning your grails Application here at SpringOne2GX in Chicago. In this session Peter talked about tuning the various aspects about in your application starting from server side optimizations to the caching and zipping of static resources.

    One of the most important thing that Peter pointed out was to “Avoid Premature Optimizations”. You first have to know that where the bottleneck exists(i.e. if it exists at all). So the first step towards performance tuning is actually profiling the application. So, its Profie then optimize

    For profiling, we need to understand and identify where things can be slow. Where can things be slow?

    As we can see, the bottleneck can be at any of the layers. We can broadly classify the layers into

    1. Server Side
    2. Client side

    Some of the tools that are available on the server side include

    1. The profiler plugin from Peter
    2. Turning on hibernate logging or using P6Spy plugin.
    3. New and shiny Spring Insight: The stats that it provides are truly amazing and informative. Its indeed a thing to look out for. However, being a grails user, the only thing that I didn’t like was that i had to create a war out of my application and deploy it on the Spring TC Server. Will love to see a grails plugin that provides these capabilities :-) .

    On the client/UI side performance profiling, Peter demoed a couple of tools:

    1. Google’s speed tracer for Google Chrome. Its a client side performance profiling tool for Google Chrome which integrates nicely with Spring Insight to provide all your client side as well as server side performance stats at one place.
    2. YSlow” extension for FireFox (needs firebug) : This is a trusty old partner that actually tells you in clear words what you need to do to improve performance of your application on the UI level.

    Once you have diagnosed the problem(s) aka done the profiling, then you need to get down to some dirty (hard) work to fix these issues: For the database performance improvements, Peter explained the various things that can be done like :

    1. Reduce the number of queries
    2. Tune your queries to use indexes or even change the model if the need be
    3. Caching: how to use the hibernate 2nd level cache or using someother caching strategies like Distributed cache (e.g. Terracotta, Gemfire and the likes)
    4. And if the need be, use an Alternative Data Store

    For other server side improvements, Peter also pointed out the use of the Spring cache plugin and also how it can be used to cache complete pages or even page fragments.

    For improving the performance on the UI level, there are a number of things that can be done such as:

    1. Reduce number of requests (latency)
      1. Expires HTTP
      2. Bundle CSS & Javascript files
      3. Image spriting
    2. Reduce amount of data transferred to browser (bandwidth)
      1. Minify Javascript
      2. Compress data

    For doing all these things the grails way, there are plugins like UI Performance, JAWR, Resources et al. available I have worked with UI Performance and now can’t wait to get hold of the awesome Resources plugins family by Marc Palmer after hearing about it from Peter.

    Well learnt a lot of new things and some learnings got re-enforced. Really happy to be here among this buzzing and vibrant community.

    As someone at the conference said: “These are exciting times :)

  • MySql : Publish results of a query to a text file

    16 Aug 2010 in Database

    A while back I was trying to debug an error in our application logic. For that I had to analyze the results of a query

    This analysis was getting pretty tough to do on the command line. So, I tried to find a way to transfer the results of a query to a text file so that they can be analysed easily.

    With help from google, I got my answer at http://www.wellho.net/forum/The-MySQL-Relational-Database/MySQL-query-to-a-text-file.html

    echo "<YOUR SELECT QUERY>"| /usr/local/mysql/bin/mysql --user=root --password=password dbName > /path/to/your/textFIle.txt/

    Hope this helps

  • Linux – Managing applications running on system start-up

    14 Jul 2010 in Linux&System

    Rcconf is a tool that we recently discovered. This tool allows you to manage your start-up applications easily.

    We found this tool when me and my colleague Aman were trying to identify the processes that we never use but they do eat up a lot of our system resources. We found this link very useful: http://www.debianadmin.com/manage-linux-init-or-startup-scripts.html.

    The other way to manage system start-up applications is as the page suggests, by using update-rc.d, but rcconf provides an interface which is easy to understand and use.

    To install rcconf, run the following command on your command line:

    sudo apt-get install rcconf

    To run rcconf, you’ll need sudo privileges:

    sudo rcconf

    The application looks like :

    * means that application is a part of startup
    Use spacebar to uncheck the application

    Save the settings and restart your linux box. I removed unused applications like postgres, tomcat, monit, bluetooth etc.

    And my system does feel a bit faster :)

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • How to Set-up shared folder/repository between two or more users on Linux

    14 Jun 2010 in Linux&System

    We had a case where we wanted two different applications (run by different users) to be able to read and write from the same file system.
    This is how we solved this problem:

    1. Create a group which these users will belong to :
      groupadd GROUP_NAME
    2. Edit user1 and user2 to be a member of this group:
      usermod -a -G GROUP_NAME user1 ;
      usermod -a -G GROUP_NAME user2;
      
    3. Create a shared directory. In our case, it had to be the document root for an Apache site. Thus we chose the location SHARED_FOLDER
    4. Now we need to change the group of this folder :
      chgrp -R GROUP_NAME SHARED_FOLDER 
    5. We’ll also need to grant the group write access on this folder :
      chmod g+w SHARED_FOLDER 
    6. Now we’ll need to set the GroupID flag on this folder. For a directory, the set-groupID flag means that all files created inside that directory will inherit the group of the directory. Without this flag, a file takes on the primary group of the user creating the file. This property is important to people trying to maintain a directory as group accessible. The subdirectories also inherit the set-groupID property. (http://www.dartmouth.edu/~rc/help/faq/permissions.html).
      chmod +s SHARED_FOLDER
    7. Now in your .bashrc / .bash_profile, set the umask as 002. Setting this umask ensures that all the newly created files by this user will have the permission “rw-rw-r”. Thus giving the group write permission.: 
       umask 002 

    Now when either of the users create any file in the SHARED_FOLDER, all the users of this group will have the read/write permissions on that file. Not only this, these permissions will be on the subfolders and the files with-in that folder as well.

    But, if any of these users create a file outside the SHARED_FOLDER, the primary group of that file/folder will be the same as the primary group of that user. Thus files/folder only in the SHARED_FOLDER are shared between these users.

    This is just one of the many great abilities that Linux provides.

    Hope this saves you some time.

    Your feedback and suggestions are welcome.

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com

  • Embedding JBPM 4.3 in a Grails 1.2.2 Application

    14 May 2010 in Grails&System

    Hi,

    In one of our projects, we had a requirement for using some existing Business Process Management tool. JBPM is one such tool that we are evaluating.

    Our first step was to run a “Hello World” process from inside the grails application. On searching over the internet, I didn’t find any helpful article/blog on integrating JBPM inside a grails application. However, there were some very good resources on integrating JBPM with a spring application. I found Joram Barrez’s Hello World Example very helpful and was able to integrate using the following steps:

    1. Download jbpm from here.
    2. Unzip the contents and copy the jbpm.jar file to the lib directory of your application.  The exploded directory has the following files/ folders for version 4.3 :
    3. Also copy the mail.jar from the jbpm installation directory (${jbpmHome}/lib) to the lib directory of your application.
    4. Create a process descriptor file in the conf directory (helloWorld.jpdl.xml) with the following code
           <process name="helloWorld" xmlns="http://jbpm.org/4.0/jpdl">
           <start>
           <transition to="printHelloWorld"/>
           </start>
       
           <java class="com.jbpm.example.Printer" method="printHelloWorld" name="printHelloWorld">
                <transition to="CheckDate"/>
                <transition to="theEnd"/>
           </java>
       
           <end name="theEnd" />
           <state name="CheckDate">
           <transition to="printHelloWorld"/>
           </state>
          </process>
    5. Create a class in src/groovy
      package com.jbpm.example
       
      class Printer {
       
       public void printHelloWorld() {
         System.out.println("&lt;----------------&gt;");
         System.out.println("&amp;nbsp;&amp;nbsp; HELLO WORLD!");
         System.out.println("&lt;----------------&gt;");
       }
      }
    6. Create a minimal jBPM config (jbpm.cfg.xml) in the conf directory
           <jbpm-configuration>
           <import resource="jbpm.default.cfg.xml"/>
           <import resource="jbpm.tx.hibernate.cfg.xml"/>
           <import resource="jbpm.jpdl.cfg.xml"/>
          </jbpm-configuration>
    7. Create a basic Hibernate config called conf/jbpm.hibernate.cfg.xml(I’m using MySql, Still looking for a way on how to use the grails DataSource)
          <?xml version="1.0" encoding="utf-8"?>
          <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
          <hibernate-configuration>
           <session-factory>
           <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
           <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
           <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testJbpm?autoReconnect=true</property>
           <property name="hibernate.connection.username">username</property>
           <property name="hibernate.connection.password">password</property>
       
           <property name="hibernate.format_sql">true</property>
           <property name="hibernate.hbm2ddl.auto">update</property>
       
           <mapping resource="jbpm.repository.hbm.xml" />
           <mapping resource="jbpm.execution.hbm.xml" />
           <mapping resource="jbpm.history.hbm.xml" />
           <mapping resource="jbpm.task.hbm.xml" />
           <mapping resource="jbpm.identity.hbm.xml" />
       
           </session-factory>
          </hibernate-configuration>
    8. Create the following Spring beans is resources.groovy
      springHelper(org.jbpm.pvm.internal.processengine.SpringHelper) {
              jbpmCfg = "jbpm.cfg.xml"
      }
      processEngine(springHelper:"createProcessEngine")
    9. Now lets deploy this process. To deploy a process we will need to inject the processEngine bean
       def processEngine;

      The code to deploy this process is

      RepositoryService repositoryService = processEngine.getRepositoryService();
               repositoryService.createDeployment()
                       .addResourceFromClasspath("helloWorld.jpdl.xml")
                       .deploy();
    10. Lets start an instance of this service :
      ExecutionService executionService = processEngine.getExecutionService();
      executionService.startProcessInstanceByKey("helloWorld");

      This will execute the printHelloWorld method of the Printer class as configured in the process description file.

    Hope you find this useful. We are still working on executing more complex processes and will keep posting our learnings.

    Your feedback and suggestions are welcome.

    Regards
    ~~Himanshu Seth~~

    http://www.IntelliGrape.com