Showing posts with label Framework. Show all posts
Showing posts with label Framework. Show all posts

Wednesday, December 7, 2011

Patterns: Factory Method

Factory Method

Purpose
  1. Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  2. Defining a “virtual” constructor.
  3. The new operator considered harmful.

Facotry Method is a Creational Pattern and it deals with Creation of Object without specifying the exact class of object that will be created. Object creation some times requires complex processes not required and it’s not appropriate to write all this code in composing object

Facotry Method design pattern handles this problem by creation of a separate method for creation of object which Subclass can override to provide its own implementation

Essence of Factory Method Pattern is

“Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”


public class TestFactoryMethod {

      public static void main(String[] args) {
            Skin s=SkinFactory.getSkin("web");
            s.printSkin();
      }          
     
}

class SkinFactory{
      public static Skin getSkin(String type){
            if(type!=null && type.equals("web"))
                  return new WebbasedSkin();
            else
                  return new DesktopbasedSkin();
      }
}

interface Skin{
      public void printSkin();
}

class WebbasedSkin implements Skin{
      public void printSkin(){
            System.out.println("I am Web based Skin");
      }
}

class DesktopbasedSkin implements Skin{
      public void printSkin(){
            System.out.println("I am DesktopbasedSkin Skin");
      }
}



Tuesday, October 4, 2011

EhCache Integration with Spring and Hibernate. Step by Step Tutorial

EhCache is a very popular open source caching framework widely used for Java based Caching.

Currently it’s owned by Terracotta.org and 2.5 beta releases is available for download.

In this article I just focused on EhCache Integration with Spring and Hibernate also I just explained few basic concepts which are required to understand Code. For detailed Caching Concepts Please visit http://ehcache.org/

Cache Manager, Caches and Elements are main entities of EhCache

EhCache consists of a CacheManager, which manages Caches. Caches contain Elements, which are essentially name value pairs. Caches are physically implemented either in-memory, or on disk.

Integration with Spring

EhCache integration with Spring is quite simple. You just need to define some properties in spring configuration xml file and its ready to use. Spring is using Annotation to integrate EhCache and by this we can add caching to any method results

EhCache Annotations for Spring is available via maven, simply add the following dependency to your pom.xml  

 
   
Next Step is to perform changes in your spring Configuration file. Below is my Spring configuration file which contains EhCache configurations



Important point to note here is that Cache Manager Name and its Configuration Location. We can use cacheManager in our code to store and retrieve information from Cache.

ehcache.xml file is configuration file for EhCache where we can define configuration details of EhCache. In my case here is content of my ehcache.xml file



Here it’s clear that we have created a cache with name Customer, I will use this Cache to store Customer details

Next step is to use it in your code. In my example I created a simple Spring based application where we have Customer Controller which is used to retrieve Customer Information

We have Customer Object with Customer Id, name and address details and related setter getter methods


Next step is to create Controller. Customer Controller is very simple. I am using Spring Restful Web services to retrieve Customer Information. In my Controller I have no logic related to EhCache. I just have two versions of getCustomer method (one with Annotation and one without Annotation), save Customer and Clear Cache method. Code is simple and self explanatory for any Spring MVC developer.




If you notice Controller is calling Customer Service. Customer Service is our main class and it’s used to get Customer Information. It can get information from Database using Hibernate or from any backend. Here I just provided basic implementation. Idea is to understand usage of EhCache
Following Service methods are used to retrieve and store information in Cache


     
Previously we have defined “cacheManager” object in our Spring.xml file and also we have defined a Cache with name “customer” in ehcache.xml file. Its time to use both these configurations
getCache method is use to retrieve Cache Object and we are storing new Element in this cache. Element requires key, value pair so I am using id filed as a key. Later on we can use same key to retrieve Customer Object from Cache.

Another great way of using EhCache is Spring Annotation

   

Add Cacheable Annotation to methods you would like to cache. In our case we are using it for getCustomer method. If we call getCustomer method with customerId 1, first time complete method will be called. If we will call this method again with same customerId then response will be returned from Cache.

To Clear Cache we can just use TriggerRemove Annotation

 

Complete Source Code is present at following location

https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B0YFdqXJcI3mY2ZiYzA4NWQtNmQ0ZS00ZWM0LTlkMzktMmM3YmJmZjUzNDEy&hl=en_US

Integration with Hibernate as a Second Level Cache

Hibernate uses different type of Caches

·         The first cache type is the session cache. The session cache caches object within the current session.
·         The second cache type is the query Cache. The query cache is responsible for caching queries and their results.
·         The third cache type is the second level cache. The second level cache is responsible for caching objects across sessions.
EhCache is used as second level cache. EhCache integration with Hibernate is quite simple as well. You just need to define some properties in persistence.xml file.
EhCache jars are available via maven, simply add the following dependency to your pom.xml  

 
   
Next step is to perform changes in persistence.xml  

 

 Put ehcache.xml at your classpath. It could be in classes or WEB-INF folder

 

In you Entity just add Annotations related to ehcache and thats it.

 

Complete Source Code is present at following location

https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0B0YFdqXJcI3mMDJiMDU4MmUtZWFkYy00MTAxLWFjMmYtMWYyMGNhMWY2Mjdj&hl=en_US





Thursday, September 29, 2011

Spring ROO, An Amazing Framework

Recently I got an assignment to build a new web based server side project. Normally for Web based projects we used Spring MVC, Hibernate for persistence and Maven for dependencies management. At this point I have two options.

First option is to manually create a new Project, create Maven POM file, create folder structure, define dependencies related to spring and Hibernate, create Hibernate and Spring configuration files like persistence.xml and web.xml. Usually this process takes two to three hours to configure every thing properly and make this project in running condition

Second Option is to use “Spring Roo”. Spring Roo will work as my junior developer. It will automatically generate Application Structure, pom file, required configuration files for spring and hibernate and all this process will take maximum 5 to 10 minutes and for this I just have to execute few commands.

Is it real or I am in my dreams J

Spring Roo is a dynamic, domain-driven development framework from SpringSource the makers of the Spring framework. Spring Roo uses standard Java and Spring, but during development time, the Spring Roo shell watches you work, helping out as possible and required. Think of Spring Roo as being the ultimate pair-programming buddy, or the most advanced code completion you’ve ever seen

As an example of this power, suppose you’re in the middle of editing a JPA entity in a Spring Roo project, and adding a field of interest—perhaps a name field to a Customer entity. As soon as you’ve finished typing out the field definition, Spring Roo automatically jumps in and adds a corresponding accessor and mutator pair for that field to a shadow class definition in the background. Similarly, it will implement a toString() definition (reflecting the fields added) if one does not already exist, and it will implement an equals() method following the same criteria.. If you update the field, the accessor and mutator are updated as well as the equals and toString methods. If you add an equals method to the JPA entity, the shadow definition is removed, delegating to your implementation instead. So, this shadow class definition is kept in sync, responding to your changes, but it does not get in your way. It defers to your will in all cases.

So, you get Java, but you don’t have to pay the cost of writing all that Java.

The Tooling

Latest Spring Roo Release can be downloaded from http://www.springsource.org/download

Once downloading will finish you will find a folder spring-roo-1.2.0.M1. If you go to bin folder you will find roo.bat. Once you click on this file a command console will open and from here you can control your project. 

Another simpler option is to use Spring Source Tool Suit IDE which has built-in support of Spring Roo and you don’t have to worry about any configuration. This ID is freely available at Spring Source website

It’s an Eclipse based IDE Just download this IDE and start your development

New Project

To start a new Project just click on FileàNewàSpring Roo Project

  






Enter name of the project. In my case I named it “CustomerManagementSystem”. Define top level java package which in my case is “com.eiconsulting.cms” and press finish.

This will automatically generate a project with Correct Maven based application structure, pom.xml file with correct dependencies of JUnit, the correct and latest versions of spring, AspectJ, logging, and the latest servlet APIs. 

You will notice a Roo.shell at bottom of your ide


This shell is your pair programmer. Here you will write all your commands

So let’s start the magic of Roo

In our project we are planning to use JPA and for this Hibernate as a JPA provider and My SQL as a database. Our pair programmer will help us to configure all this we just need to execute a simple command at Roo console

Actually I am not good in remembering commands, I remember it was some thing like “persist” so I just type persis and press CTRL+ SPACE, automatically “persistence setup” appears in my console after that I press CTRL+ SPACE again now I have two options to define provider and database. Finally I configured my command like this

persistence setup --provider HIBERNATE --database MYSQL

I pressed enter and Magic started

Roo has defined all Hibernate related dependencies in my POM. In META-INF folder persistence.xml automatically created with all MySQL related configuration details and now in a newly generated database.properties file I just have to define database url, username and password.

Now my My Project has full support of Spring and Hibernate with all required configuration files.

After this step my IDE started complaining about Maven Dependency

Missing artifact org.springframework.roo:org.springframework.roo.annotations:jar:1.1.4.RELEASE:provided
I searched about this at Internet and come up with a very simple solution

Open you pom file and replace Roo dependency

        <!-- ROO dependencies -->
        <dependency>
            <groupId>org.springframework.roo</groupId>
            <artifactId>org.springframework.roo.annotations</artifactId>
            <version>${roo.version}</version>
            <scope>provided</scope>
        </dependency>

With this

        <dependency>
            <groupId>org.springframework.roo</groupId>
            <artifactId>org.springframework.roo.annotations</artifactId>
            <version>1.0.2.RELEASE</version>
            <scope>compile</scope>
        </dependency>

Problem solved

Next step is to write my business logic. My initial thinking, “defiantly I have to write all my code by my self “, Luckily Spring Roo is helping me here as well

Because I am developing a CMS so my business requirement is to create a Customer Entity which has name and address field. To create an entity in Spring ROO simply type

entity --class  com.eiconsulting.beans.Customer

In response ROO will automatically generate package and class with name Customer. Also you have noticed that ROO has created couple of configuration files for this entity. These files are not part of our project and they are ROO internal use and we don’t have to bother about them.

Next step, we want to add name and address field. Following commands will perform this action

field string --fieldName name –notNull
field string --fieldName address --notNull
You will notice that ROO has generated few annotation is Customer class
@RooJavaBean
@RooToString
@RooEntity

This is for ROO Internal use to assist you during development If you simply don’t want Roo to even bother, simply remove the annotation from the Customer.java file and watch as Spring Roo removes the corresponding .aj file. If, later, you decide you that you were a bit hasty in dismissing its help, simply replace the annotation and Roo will obediently hop back into action again.

From this point you can move forward and start writing your business logic as per our requirements

As I mentioned earlier that we are planning to build MVC based project and we noticed that our project doesn’t contains folder structure for a Web based project, also for MVC based project we need a Customer Controller

Well very simple just execute following command and see the magic

controller scaffold --entity com.eiconsulting.beans.Customer --class com.eiconsulting.web.CustomerController

Automatically ROO will convert you project to a Web based project with Customer Controller with proper directory structure for a web based project

Also you will notice that ROO has create lots of images, css files and sample images

All these files are for your support. You can delete them or use them as per your requirements

Just build your project using your maven package command and it will generate a resultant war file. In our case it is CustomerManagementSystem-0.1.0.BUILD-SNAPSHOT.war. Deploy it in your favourite web server

You will notice a file with name log.roo. This file contains all commands which you have executed in ROO so far

To remove Roo from a project, you need to import the project into Eclipse or SpringSource Tool Suite. Once the project has been imported into Eclipse, right-click the project name in Package Explorer and select Refactor > Push-In Refactor. If this option is missing, ensure that you have a recent version of AJDT installed. After selecting the push-in refactor menu option, a list of all Roo inter-type declarations will be displayed. Simply click OK. AJDT will have now moved all of the Roo inter-type declarations into your standard .java files. The old *_Roo_*.aj files will have automatically been deleted. Complete Removal details are present at this URL http://static.springsource.org/spring-roo/reference/html/removing.html


Reference: Getting Started with ROO