Sunday, September 29, 2013

Spring AOP - Part II

For Part -I, refer blog: Spring AOP-Part I

Let me give a simple example of AOP to add logging service.

Pom.xml

<dependency> 
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>2.2</version> 
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.11</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.6.8</version>
</dependency>

<!--  logging -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>1.7.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
    <scope>runtime</scope>
</dependency>

AOP Targets:

These are the interfaces/classes on which AOP will be applied. We will define a simple tax calculation service.
public interface TaxService {
        public double calculate(String state,String price);

}

public class TaxServiceImpl implements TaxService{
         public double calculate(String state, String price) {
                double tax = 0.0;
                double priceDbl = Double.parseDouble(price);
    
                if("NY".equals(state)){
                       tax =priceDbl +  priceDbl *0.25;
                }
                else{
                       tax =priceDbl +  priceDbl *0.20;
                }
  
                return tax;
  
         }

Aspect classes:

These are the interface/classes where you will implement the cross cutting concern. In our case, logging. Note that we will get the JoinPoint instance, from which we can derive the method arguments being passed to the target methods.Logging will be  applied before entering a method, after method exit as well in case of any exception being thrown.
public interface LoggingService {
       public void logEntry(JoinPoint jp);
       public void logExit(JoinPoint jp);
       public void logException(JoinPoint jp);
}

public class LoggingServiceImpl implements LoggingService{
 
        private static final Logger logger = LoggerFactory.getLogger(com.myorg.service.LoggingService.class);
 
        public void logEntry(JoinPoint joinPoint){
                logger.debug("Entering method: "+joinPoint + " with args: "+Arrays.toString(joinPoint.getArgs()));
        }
        
        public void logExit(JoinPoint joinPoint){
                logger.debug("Exit method: "+joinPoint);
        }
 
        public void logException(JoinPoint joinPoint){
                logger.debug("In Exception method: "+joinPoint);
        }
}

Spring Config XML

Here we configure the AOP targets and the point cuts and specify the expression for identifying the pointcuts.

<bean id="taxService" class="com.myorg.service.TaxServiceImpl"/>
<bean id="loggingService" class="com.myorg.service.LoggingServiceImpl"/>

<aop:config>
    <aop:aspect ref="loggingService">  
        <aop:pointcut  id ="logMethod" expression="execution(* com.myorg.service.TaxService.*(..))"/>
 
        <aop:before  method="logEntry"  pointcut-ref="logMethod"/>
        <aop:after  method="logExit"  pointcut-ref="logMethod"/>
       <aop:after-throwing  method="logException"  pointcut-ref="logMethod"/>
 
    </aop:aspect>

</aop:config>

log4j properties

Place the below file in classpath to configure the log4j.

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

Testing:

Now that the configurations and code is in place, invoke the TaxService from any of the controllers and you will find the log statements for every method invoked on TaxService. This way, logging is separated out of the actual business logic. 

                                                                                                 Continued......

Thursday, September 26, 2013

Spring AOP - Part I

In this blog I'm going to write about AOP using Spring. 

Overview:

AOP which stands for Aspect Oriented Programming aims at separating out cross cutting concerns from the normal programming logic. This makes way for cleaner application code can focus on business logic and the other concerns like logging, security etc will be handled by the aspects.


Illustration:

To give a perspective of how AOP works, let us consider the following example:

Let us say, in a big city, there are no proper sign boards. So the city Mayor decides to take up a project to install sign boards. This project is like a cross cutting concern in some way. 

The city corporation will define certain rules to install the sign boards. 
Sign board rules:
  1. A sign board indicating 'school nearby' should be placed 5 meters from the school in both directions. 
  2. A sign board indicating a sharp curve should be placed 5 meters before the curve. 
  3. A sign board 'Thank you. Visit again' should be placed after the city exit.
  4. A sign board 'Welcome to the city' should be placed before entering the city.

Terminologies:

Now, let us try to correlate the above example with AOP. There are certain terminologies which are defined by AOP.
  1. Aspect: Module which defines the cross cutting concern.
  2. Advice: Defines the task to be done by the cross cutting concern. In the above example, it is the display contents of the sign board.
  3. Join Point: Defines the exact places where the advice should be applied. Spring AOP supports only method level advices.
  4. Point cut: An expression which identifies the Join Point. In our example, this could be the identifying places like school, city exit etc.
  5. Introduction: Allows you to declare additional methods or fields.
  6. Target Object: The object which is being adviced.
  7. Weaving: The actual process of applying the advice. Spring AOP applies advice at run time using Dynamic Proxies (Refer this blog for more details on Proxy pattern).
Spring supports 5 types of advices:
  1. Before advice - The Advice executes before the specified join point. In the above eg, it is the sign board which is placed before the  sharp curve.
  2. After returning advice - The advice executes after the specified join point. (This happens only if the method did not throw any exception). In the above eg, it is the sign board after the city exit.
  3. After throwing advice - The advice executes when the method throws exception.
  4. After advice - The advice executes regardless of exception being thrown or not.
  5. Around advice - The advice surrounds the join point. It has provisions to execute some piece of code before and after the method execution. You can also chose whether to proceed with the method invocation or not. In the above eg, it is the sign board while entering the city and the city exit.

                                                                             Click here to continue....

Wednesday, September 18, 2013

Proxy Pattern

In this blog, I'm going to write about Proxy pattern and it's applications.


Definition:

Proxy is a Structural design pattern which works 'on behalf of' or 'in place of' another object in order to access the later.

Here proxy objects are used to perform the work on somebody's behalf. We will use proxy objects in the following scenarios:
  1. Lot of boilerplate code is required in order to invoke the real object.
  2. The access to the real object is limited and all the access needs to go through the proxy.
  3. The real object is a remote object

Illustration:

Let us take an example.

Lets say there is a King who lives in a palace and he has all kind of antique jewelry, paintings etc. John has a hobby of collecting antique items and he wants to purchase some antique items from the king. 

But the king will not part with his antique pieces so easily. He misses his good old glorious days in this modern era and hence the person who wants to purchase has to sing and praise the qualities of the king. Uh, surely the king misses yesteryears..

However, John is not interested nor good enough in singing and praising the king and he is quite sure that he will not be able to persuade the King to sell his antiques. So John hatches a plan. He hires a person (say, Danny the dwarf) who is well versed with the nuances of the king and can get the job done. Cool, John has one less thing to worry about.

So, John will instruct Danny on what antique items he is interested in and pays Danny. Danny in turn will go to the palace, sing and flatter the King and persuade him to sell them. Danny then hands over the antiques to John.

Perfect!..We just described the Proxy pattern. Danny is the proxy here, who works on behalf of John. The king is the 'subject' and John the client.

Implementation:

In real world, we will have one interface and two implementation classes; one implemented by the proxy and one the real implementor.

Let's say the interface is AntiqueSale as below, with a method say sellPaintings(long _cost);
public interface AntiqueSale{

    public Painting sellPaintings(long _cost);

}

The real implementation of this interface will lie with the King. It will remove the painting from the king's inventory and return it to the purchaser.
public class AntiqueSaleRealImpl{

    public Painting sellPaintings(long _cost){
              /*remove from inventory*/
              /*Other housekeeping stuff*/
              
              return painting;
    }
}

Lets take a look at the proxy implementation. It will have a reference to the real implementation and then sing, convince the king and finally would invoke the real implementation to get the antiques.

public class AntiqueSaleProxyImpl{
    private AntiqueSale antique = new AntiqueSaleRealImpl();

    public Painting sellPaintings(long _cost){
              /*Sing and praise the King*/
              /*Convince the King*/
              
              /*Invoke real implementation*/
              antique.sellPaintings(_cost);
              
              return painting;            
                            
    }

}

In real world, the proxy might do the following things:
  1. Implement the low level boiler plate code for remote access/security as in EJB remote proxies. 
  2. The real implementation might be fine grained which might require a series of invocations, and the proxy might act like a facade.

Dynamic proxies:

In the above example, we had to create a new proxy implementation class for every scenario which requires a proxy generation. So these proxies have to be generated at compile time.  But there could be scenarios where you would want to generate proxies on the fly at run time. Dynamic proxies come to our rescue to handle these situations.

java.lang.reflect package has an interface 'InvocationHandler'. This has a method invoke() which needs to be implemented. This method receives the method to be invoked as an argument, and the implementer of this interface can perform the necessary plumbing code before the actual method invocation.
public class GenericInvocationHandler implements InvocationHandler {
       Object invokeImpl;
       
       public GenericInvocationHandler(Object _invokeImpl){
               this.invokeImpl = _invokeImpl;
       }
       
       @Override
       public Object invoke(Object proxy, Method method, Object[] args)
                            throws Throwable {

                /*Do something before invoke*/
         method.invoke(invokeImpl, args);
                /*Do something after invoke*/
         return null;
 }
}

To create the proxy object, Proxy.newProxyInstance() could be invoked by passing in the required arguments as below. Note that a proxy class is generated at run time and returned back. Calls to hashcode(), toString(), equals() methods on the proxy class will be delegated to the actual implementor classes.

AntiqueSale antiqueProxy = (AntiqueSale) Proxy.newProxyInstance(AntiqueSale.class.getClassLoader(), new Class[]{AntiqueSale.class}, new GenericInvocationHandler(obj));


Applications of dynamic proxy:

  1. In Spring framework to implement AOP. Using dynamic proxies, Spring framework will be able to apply the 'advices'.
  2. Hibernate framework also extensively uses proxies.
  3. EJB remote proxy

Saturday, September 14, 2013

Spring Webflow Code example - Part IV

For previous parts:
For Part-I click on: Spring Webflow Code example - Part I

For Part-II click on: Spring Webflow Code example - Part II

For Part-II click on: Spring Webflow Code example - Part III

Lets create the third page which is to provide a complementary drinks, if the user has selected 'Indian Spicy Pizza'. Now since this page needs to be shown conditionally, we need to make use of 'action-state' element. Using this, we can evaluate a condition and then make the transition accordingly.

In the view-state for 'selectPizza', insert the transition for 'next' to a state 'complementaryDrinks'. This will actually be a action state as shown below.

Note the action state 'complementaryDrinks' will invoke a method hasComplementaryDrinks() to determine the transition.

Modify the pizza-order-flow.xml as below:
<view-state id="selectPizza" model="viewScope.newpizza">
        <on-render>
              <evaluate expression="pizzaOrderController.createPizza()" result="viewScope.newpizza"/>
        </on-render>
        <transition on="previous" to="customerDetails" />
        <transition on="add" to="selectPizza">                 
              <evaluate expression="pizzaOrderController.addPizza(flowScope.order,viewScope.newpizza)"/>
        </transition>
        <transition on="next" to="complementaryDrinks" />
        <transition on="clear" to="selectPizza">
              <evaluate expression="pizzaOrderController.clearPizzas(flowScope.order)"/>
        </transition>
        <transition on="cancel" to="cancelOrder" />
</view-state>
 
<action-state id="complementaryDrinks">
    <evaluate expression="pizzaOrderController.hasComplementaryDrinks(flowScope.order)" />
    <transition on="yes" to="showDrink" />
    <transition on="no" to="reviewOrder" />
</action-state>

<view-state id="showDrink">
     <transition on="previous" to="selectPizza" />
     <transition on="next" to="reviewOrder" />
     <transition on="cancel" to="cancelOrder" />
</view-state>

Controller changes:

Add new method hasComplementaryDrinks() which will check if the user has selected 'Indian Spicy Pizza'.

public String hasComplementaryDrinks(Order order){
         String outcome = "no";
         for(Pizza pizza: order.getPizzaList()){
             if("Indian Spicy Pizza".equals(pizza.getName())){
                   outcome = "yes";
                   break;
             }
         }
         return outcome;
}

New JSP for complementary message:

<form:form modelAttribute="pizza" action="${flowExecutionUrl}">
<h1><spring:message code="complimentMsg"/></h1>

<table width="30%"  border="0" cellspacing="3" cellpadding="1">
<tr><td>
     <button type="submit" id="previous" name="_eventId_previous">
           <spring:message code="previous"/>
     </button>
</td><td>
      <button type="submit" id="next" name="_eventId_next">
           <spring:message code="next"/>
      </button>
</td><td>
       <button type="submit" id="cancel" name="_eventId_cancel">
           <spring:message code="cancel"/>
       </button>
</td></tr>
</table>
</form:form>


Review Order page:

In this page, we will show the details from the first two pages for review. Clicking on 'submit' will submit the order for processing and provide an order Id back.

Modify 'pizza-order-flow.xml' to add the following view state.

<view-state id="reviewOrder" model="order">   
        <transition on="previous" to="selectPizza" />
        <transition on="submit" to="orderConfirmation" >
               <evaluate expression="pizzaOrderController.submitOrder(flowScope.order)" />
        </transition>
        <transition on="cancel" to="cancelOrder" />
</view-state>

The code sample for the controller and jsp for the next section are ommitted as they are pretty straight forward.
Create a method in the controller 'submitOrder' which will invoke a service to process the orde and update the order object with order number. 

Similarly create JSP page 'reviewOrder.jsp' and display the customer details and pizza selected along with the navigation buttons.




End states:

The end states define the state points at which the flow will terminate. In our example, we have two end states, one when the user has submitted the 'Review Order' page and one when the user has clicked on 'Cancel'. 

<end-state id="orderConfirmation"  view="orderConfirmation"/>
<end-state id="cancelOrder"  view="cancelOrder"/>


Create a JSP 'orderConfirmation.jsp' which will show the order number. 

This completes the webflow tutorial. I hope the example was complete enough to provide a simple flow up and running.

Friday, September 13, 2013

Spring Webflow Code example - Part III

For Part-I click on: Spring Webflow Code example - Part I
For Part-II click on: Spring Webflow Code example - Part II

Let's create the second page 'Select Pizza'. In this page, we will show a drop down of available pizzas. This page will have buttons 'Add', 'clear' in addition to navigation buttons 'Next', 'Previous', 'Cancel'.
Once the user has selected a pizza, the user can click on 'Add' button to add the pizza to the user's cart. The user can use the 'Clear' button to clear the cart, if he wants to start all over again.

Controller changes:

In order to initialize the collection for this drop down, we will create a new method 'initPizzaList' in the controller. We also need a method to initialize the Pizza object which will be the model for the jsp.

Further, we need a controller method 'addPizza' to update the Order model with the pizzas added. We also need a 'clearPizzas' method as well.

public List initPizzaList(){
                List pizzaList = new ArrayList();
                pizzaList.add("NY Cheese Pizza");
                pizzaList.add("Indian Spicy Pizza");
                pizzaList.add("Italian Special Pizza");
  
                return pizzaList;
}
public Pizza createPizza(){
               return  new Pizza();
  
}
 
public void addPizza(Order order,Pizza pizza){
                order.addPizza(pizza);
}
 
public void clearPizzas(Order order){
                order.clearPizzas();
}

Changes to pizza-order-flow.xml:

<view-state id="selectPizza" model="viewScope.newpizza">
        <on-render>
              <evaluate expression="pizzaOrderController.createPizza()" result="viewScope.newpizza"/>
        </on-render>
        <transition on="previous" to="customerDetails" />
        <transition on="add" to="selectPizza">                 
              <evaluate expression="pizzaOrderController.addPizza(flowScope.order,viewScope.newpizza)"/>
        </transition>
        <transition on="clear" to="selectPizza">
              <evaluate expression="pizzaOrderController.clearPizzas(flowScope.order)"/>
        </transition>
        <transition on="cancel" to="cancelOrder" />
</view-state>
If you observe the above view state, the model object is defined with view scope. This is because, the Pizza object will need to exist only till life span of the view and once user clicks on 'Add' this Pizza object will be added to the Order objects pizzaList.

The addPizza() method, will accept two parameters, first is the Order object from the flowScope and second is the Pizza object from the view scope. 

So, from the third page onwards, the view Scope 'Pizza' object will not be available and only the 'Order' object from the flow Scope will be available.

New JSP 'selectPizza.jsp'

Create a new jsp as below:
<form:form modelAttribute="newpizza" action="${flowExecutionUrl}">
<table width="40%"  border="0" cellspacing="3" cellpadding="1">
 
<tr>
<td><spring:message code="selectPizza"/></td>
<td><form:select path="name" items="${pizzaList}"/></td>
</tr>
 <tr>
<td><spring:message code="quantity"/></td>
<td><form:input path="quantity"/></td>
</tr>
</table>

<table width="20%"  border="0" cellspacing="3" cellpadding="1">
<tr><td>
<button type="submit" id="add" name="_eventId_add">
        <spring:message code="add"/>
</button>
</td><td>
<button type="submit" id="clear" name="_eventId_clear">
        <spring:message code="clear"/>
</button>
</td>
</tr>
</table>

<table width="40%" border="1" cellspacing="3" cellpadding="1">

<tr><th><spring:message code="pizzaName"/></th><th><spring:message code="quantity"/></th></tr>
<c:forEach items="${order.pizzaList}" var="pizza">
<tr>
<td>${pizza.name}</td>
<td>${pizza.quantity}</td>
</tr>
</c:forEach>
</table>

<table width="30%"  border="0" cellspacing="3" cellpadding="1">
<tr><td>
<button type="submit" id="previous" name="_eventId_previous">
       <spring:message code="previous"/>
</button>
</td><td>
<button type="submit" id="next" name="_eventId_next">
       <spring:message code="next"/>
</button>
</td>
<td>
<button type="submit" id="cancel" name="_eventId_cancel">
       <spring:message code="cancel"/>
</button>
</td></tr>
</table>

</form:form>



                                                                                               ....Click here to continue

Thursday, September 12, 2013

Spring Webflow Code example - Part II

For Part-I click on: Spring Webflow Code example - Part I

In order to invoke the webflow, let's create a link 'Create Order' in index.jsp. The link would refer to the path of the webflow xml.

index.jsp

<a href="http://www.blogger.com/webflowsample/pizza-order-flow.htm">Create Order</a>


Let's try to create the first Page "Customer details". Before landing on this page, we need to instantiate the model objects in controller. We will be adding new method to the controller for this.

Validation:

In the customer details page, let us try to validate 'First Name' for  mandatory field. Let us create a method to validate the customer in the controller. The method should follow a naming convention 'validateXXX' where XXX refers to the field name.

Changes to controller:

@Controller
public class PizzaOrderController {
        public Order createOrder(){
                Order order = new Order();
                Customer cust = new Customer();
                order.setCust(cust);
                return order;
        }
        public Event validateCust(Order order, MessageContext messageContext){
   
                          if(order.getCust().getFirstName() == null || order.getCust().getFirstName().trim() == ""){
                               MessageBuilder errorMessageBuilder = new MessageBuilder().error();
                               errorMessageBuilder.source("cust.firstName");
                               errorMessageBuilder.code("firstName.req");
                               messageContext.addMessage(errorMessageBuilder.build());
                               return new EventFactorySupport().error(this);
                 }
                 return new EventFactorySupport().success(this);
        }
}

Changes to Web Flow xml:

We need to invoke the 'createOrder' method before the first view of the webflow is displayed. So let's put this in 'on-start' as below.
Note that the result of the expression (which is the 'Order' object returned by the method) is put in flowScope. Webflow supports 5 scopes (conversation,flow,view,request,flash).
These scopes are internally managed by webflow and we can put objects in this scope by using a user defined key. A flowscope is valid till the end of the flow.

Let's add a view-state which is the view definition for our first page. The Id name should match the name of the view which we are going to show. (i.e, 'customerDetails').

Now, there are two possible transitions from this page: one is to second page (on click of next) and second is cancelling the order. So, we will add two transitions accordingly.

We have not yet invoked the validation logic. This should be validated upon click of 'next' button. So, lets invoke that as an expression within the transition to 'next' state.

<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow
                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
                          
        <on-start>
             <evaluate expression="pizzaOrderController.createOrder()" result="flowScope.order"/>
       </on-start>
        
        <view-state id="customerDetails" model="order">
             <transition on="next" to="selectPizza">
                 <evaluate expression="pizzaOrderController.validateCust(flowScope.order, messageContext)"/>
            </transition>     
            <transition on="cancel" to="cancelOrder" />
        </view-state>
                          
</flow>

JSP:

Let's create a jsp 'customerDetails.jsp'. Note that the action url should be '${flowExecutionUrl}' which is an implicit object provided by webflow. This will append the flow Id along with the URL. 

Now, this page needs two buttons, 'next' and 'cancel'. Clicking on next will take us to second page, whereas 'cancel' will cancel the ordering process. The button names should follow a certain naming convention for webflow to identify and process them. The names should be preceeded with '_eventId_'. So next button will have a name '_eventId_next'.

I'm not including the html formatting in the code segment to maintain clarity on what we are trying to accomplish.


<form:form modelAttribute="order" action="${flowExecutionUrl}">

<table width="30%"  border="0" cellspacing="3" cellpadding="1">
<tr>
    <td><spring:message code="firstName"/></td>
    <td><form:input path="cust.firstName"/></td>
    <td><form:errors path="cust.firstName" cssClass="error"/></td>
</tr>
<tr>
    <td><spring:message code="lastName"/></td>
    <td><form:input path="cust.lastName"/></td>
    <td><form:errors path="cust.lastName" cssClass="error"/></td>
</tr>
<tr>
    <td><spring:message code="email"/></td>
    <td><form:input path="cust.emailAddress"/></td>
    <td><form:errors path="cust.emailAddress" cssClass="error"/></td>
</tr>
</table>
<table width="20%"  border="0" cellspacing="3" cellpadding="1">
<tr><td>
    <button type="submit" id="next" name="_eventId_next">
        <spring:message code="next"/>
    </button>
</td>
<td>
    <button type="submit" id="cancel" name="_eventId_cancel">
        <spring:message code="cancel"/>
    </button>
</td></tr>
</table>

</form:form>




Cancel page:

Create a jsp 'cancelOrder.jsp' with a message for cancellation.
In the messages.properties file put a key value pair orderCancelMsg=Your order has been cancelled!

<spring:message code="orderCancelMsg"/>


                                                                                               ....Click here to continue

Tuesday, September 10, 2013

Spring Webflow Code example - Part I

This blog shows how to develop a Spring Webflow application having integration with Spring MVC. Spring WebFlow allows us to create a UI workflow with a series of page navigation and abiltity to navigate back and forth. It also provides a context to work with in addition to many other features.

Overview:

We will be creating a flow to order pizza with the following navigation pages. 

  1. The first page - Enter customer details
  2. The second page - Select pizza
  3. Review Order & submit
  4. Order confirmation

Now, in the second page, you get a few options to select the pizza you want. If the customer selects 'Indian Spicy Pizza', then we will offer free coke (The pizza provider is kind enough to provide some relief to customers after eating spicy stuff. :)  )

So, after the second page, if the customer selects 'Indian Spicy Pizza', then a page showing complimentary coke is displayed. This is conditional navigation.
After submitting the order in the third page, order confirmation page will be shown.

Creating project:

Create a Maven project with a archetype 'maven-archetype-webapp'.

pom.xml

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>
<dependencies>
    <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>3.8.1</version>
         <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <type>jar</type> 
      <scope>compile</scope>
    </dependency>  
    <!-- Spring 3 dependencies -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>    
      <groupId>org.springframework.webflow</groupId> 
      <artifactId>spring-webflow</artifactId>
      <version>2.3.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
</dependencies>

web.xml

<web-app id="WebApp_ID" version="2.4" 
        xmlns="http://java.sun.com/xml/ns/j2ee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>
 
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <!-- Welcome files --> 
 <welcome-file-list>  
     <welcome-file>index.jsp</welcome-file> 
        </welcome-file-list> 
</web-app>

Spring dispatcher servlet xml:

The servlet-name is 'mvc-dispatcher'. So we need a context xml with the name mvc-dispatcher-servlet.xml.

<beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:util="http://www.springframework.org/schema/util"  
        xmlns:webflow="http://www.springframework.org/schema/webflow-config"
        xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd 
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/webflow-config
        http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.3.xsd">   
        
        <context:component-scan base-package="com.myorg" />
        <mvc:annotation-driven/>
        
        <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename" value="messages"/>
        </bean>
        
        <bean id="myViewResolver"
                       class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
                       <property name="prefix">
                           <value>/WEB-INF/view/</value>
                       </property>
                       <property name="suffix" value=".jsp"/>
        </bean>
        
        <!-- Web flow configs -->
        
        <webflow:flow-registry id="flowRegistry" flow-builder-services="flowBuilderServices">
             <webflow:flow-location path="/WEB-INF/pizza-order-flow.xml" />
        </webflow:flow-registry>
 
        <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry" />
 
 
        <!-- Enables FlowHandler URL mapping -->
        <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
             <property name="flowExecutor" ref="flowExecutor" />
        </bean>
 
        <webflow:flow-builder-services id="flowBuilderServices" view-factory-creator="mvcViewFactoryCreator"/>
 
                <bean id="mvcViewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
                      <property name="viewResolvers" ref="myViewResolver"/>
                </bean>
  
        <!-- Maps request paths to flows in the flowRegistry; -->           
        <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
            <property name="flowRegistry" ref="flowRegistry"/>
            <property name="order" value="0"/>
        </bean>
  
</beans>  

Note the additional configuration for webflow integration. The FlowhandlerMapping and FlowHandlerAdapter are used to identify webflow requests.

Every webflow which is defined should be declared in a registry. Here we have provided the absolute path of the flow xml as '/WEB-INF/pizza-order-flow.xml'.

POJOs:

public class Order implements Serializable{
        private Customer cust;
        private List pizzaList;
        
        //Setters and Getters
}

public class Customer implements Serializable{
        private String firstName;
        private String lastName;
        private String emailAddress;
        
        //Setters and Getters
}

public class Pizza implements Serializable{
        private String name;
 private int quantity;
 
 //Setters and Getters
}

Controller:

We will have a single controller, PizzaOrderController which will be annotated with @Controller. We will add methods to this as we go along.

Web Flow xml:

Create a file 'pizza-order-flow.xml' within WEB-INF and this will have the flow related stuff. Following is the plain flow xml.

<flow xmlns="http://www.springframework.org/schema/webflow"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/webflow
                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
                          
                          
</flow>


                                                                                               ....Click here to continue

Friday, September 6, 2013

Spring Tips: Introduction

Spring framework is amazingly so vast and having tons of features that how much ever you learn, it would appear to be just a tip of the iceberg.

This series of blogs titled "Spring Tip" aims to provide Spring features in a small and concise manner without over diluting the content.

These blogs will have links to next and previous tips so that you can navigate back and forth and savor each tip. :)

PS: Special thanks to Venu for designing the buttons.



Next Tip


Wednesday, September 4, 2013

Building UI using Spring MVC - Part II

In continuation of my previous blog, in this blog we will see how session is handled and little more about spring tags.

Session Handling:

Spring MVC provides an annotation '@SessionAttributes' which will identify objects which need to be put in session. Spring container will take care of adding and updating these objects into the Session.

For eg.,
@SessionAttributes("user")
public class UserController{
   ....
}

The above annotation will inform the container that the object identified by "user" attribute in the Model will be stored in session. Further, in the controller method, we will create a ModelAndView object as usual and add the User object to it. 

The point to note here is that:

  1. Before a controller method is invoked, the sessionAttribute values are retrieved from session and the model object is updated.
  2. After controller method returns, the updated model values (only those annotated with SessionAttributes) are put back in session.
So, though the HttpSession object is available to you in controller methods, it is safer to use SessionAttributes instead.

Let us say, we need to put the logged in user's username into the session and retrieve it at different locations.

@SessionAttributes("loggedInUserName")
public class LoginController {
        @RequestMapping(value="/exampleweb/login", method=RequestMethod.POST) 
     public String login(@ModelAttribute @Valid User user, BindingResult result ) {
         boolean loginResult = loginService.login();
         if(!loginResult){
             return "loginFailure";
         }
         ModelAndView mav = new ModelAndView("home");
         /*Put the username in session*/
         mav.put("loggedInUserName",user.getUserName());
         
     }
}

Once the login method returns, the username is updated into the session scope. Later for example, in any of the JSP pages, we can retrieve this user name by using "${loggedInUserName}".

Custom binding of properties:

Lets say we need to have a custom conversion of the data sent in form post. For eg, Let us say, User has date of birth field as 'birthDate'. The UI will have a input field mapped to 'birthDate'. In order to convert this string to a proper date, we can use @initBinder annotation as below in the controller.
@InitBinder("user")
protected void initBinder(WebDataBinder binder) {

    binder.setValidator(new UserValidator());  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);

    binder.registerCustomEditor(Date.class, "birthDate", new CustomDateEditor(dateFormat, false));


}

The initBinder is mapped to model attribute "user". Also, we have created a SimpleDateFormat object to format date. This along with
Spring's CustomDateEditor is used to register our custom editor. You can also create your own extension of PropertyEditor and register that.

Note that we have registered this editor against a field "birthDate". If the user provides invalid date format, then this will throw an exception back.


Spring tags:

Apart from the form tag, spring tag offers quite a few interesting things as below:
1.  spring:bind tag:

<spring:bind path="birthDate">
 <div>${status.errorMessage}</div>
</spring:bind>

The spring:bind tag allows us to get the error details specific to a field (birthdate in above example). The status variable will indicate if there is a error for this field.

2.  spring:url tag:

In order to create a url which has parameters in it, we can use the spring:url tag as below:

<spring:url value="/exampleweb/users/user/{userId}" var="formUrl">
 <spring:param name="userId" value="${user.userId}"/>
</spring:url>

Sunday, September 1, 2013

Building UI using Spring MVC - Part I

In my previous blog, I wrote about implementing Restful services using Spring MVC. In this blog, we will see how to build a UI using Spring MVC.

Let us try to implement a UI to create a User. Again the intent is to show to use Spring MVC and hence we can reuse most of the artifacts from previous blog, except for the controller.


Create User URI:


Before landing on the jsp for creating a User, we will need some preprocessing to happen, which will include creation of User model and also model for drop downs if any (let us say a drop down to show Countries).

Now, there are two approaches to build the URI for create form as explained below.
1. Same URI for preprocesing as well as actual create.
In this approach, the same URI let us say '/example/users/user/new' will be used for preprocessing and user creation. The only difference being, for preprocessing we will use GET and for user creation (upon form submission) we will use POST.

@RequestMapping(value="/example/users/user/new", method=RequestMethod.GET) 
public ModelAndView preprocessCreateUser(){
   ........
}

This method will do the preprocessing and return the view name. The JSP form will look like:

<form:form commandname="user">
    ........
</form:form>
Note that there is no 'action' for this form. The same action attribute from the GET request is carried over to this form as well.  Upon submitting this form it will do a POST to the same controller and the method which supports POST will be invoked.
@RequestMapping(value="/example/users/user/new", method=RequestMethod.POST) 
public ModelAndView addUser(){
   ........
}

2. Use different URI for preprocess as well as user creation.

In this approach, the URI for preprocess will look like '/example/users/user/preprocess'.

The URI for user creation will look like '/example/users/user/new'.
These two URIs will map to the two methods preprocessCreateUser() and addUser() respectively.

In the jsp, we need to explicitly mention the action attribute for submission.
<form:form commandName="user" action="/example/users/user/new">
    ........
</form:form> 

The advantage with the second approach is easy to maintain. If your application is a huge one with lots of jsp pages, then looking at the jsp page you can figure out to which controller it is submitting to. This is something you cannot do with the first approach.

The index.jsp which serves as welcome page will have the link to create User.

<a href="/example/users/user/new">Create User</a>


Controller code:


Pre-processing and handling POST request:
@RequestMapping(value="/example/users/user/new", method=RequestMethod.GET) 
public ModelAndView preprocessCreateUser(){
  ModelAndView mav = new ModelAndView("addUser");
  User user = new User(); 
  mav.addObject("user",user);
  
  return mav;
}

@RequestMapping(value="/example/users/user/new", method=RequestMethod.POST) 
public String addUser(@ModelAttribute @Valid User user, BindingResult result ) 
                     throws UserCreateException{
       if(result.hasErrors()){
           return addUserErrorView;
       }
       userService.createUser(user);

       return addUserSuccessView;
}

Validation:


Validation could be performed by using either a separate validator implementation or by annotating the domain object by using JSR 303 annotation support. Here, we will use a separate validator.
public class UserValidator implements Validator {
       public boolean supports(Class _class) {
           return User.class.equals(_class);
       }
 
        public void validate(Object obj, Errors e) {
            ValidationUtils.rejectIfEmpty(e, "firstName", "firstname.empty", "first Name is empty");
     }
}

Note that the validator implements Spring Validator interface. The supports() method is to invoked by the Spring container to tie this validator to the corresponding model object. The key "firstName.empty" would be looked upon in the resource bundle file messages.properties.
To register this validator we use the @InitBinder annotation.

@InitBinder("user")
protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserValidator());
}

To invoke this validator we have to use the @Valid annotation on the model object in the method argument (see addUser() method above). Note that BindingResults argument will contain the error results and this method argument should always be present next to the model object.
The controller methods can accept various arguments like HttpRequest, HttpResponse, Model object in any order. The return type could be either a String which will indicate a view name or a ModelAndView object.
In the preprocessCreateUser() method which returns a ModelAndView object, the constructor argument "addUser" represents the view name. The User model object is added to the ModelAndView and this model object could be referenced in the view by the name "user". Note that this attribute name is optional, and if you do not specify any name Spring will add the lower case name as attribute name. For eg, the object Account could be referenced by the name "account", the list userList could be referenced by "userList" and so on.


View:

Let us write the JSP addUser.jsp
<form:form commandName="user">
    <!-- HTML constructs omitted-->
    <form:errors path="firstName"/>
    <form:input path="firstName"/>
 
    <form:errors path="lastName"/> 
    <form:input path="lastName"/>
    <button type="submit">Add User</button>
</form:form>

Use of PUT and DELETE:

The browsers do not support PUT and DELETE methods currently. To overcome this, Spring provides a response filter which should be configured in the web.xml as below:
<filter>
        <filter-name>httpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
        <filter-name>httpMethodFilter</filter-name>
        <servlet-name>mvc-dispatcher</servlet-name>
</filter-mapping>

In the JSP, we need to mention the form action method as PUT/DELETE. While rendering the view, the response filter would replace the PUT/DELETE with POST and will also place a hidden parameter as below. 
View source of the page would look like:
<form id="user" action="/example/users/user/1111" method="post">
<input type="hidden" name="_method" value="PUT"/>
This parameter is used by Spring, during submission to route the request to PUT/DELETE methods respectively.


Handling multiple submits:


If there are multiple submit buttons, lets say 'Save As Draft', 'Publish' etc, then we can use @RequestParam annotation with specific parameter names to distinguish each request.

@RequestMapping(value="/example/users/user/{userId}",params="actionParam=publish", method={RequestMethod.POST}) 
public String publish(){

}

View Names:

The view names could be hardcoded into the controller like we have done above. However, this would tightly couple the view and the controller. In order to avoid this, we can inject the view names into the controller. The view names could be stored in a properties file (lets say view.properties) and they could be referenced in the controller as below.
@Value("${addUserView}")
private String addUserView;

The @Value annotation injects the value into the addUserView variable. The "addUserView" key is also defined in view.properties as key/value pair "addUserView= addUser", where addUser is the jsp name.
This view.properties file should be placed in root of the classpath and the following entry in the dispatcher-servlet.xml file will help Spring to recognize and load the properties file:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
             <value>classpath:/view.properties</value>
        </property>
</bean>