Spring « Intelligrape Groovy & Grails Blogs

Archive for the ‘ Spring ’ Category

User-Role hierarchies in spring security

Posted by on September 6th, 2012

In most of our applications we are using spring security core plugin for the authentication process. We define some roles in that . Have your ever thought about assigning precedence to the roles. Like, You are having 3 roles defined in your application.

i.e. ROLE_SUPER_ADMIN, ROLE_ADMIN ,ROLE_ATTENDEE.

While using these roles i.e

   @Secured(['ROLE_ATTENDEE'])
    def dashBoard(){
        render(view: 'dashBoard')
    }

Here above you can see that you are restricting the access to this function , if you want that this function should be accessible by ADMIN also , you will mention that role over there.

i.e.

 @Secured(['ROLE_ATTENDEE','ROLE_ADMIN'])

In my project i was having same scenario , So instead of defining list of comma separated roles. You would define a role hierarchy in your config.groovy as mentioned below :-

grails.plugins.springsecurity.roleHierarchy = '''
    ROLE_SUPER_ADMIN > ROLE_ADMIN
    ROLE_ADMIN >  ROLE_ATTENDEE
'''

Here you can see , I have defined a role hierarchy like parent child relationship. So, Like in previous example

   @Secured(['ROLE_ATTENDEE'])
    def dashBoard(){
        render(view: 'dashBoard')
    }

Now above written function would be acessible by all parent roles . No need to specify all the required roles. Isn’t it cool.

Hope it helps. :)

Thanks & Regards,
Robin Sharma.
robin@intelligrape.com

Posted in Grails, Groovy, Spring

New Features in Try/Catch – JDK 7

Posted by on August 27th, 2012

In our applications we generally make use of try-catch blocks to handle exceptions. Since JDK-7 , It has certain new features. These features are quite good , I must say.

Some of the new changes in try/catch bloack are :

1.  Multiple exceptions handling in only one catch block.
2.  Finally out of scope. (Try-Catch with resources is new feature.)

1. Catching Multiple Exception Types

In our applications , We generally make use of catch block like these :-

catch (SQLException ex) {
     logger.log(ex);
     throw ex;
catch (IOException ex) {
     logger.log(ex);
     throw ex;
}

We can cleary see that we are maintaining duplicate code for handling exceptions . So , In Java SE 7 there are some modifications that resolves this issue.

Have a look at following snippet of code :-

catch (IOException | SQLException ex) {
   logger.log(ex);
   throw ex;
}

Here above , We can see that a single catch block is handling multiple exceptions. Isn’t it cool. :)

For more details , Please visit Oracle-docs for try-catch

2. Finally out of scope. (Try-Catch with resources is new feature.)

We generally make use of finally block to close thre resources we used in our code.
e.g.

String readLineFromBlock(String pathOfFile)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(pathOfFile));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

You can see that in above written snippet of code, We are closing the reader and handling the exception for the same , But In JDK7, finally is no longer required. Now in JDK-7 a new feature is added that is , Try-Catch with resources . This is a wonderful feature .

Just have a look at the syntax :

String readLineFromBlock(String pathOfFile) throws IOException {
     try (BufferedReader br =new BufferedReader(new FileReader(pathOfFile))) {
         return br.readLine();
     }
}

You can see that in above written snippet of code, We are not closing the reader and handling the exception for the same , It is being taken care of automatically by JDK-7.

Now closing the streams , readers n all will not be a headache for you , Need not to to write a extra snippet of code for them & then enclosing them again in try-catch block.

For more details , Please visit try-catch resource

These are really good features, Quite helpful . Just give a try . :)

Thanks & Regards,
Robin Sharma,

robin@intelligrape.com,
Intelligrape Software Services.

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