Spring « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ Spring ’

How to implement AOP Profiling in Grails application

Posted by on September 25th, 2012

In one of my recent project, i want to profile method execution time. I have used Spring AOP to profile method execution time.

It’s very easy to implement AOP profiling in grails

1. Suppose we have below mentioned service class, we want to log execution time of method saveDataStudent,saveDataUpdated methods in service class. We need to write aspect for it.

package com.service

import com.test.Student
class StudentService {
    Student saveDataStudent(Student student) throws Exception{
        return student.save(flush: true,failOnError: true)
    }

    Student saveDataUpdated(Student student){
        return student.save(flush: true,failOnError: true)
    }
}

2. Use following aspect code for profiling.

package com.spring3.base.test

import org.aspectj.lang.JoinPoint
import org.aspectj.lang.ProceedingJoinPoint
import org.springframework.stereotype.Component
import org.springframework.util.StopWatch
import org.aspectj.lang.annotation.*

@Aspect
@Component
class LoggerInterceptor {

     @Around("execution(* saveData*(..))")
    public Object profileSaveMethod(ProceedingJoinPoint call) throws Throwable {
        StopWatch clock = new StopWatch("Profiling:::::" + call.signature + ":::::Args::::::" + call.args
        );
        try {
            clock.start(call.toShortString());
            return call.proceed();
        } finally {
            clock.stop();
            System.out.println(clock.prettyPrint());
        }
    }

}

@Around(“execution(* saveData*(..))”) : It represents that this advice will execute for those methods whose name is starting with saveData.

Hope this code will help you :)

To know more about AOP, you can take the reference from following links:

http://www.intelligrape.com/blog/2012/08/27/integrating-of-spring-aop-with-grails-application/
http://static.springsource.org/spring/docs/2.5.5/reference/aop.html

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Grails

Attributes of Spring Cache

Posted by on September 25th, 2012

In my previous blog, i have mentioned how to integrate spring cache plugin in grails. In this blog we will see how we can use different attributes of cache.

Different attributes of cache :-

  1. maxElementsInMemory- How many elements you can store in cache
  2. overflowToDisk-The attribute overflowToDisk is true, meaning that whenever the maximum number of in-memory objects is reached, objects are swapped to disk
  3. diskPersistent – if diskPersistent is false, it means when application server is restarted, in-memory cache is lost.
  4. ttl(time to live seconds)- It denotes for how many seconds element will remain in cache?
  5. memoryStoreEvictionPolicy – It is used to evict element from in-memory when the maximum number of in-memory objects is reached . Different type of eviction policy:
  6. a) LRU (Least Recently Used): Oldest element will be evicted.
    b) LFU (Least Frequently Used): Element with least hits will be evicted.

In grails, you can implement different cache attributes like this way.

studentCache(EhCacheFactoryBean) { bean ->
cacheManager = ref("springcacheCacheManager")
cacheName = "studentCache"
eternal = false
diskPersistent = false
memoryStoreEvictionPolicy = "LRU"
ttl = 3000
}

Hope this code will help you :)

To know more about Cache, you can take the reference by using below link.
http://grails.org/plugin/springcache
http://www.intelligrape.com/blog/2012/09/25/how-to-integrate-spring-cache-plugin-with-grails/

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Grails

How to integrate Spring cache plugin with Grails

Posted by on September 25th, 2012

In one of my recent project, i want to cache  method output. For implementing method level cache, i have used spring cache. For implement Spring cache, we can use grails cache plugin.

It’s very easy to integrate cache plugin with grails.

1. Add following plugin dependency in BuildConfig.groovy.

compile ":springcache:1.3.1"

2.  We need to define the caches in resource.groovy. Use below mention code to create cache in resources.groovy.


studentCache(EhCacheFactoryBean) { bean ->
cacheManager = ref("springcacheCacheManager")
cacheName = "studentCache"
memoryStoreEvictionPolicy = "LRU"
}

EhCacheFactoryBean – Pre define class of the spring
studentCache – Cache name

3. Add following codes in Config.groovy file to enable cache.

springcache {
    defaults {
        eternal = false
        diskPersistent = false
    }
    caches {
        studentCache {
            memoryStoreEvictionPolicy = "LRU"
           ttl=1000
        }
    }
}

We need to mention the cache name that we want to enable. We can enable multiple cache.

4. Add @Cacheable annotation above method that you want to cache.

@Cacheable(cache="studentCache")
    Student showStudent(long id){
        return Student.get(id)
    }

@Cacheable – We need to pass cache name
But one thing we need to ensure, the class in which we are implementing the cache, it should be managed by spring or grails.
Run server, hit the url, you can see our method output is cached.
Hope so this code will work for you :)

To know more about Cache, you can take the reference by using below link.
http://grails.org/plugin/springcache

Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Posted in Grails

Using PostConstruct annotation with Grails Services

Posted by on August 27th, 2012

We can use PostConstruct with Grails Services and injected Spring Beans. This PostConstruct annotation can be used to annotate a method which needs to be executed after dependency injection to perform any initialization.

import javax.annotation.PostConstruct

class PostConstructDemoService {

    @PostConstruct
    private void init() {
          println "Initializing"
          //your initialization code goes here. e.g connect to some Messaging Service
     }
}

Check this for more details. We also have PreDestroy annotation.

Regards,
Ankur Tripathi
ankur@intelligrape.com

Posted in Design Pattern, Grails

Integrating Spring AOP with Grails Application

Posted by on August 27th, 2012

AOP means Aspect Oriented Programming

  1. Enables encapsulation of functionality that affects multiple classes in separate units.
  2. Complements Object Oriented Programming.
  3. Cross Cutting Concerns : Functionality whose implementation spans multiple modules.

Different From OOPS

Sometimes we want to implement common functionality through out some classes, through out some common method. We can achieve that functionality by implementing separate module without touching core logic.

Take the example of Banking Domain

In this case when person calls the withDraw() function, we want to log the detail of each step, that is performed in back end, i.e. what parameters were passed to each function, we want to log such details. Using OOPS concepts, we have to write logging code in each method, it’s very difficult to implement, but by using AOP we can implement this functionality as separate module without touching the core logic. We can implement security on method level by using some pattern as a Join Point with AOP.

Where can we use AOP

  1. Logging
  2. Transaction Management
  3. Profiling
  4. Security

What does Spring AOP contains:

  1. Join Point : A point in the execution of program.
  2. Advice : Code to be executed at a join point that has been selected by point cut.
  3. Point cut : An expression mapped to a join point.

Now Question comes in mind, How to integrate Spring AOP with Grails Application

It’s very easy to integrate Spring AOP with Grails Application

  1. Firstly we have to add configuration of Spring AOP in resources.groovy
  2. Now write following line of codes in resources.groovy
beans = {
xmlns aop:"http://www.springframework.org/schema/aop"
aspectBean(com.test.aop.LoggerInterceptor)
aop.config("proxy-target-class":true) {
}

3.   In this case we create the bean of AOP class by using aspectBean(com.test.aop.LoggerInterceptor).

4.    aop.config(“proxy-target-class”:true) It’s enable AOP to create proxy of target class.

5.   Create Groovy class that contains the implementation of AOP.

6.   I will show the example of logging functionality with using AOP.

package com.test.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Service;
import java.util.Arrays;
@Aspect
public class LoggerInterceptor {
private static Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);
@Before("within(com.service..*)")
public void logBefore(JoinPoint joinPoint){
String logMessage = String.format("Beginning of each method: %s.%s(%s)",
joinPoint.getTarget().getClass().getName(),
joinPoint.getSignature().getName(),
Arrays.toString(joinPoint.getArgs()));
logger.info(logMessage);
}
}

@Aspect : Any bean with a class annotated as an aspect will be automatically detected by Spring.

@Before : It’s Before advice that executes before the matched method.

JoinPoint : Provides access to the current join point (target object, description of advised method,parameters types, parameters values, etc).

within(com.service..*) : This method will executed before calling any method in service class under package com.service..*

You can easily apply advice to any public method, any parameterized method to any Class.

To know more about AOP, you can take the reference of Spring AOP official site.
http://static.springsource.org/spring/docs/2.5.5/reference/aop.html

Thanks & Regards,
Mohit Garg

mohit@intelligrape.com
@gargmohit143Thanks & Regards,
Mohit Garg
mohit@intelligrape.com
@gargmohit143

Tags: , ,
Posted in Grails, logging, Spring

Overriding properties in a Spring Bean with BeanFactoryPostProcessor

Posted by on May 12th, 2012

I was going through the source code of one of the Grails Plugins where I found the use of Spring’s BeanDefinitionRegistryPostProcessor to override some configurations that are available in DataSource.groovy. That involved a complete over riding of a PropertyValue definition.

 

It set me thinking about whether there is a way to override bean properties like String, Integer etc in a simpler way after the bean has initialized. In comes BeanFactoryPostProcessor, which provides a wonderful hook to do just that.

 

I created a small grails project and added a class CustomBean which looked like this :


class CustomBean {
       String customVariable
}

I registered a customBean on resources.groovy using

beans = {
    customBean(CustomBean) {
        String value = "Test Data From resources.groovy"
        println "Setting value ${value}"
        customVariable = value
    }

    customBeanPostProcessor(CustomBeanPostprocessor)
}

This sets the initial value of customVariable as “Test Data From resources.groovy”.

If you are wondering what the customBeanPostprocessor is, that is just what I am going to explain next.
The bean implements the BeanFactoryPostProcessor interface and overrides the methods which provides us with hooks to modify the properties of the bean.

 

The class definition is:

import groovy.util.logging.Log4j
import org.springframework.beans.factory.config.BeanPostProcessor

@Log4j
class CustomBeanPostprocessor implements BeanPostProcessor{

    @Override
    Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean
    }

    @Override
    Object postProcessAfterInitialization(Object bean, String beanName) {
        if(beanName == 'customBean') {
            log.debug("Setting custom value inside post processor")
            bean.customVariable = "Set from Post Processor"
        }
        return bean
    }
}

What amazed me is the elegance with which the developers of the framework has provided entry points into its internals without forcing the users to shave the yak.

 

Posted in Grails, Spring

Change user preferred locale using spring’s SessionLocaleResolver

Posted by on May 11th, 2012

Here we are going to talk about a scenario where there are some records in database which are specific to locale and they need to be displayed as per user’s current locale at number of places.Also user can change its preferred locale.

For this I preferred to set the user’s locale in the session object. There are two ways to do this :-

1. Add attribute “lang” to the request and it will be available to session automatically.

For example: whenever user clicks on the link, the language will change to English and the user will remain on the same page.


<g:link controller="${params.controller}" action="${params.action}" params="${params+[lang:'en']}">English</g:link>
/*Add different languages here*/

2.Also set default locale in the session in case, it is not set.

For that add following to any Filters :-


if (!session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE') {
LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
localeResolver.setLocale(request, response, new Locale('en'));

}

This sets the locale in spring’s SessionLocaleResolver class. Session always refer for the locale from here only.

Now one can check the locale wherever session is available. For example in GSPs:


<g:if test="${session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'.toString()=='en'}">

Note: This implementation is useful to set locale in session (for accessing many times). Otherwise locale is available directly from current request as given below:-

import org.springframework.web.servlet.support.RequestContextUtils as RCU
Locale locale=RCU.getLocale(request)

Hope this helped!
Nitesh Goel
[Intelligrape Software Pvt. Ltd.]

RequestContextUtils
Posted in Grails

Request Mocking to use groovyPagesTemplateEngine in backend threads

Posted by on December 27th, 2010

We have a setup where a backend thread, fired by the Spring Events, does some processing, generates a PDF and emails the result to the user.
The code we were using to generate the HTML from a GSP to be converted to a PDF using iText was as follows :

        def webRequest = RequestContextHolder.getRequestAttributes()
        def originalOut = webRequest.out
        try {
            def sw = new StringWriter()
            def pw = new PrintWriter(sw)
            webRequest.out = pw
            groovyPagesTemplateEngine.createTemplate("path_to_gsp").make([model:model]).writeTo(pw)
            return sw.toString()
        } finally {
          webRequest.out = originalOut
        }

There was the obvious fallibility of this code that there was no Current Request associated with the backend thread!

After doing some googling around it, I came across a few threads and posts which talked about Request Mocking, which has been used in Grails Template Engine Plugin.  We overcame this by using the code snippet given below to mock the web request

def webRequest = RequestContextHolder.getRequestAttributes()
if(!webRequest) {
          def servletContext  = ServletContextHolder.getServletContext()
          def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
          webRequest = grails.util.GrailsWebUtil.bindMockWebRequest(applicationContext)
}

However, things didn’t end there. This code broke while working on a WAR environment. The problem was that the MockWebRequest class was part of the “org.springframework:org.springframework.test:3.0.3.RELEASE” jar and had to be included in the BuildConfig.groovy as


dependencies{

runtime 'org.springframework:org.springframework.test:3.0.3.RELEASE'

}

Ensure that the line


mavenCentral()

is not commented in BuildConfig.groovy

We were working on Grails 1.3.4

 

Hope this helps.
Vivek

http://in.linkedin.com/in/svivekkrishna

Posted in Grails

Finding User’s Session Locale in GSP

Posted by on July 14th, 2010

There are situations where you might want to know the Locale of the user as set in the session in your GSP so that you can show text in a particular language/manner. Here the Spring framework’s SessionLocaleResolver can come to the rescue. In one of our recent Grails projects, we did the following in one of our GSPs to display the content accordingly.

Please note that our use-case was like that in which we have fields for different languages in our domain classes. For example:

class MyDomain {
String greetingEnglish
String greetingFrench
}

And now you have to conditionally display the object’s fields based on the user’s locale. If this were a static text, then the Grails in-built i18n support in the form of message bundles would be the ideal solution. But this is a different scenario.

So let’s start by writing the following in your GSP :

<g:set var="lang" value="${session.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'}"/>

The above statement returns the ISO Language Code from the session object which is a map. In Grails, the map values can be retrieved by the ‘.’ operator too by passing the keys. These codes are the lower-case, two-letter codes as defined by ISO-639. For example: ‘en’ for English, ‘fr’ for French and so on.

Once you know the locale, you can show the conditional content on your page. It could be something like this:

<g:if test="${lang.startsWith('en')}">
<h1> ${myDomainobject.greetingEnglish} </h1>
</g:if>
<g:elseif test="${lang.startsWith('fr')}">
<h1> ${myDomainobject.greetingFrench}</h1>
</g:elseif>
<g:else>
<h1> Default Greeting </h1>
</g:else>

Hope this will help !!!

- Abhishek Tejpaul

[Intelligrape Software Pvt. Ltd.]

Posted in Grails, HTML-UI-CSS

Overriding default Transactional Behaviour in Grails Services using Annotations

Posted by on April 28th, 2010

In a project, we needed to have fine tune the transaction behaviour on our Service classes. One service method was calling the a method in another service. The calling service method A was to happen in one transaction and the called service method B in its own transaction. This was required because we needed to persist the error log from the B() in a domain using A().

Even though an exception was thrown from B() and it was caught in A() and handled gracefully, some exceptions were thrown, which meant that the changes made in A() were also rolled back, which was not the behavior we required. After some investigation and taking cue from the mailing list , it was decided that the best way to go about it was to run B() in its own transaction. This was possible using the Spring Transaction Annotation, a property of which creates a new session for B().

This was done by adding the annotation

   import org.springframework.transaction.annotation.*
   class SampleService{
        static transactional = true
        @Transactional(propagation = Propagation.REQUIRES_NEW)
         def B(){
                   //..implementation which can throw exceptions. The logic in this method is run in a single transaction
        }
  }
 

And in A(), we have try catch blocks to handle the exception.

Hope this helps.

Posted in Grails