Suggested Pages

Wednesday, May 30, 2012

Serialization

Serialization is the process of converting a data structure or object state into a format that can be stored.
In Java an object to be serialized must implement the java.io.Serializable interface.

Serialization and Inheritance


Suppose you have the following classes:
A.java

public class A implements Serializable {
  
  protected int variableA=3;
  
  public static void main(String [] args){
        B b=new B();
        b.variableA=4;
        b.variableB=7;
        serialize(b);
        b=(B) deserialize(b);
        System.out.println(b.variableA);  
        System.out.println(b.variableB);  

  }

  // this method serializes object o
  private void serialize(Object o){
     ...
  }
  // this method deserializes object o
  private Object deserialize(Object o){
     ...
  }
}

class B extends A {
      
   private int variableB=2;
}

The output of the program is the following

    4 
    7 
Because the class B extends A, B is automatically a serializable class. During ​​the deserialization no constructor of A and B is invoked, so the instance fields of A ​​and B are restored correctly.
Instead suppose your classes are:
A.java

 public class A {

  protected int variableA=3;

  public static void main (String [] args){
        B b=new B();
        b.variableA=4;
        b.variableB=7
        serialize(b);
        b=(B) deserialize(b);
        System.out.println(b.variableA);  
        System.out.println(b.variableB);        
  }

  // this method serializes object o
  private void serialize(Object o){
     ...
  }
  // this method deserializes object o
  private Object deserialize(Object o){
     ...
  }
}

  class B extends A implements Serializable{
     
    private int variableB=2;
 } 

The output of the program is the following

    3 
    7 


The value of the field variableA is not restored; its value is reinitialized to 3 value. During deserialization, the fields of the first non-serializable superclass (A class) will be initialized using the public or protected no-arg constructor of the class.

Serialization and Transient keyword

Suppose you have these classes:
A.java

 public class A implements Serializable{
    private B b=new B();
    private int variableA=3;

  public static void main (String [] args){
      A a =new A();
      serialize(a);       
 }

  class B {
     private int variableB=2;
 } 

}
In this case we'll have a Runtime Exception: throws NotSerializableException . This exception occurs because B is not marked as transient.
If an object doesn't implement Serializable interface, it must be marked with transient keyword. The consequence is that when you persist an instance of A, you'll find a null value in place of B state.

Monday, May 28, 2012

DispatcherServlet vs ContextLoaderListener

DispatcherServlet


Suggested Pages:


DispatcherServlet loads its configuration file using <servlet_name>-servlet.xml. You can configure a custom config file using contextConfigLocation param inside <init-param> tag of DispatcherServlet .

web.xml

<servlet>
 <servlet-name>addressbook</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring/spring-mvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>


spring-mvc.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           ">

<context:annotation-config />
 
 <context:component-scan base-package="com.simonefolinoblogspot.controller" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>

As you can see in this file there's only a scanning of @Controller annotated beans. This file should contain web tier components as:
  • Controllers
  • ViewResolvers
  • LocaleResolvers
  • ThemeResolvers
These components are not middle tier components.

ContextLoaderListener

ContextLoaderListener loads its configuration file using contextConfigLocation param.
web.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
 <param-value>classpath*:META-INF/spring/spring-context.xml</param-value>
</context-param>
<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

spring-context.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xmlns:cxf="http://cxf.apache.org/core"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.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/jee  http://www.springframework.org/schema/jee/spring-jee-3.0.xsd    http://www.springframework.org/schema/tx   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

   
 <context:annotation-config />

 <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" />

 <context:component-scan base-package="com.simonefolinoblogspot.dao" >
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>

     ...

</beans>


As you can see in this file there's not a scanning of @Controller annotated beans because we are interested into other annotated beans such as @Service, @Repository etc.. This file contains your middle tier and data tier components:
  • DAO: such as @Repository bean
  • Entity: such as @Entity bean
  • Service: such as @Service bean
Spring will merge all these components into ApplicationContext. Then the middle tier components is accessible from your web tier components.

Friday, May 25, 2012

Java Nested Classes: Inner Class, Static Class, Local Class

nested non-static classes (Inner Classes)

 public class OuterClass {
 
   private int id;
 
   private static String name="nome";

   class InnerBean {
  
     private int a;
  
     public void doThis(){
        System.out.println(OuterClass.name);
        System.out.println(OuterClass.this.id);
     }
  
   }

 }
The creation of an Inner class instance depends on the creation of the Outer class instance. Suppose you have just created an instance of the Outer class:
 OuterClass outerclass=new OuterClass();

To create the inner class you have to write the following code:
 InnerBean innerBean =outerclass.new InnerBean(); 

  • An Inner class can access static and instance variables of the Outer Class;
  • An Inner class can't declare static variable.


nested static classes


 public class OuterClass {
 
    private int id;
 
    private static String name="nome";

        static class InnerStatic {
  
            private int a;
  
            private static int b;
  
            public void doThis(){
              System.out.println(OuterClass.name);
           }
        }
 }
To create the nested static class you have to write the following code.
  Bean.InnerStatic innerStatic=new Bean.InnerStatic();
  • A nested static class is like a top-level class;
  • A nested static class can't access instance variables of the outer class.


Local Classes


public class OuterClass {
 
 private int id;
 
 private static String name="nome";

    public void doThis(){
        
        final String innername="hi!";
         
        class LocalInner{
      
            public void doThat(){
              System.out.println(innername);
            }
         }
    }
}

  • A Local Class is an InnerClass declared inside a block of code;
  • A Local Class can only access final variable declared in the same block code.

Thread States

Thread states are these shown below.

New

Threads are only created by the JVM after starting thread with start() method.

Ready

The thread is available to the scheduler, waiting to use the processor.

Running

The thread is using the processor.

Time Waiting

The thread must wait a determinate period before resuming.
Methods that take threads to this state are: sleep(long mill),wait(long mill), join(long timeout)

Waiting

Threads are wating for a condition to be verified.
Methods that take threads in this state are: wait(), join()

Blocked

Threads are wating for the availability of an implicit lock (monitor lock) because of synchronized code.

Terminated

A thread that has finished to work

Thursday, May 24, 2012

Immutable Objects

Immutable objects are objects whose state cannot change after construction. An Example of immutable objects from the JDK is the String class.

Immutable Objects Benefict

  • Thread-safe: there's no need of synchronization
  • Good Map keys

Immutable Object Guidelines


In order to create an immutable object:
  • Private constructors;
  • Avoid the Java Beans pattern creation (using set methods to inizialize);
  • Make fields private and final;
  • Make the class final;
  • Do not provide any methods which can change the state of the object;
  • Use defensively copied if the class has any mutable object fields.

The following class is an example of Immutable Class.
FootballMatch.java

import java.util.Date;


public final class FootballMatch {

 
 private final Date matchDate;
 
 private final String place;
 
 private final String guestTeam;
 
 private final String homeTeam;

 public FootballMatch(Date matchDate, String place, String guestTeam,
   String homeTeam) {
  super();
  this.matchDate =  new Date(matchDate.getTime());
  this.place = place;
  this.guestTeam = guestTeam;
  this.homeTeam = homeTeam;
 }

 public Date getMatchDate() {
  return new Date(this.matchDate.getTime());
 }

 public String getPlace() {
  return place;
 }

 public String getGuestTeam() {
  return guestTeam;
 }

 public String getHomeTeam() {
  return homeTeam;
 }
}

Tuesday, May 22, 2012

Hibernate vs JPA: Modifying persistent objects

In this post i will show how to modify a persisted object using hibernate and jpa language:

Hibernate

sess is the hibernate Session object. In this snippet code, the dog entity becomes a managed entity so changes to this object will be performed on the DB.
   
  Dog dog = (Dog) sess.load( Dog.class, new Long(20) );
  dog.setName("Sean");
  sess.flush(); 




JPA

em is the EntityManager object. In this snippet code, the dog entity becomes a managed entity so changes to this object will be performed on the DB.
   
  Dog dog = (Dog) em.find( Dog.class, new Long(20) );
  dog.setName("Sean");
  em.flush();  

Monday, May 21, 2012

Static block, Instance block and Constructor

Given the following class A which is the output of A a=new C(); ?

A.java
package a;
public class A {
 static {
      System.out.println(“1”);
 }
 {
      System.out.println(“2”);
 }
 A(){
      System.out.println(“3”);
  }
}

class B  extends A {
  static {
      System.out.println(“4”);
  }
  {
      System.out.println(“5”);
  }
  B(){
      System.out.println(“6”);
  }
}


class C  extends B {
  static {
      System.out.println(“7”);
  }
  {
      System.out.println(“8”);
  }
  C(){
      System.out.println(“9”);
   }
}


The output of the statement A a=new C(); is:
    1
    4
    7 
    2
    3  
    5 
    6  
    8 
    9 
  • 1 4 7 belong to static blocks: static blocks are called at startup
  • 2 belongs to A instance block: instance blocks are called each time an object is constructed
  • 3 belongs to A constructor
  • 5 belongs to B instance block: instance blocks are called each time an object is constructed
  • 6 belongs to B constructor
  • 8 belongs to C instance block: instance blocks are called each time an object is constructed
  • 9 belongs to C constructor
A constructor is called before the B constructor and B constructor is called before the C constructor because we don't have to forget that each time a constructor is invoked, the java virtual machine goes to inizialize the superclass constructor.

Sunday, May 20, 2012

JPA: queries with P6spy driver

Many Java developers know the property showSql that allows to see all JPA queries. Unfortunately the query format is something like this:
insert into ExampleSchema.Contacts (number, id) values (?, ?).
You can't see the real parameters, but in their place, there are question marks. In order to see all SQL queries in clear, we have to use the framework: P6spy.

The configuration of this framework requires only three steps:

Step-1: Replace the driverClass in your datasource with P6SpyDriver


Datasource without P6SpyDriver

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="org.hsqldb.jdbcDriver" />
  <property name="jdbcUrl" value="jdbc:hsqldb:mem:ex" />
  <property name="user" value="sa" />
  <property name="password" value="" />
 </bean>


Datasource with P6SpyDriver
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 
  <property name="driverClass" value="com.p6spy.engine.spy.P6SpyDriver"/> 
  <property name="jdbcUrl" value="jdbc:hsqldb:mem:SN"/> 
  <property name="user" value="sa"/> 
  <property name="password" value=""/> 
 </bean> 
As you can see, we have replaced only the driverClass.

Step-2: Put spy.properties in classe folder


In the following snippet I'll show the most common properties for customizing P6Spy framework. You have to notice in particular two properties:
  • realdriver property: it is set to value: org.hsqldb.jdbcDriver;
  • useprefix property: it is set to false because it's not used any prefix in jdbcUrl property of datasource bean.


# real driver
realdriver=org.hsqldb.jdbcDriver
useprefix=false
deregisterdrivers=true
module.log=com.p6spy.engine.logging.P6LogFactory

executionthreshold=

outagedetection=false
outagedetectioninterval=

# filter what is logged
filter=false

# comma separated list of tables to include when filtering
include     =
# comma separated list of tables to exclude when filtering
exclude     =

# sql expression to evaluate if using regex filtering
sqlexpression =


# turn on tracing
autoflush   = true

# sets the date format using Java's SimpleDateFormat routine
dateformat=yyyy-MM-dd hh:mm:ss

#list of categories to explicitly include
includecategories=

#list of categories to exclude: error, info, batch, debug, statement,
#commit, rollback and result are valid values
excludecategories=info,debug,result,batch



#stringmatcher=com.p6spy.engine.common.GnuRegexMatcher
#stringmatcher=com.p6spy.engine.common.JakartaRegexMatcher
stringmatcher=

# prints a stack trace for every statement logged
stacktrace=false

# if stacktrace=true, specifies the stack trace to print
stacktraceclass=

# determines if property file should be reloaded
reloadproperties=false


reloadpropertiesinterval=60


#appender=com.p6spy.engine.logging.appender.Log4jLogger
appender=com.p6spy.engine.logging.appender.StdoutLogger
append=true

log4j.additivity.p6spy=false

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=p6spy - %m%n


log4j.logger.p6spy=DEBUG,STDOUT




Step-3: Insert p6spy dependency into your pom.xml


pom.xml
  <dependency>
   <groupId>p6spy</groupId>
   <artifactId>p6spy</artifactId>
   <version>1.3</version>
   <scope>test</scope>
  </dependency>

Supposing that your application writes on the Console, you can see SQL queries in clear.

2012-05-15 02:02:37|6|0|statement||CREATE SCHEMA ExampleSchema AUTHORIZATION DBA
2012-05-15 02:02:39|18|0|statement||select sequence_name from information_schema.system_sequences
2012-05-15 02:02:39|3|0|statement||
    create table ExampleSchema.Contacts (
        id integer not null,
        number varchar(255),
        primary key (id)
    )
------------testSaveContact(): start -------
Hibernate: 
    insert 
    into
        ExampleSchema.Contacts
        (number, id) 
    values
        (?, ?)
2012-05-15 02:02:39|1|0|statement|insert into ExampleSchema.Contacts (number, id) values (?, ?)|insert into ExampleSchema.Contacts (number, id) values ('22xxxx', 1)
2012-05-15 02:02:39|0|0|commit||
------------testSaveContact(): end -------
------------testRetrieveContact(): start -------
Hibernate: 
    select
        contact0_.id as id0_0_,
        contact0_.number as number0_0_ 
    from
        ExampleSchema.Contacts contact0_ 
    where
        contact0_.id=?
2012-05-15 02:02:39|1|0|statement|select contact0_.id as id0_0_, contact0_.number as number0_0_ from ExampleSchema.Contacts contact0_ where contact0_.id=?|select contact0_.id as id0_0_, contact0_.number as number0_0_ from ExampleSchema.Contacts contact0_ where contact0_.id=1
2012-05-15 02:02:39|-1||resultset|select contact0_.id as id0_0_, contact0_.number as number0_0_ from ExampleSchema.Contacts contact0_ where contact0_.id=1|number0_0_ = 22xxxx
2012-05-15 02:02:39|0|0|commit||
Contact [id=1, number=22xxxx]
------------testRetrieveContact(): end -------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.512 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

Saturday, May 19, 2012

Overriding and Shadowing

Overriding


In Java, overriding applies to instance methods. The mechanism of method overriding is to run the method of the dynamic type at runtime.
Suppose you have the following classes:
A.java
public class A {
  public void doThis(){
      System.out.println("A");
  }
}
class B extends A{
  public void doThis(){
      System.out.println("B");
  }
}

class C extends B{
  public void doThis(){
      System.out.println("C");
  }
}

Main.java
public class Main {
  public static void main(String[]args){
          A a =new C();
          a.doThis();
  }
}
If we launch the above Main class we have the following output:
Console
  C
As you can see, the method of dynamic object type has been chosen.

Variable Shadowing


With regard to the instance variables the mechanism is called shadowing. Shadowing for instance variables depends on the static type and not dynamic type.
Suppose you have the following classes:
A.java

 package a;
 
 public class A {
   int variable=1;
 }

 class B extends A {
   int variable=2;
 }

 class C extends B {
   int variable=3;
 }

Main.java
 public class Main {

  public static void main (String [] args){
     A a =new C();
     System.out.println(a.variable);     
     B b=new C();
     System.out.println(b.variable);  
 
  }

 }

If we launch the above Main class we have the following output:
Console
     1  
     2
As you can see the static type has been chosen. The instance variable printed on the console depends only on the static type.

Method shadowing


We cannot say that overriding applies to static method. If you create a static method in the subclass with the same signature, at runtime you will not see overriding for that method.
A.java
 package a;
public class A {
     public static void doThis() {
           System.out.println(“A”);
     }
 }

class B extends A {
     public static void doThis() {
         System.out.println(“B”);
     }
}

Main.java
 public class Main {

  public static void main (String [] args){
    A.doThis();     
    B.doThis();  
 
  }

 }
If we launch the above Main class we have the following output:
Console
    A
    B
As you can see the static type has been chosen. The static method chosen only depend on the static type.

Tuesday, May 15, 2012

Unit Test with Maven, Spring and HSQLDB - Tutorial

In my programming experience, I have learnt the importance of making unit tests on persistence functionalities. In this post I'll show a way to test persistence functionalities with Maven, Spring and HSQLDB.

HSQLDB


When you develop a software that has to store data, you usually prepare a testing local database. With HSQLDB used in memory mode you can test persistence unit of work in your local machine in easy way. The database is not persistent and exists entirely in random access memory.

Maven - Surefire Plugin


Maven has a lifecycle composed by different phases. During the test phase maven use the the Surefire Plugin to execute the unit tests of an application. You should put your testing code at src/main/test. Then calling mvn clean test you can execute your tests.

Spring - SpringJUnit4ClassRunner


Spring has a package org.springframework.test.context that provides annotation-driven unit and integration test support. It also provides a custom runner class called SpringJUnit4ClassRunner that permit to run your test.

Now Suppose you have a DAO that has only two methods: saveContact and retrieveContact.

ContactDAO.java
package com.simonefolinojavablog.persistence.dao;

import com.simonefolinojavablog.persistence.entity.Contact;

public interface ContactDAO {

 public void saveContact(Contact contact);
 
 public Contact retrieveContact(int idContact);

}



ContactDAOImpl.java
package com.simonefolinojavablog.persistence.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.simonefolinojavablog.persistence.entity.Contact;

@Repository(value = "ContactDAO")
public class ContactDAOImpl implements ContactDAO {

 @PersistenceContext(unitName = "persistenceUnitTest")
 private EntityManager entityManager;

 @Transactional(propagation = Propagation.REQUIRED)
 public void saveContact(Contact contact) {
  entityManager.persist(contact);
 }

 @Transactional(propagation = Propagation.REQUIRED)
 public Contact retrieveContact(int idContact) {
  return entityManager.find(Contact.class, idContact);
 }

}

Contact.java
package com.simonefolinojavablog.persistence.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Contacts",schema="ExampleSchema")
public class Contact {

 @Id
 @Column
 private int id;
 
 @Column
 private String number;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getNumber() {
  return number;
 }

 public void setNumber(String number) {
  this.number = number;
 }

 @Override
 public String toString() {
  return "Contact [id=" + id + ", number=" + number + "]";
 }

}
ContactDAOImpl implements simply the storing and the retrieving of Contact class. Both ContactDAOImpl and ContactDAO are located at src/main/java in Maven's structure.
If you are interested in testing these two functionalities, you can create ContactDAOTest class at src/main/test in Maven's structure, as shown below.

ContactDAOTest.java
package com.simonefolinojavablog.persistence.test;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.simonefolinojavablog.persistence.dao.ContactDAO;
import com.simonefolinojavablog.persistence.entity.Contact;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "ContactDAOTest-context.xml")
public class ContactDAOTest {

 @Autowired
 private ContactDAO contactDAO;

 private static Contact contact;
 
 @BeforeClass
 public static void initContact(){
  contact=new Contact();
  contact.setId(1);
  contact.setNumber("22xxxx");
 }

 @Test
 public void testSaveContact() {
  System.out.println("------------testSaveContact(): start -------");
  contactDAO.saveContact(contact);
  System.out.println("------------testSaveContact(): end -------");
 }
 
 @Test
 public void testRetrieveContact() {
  System.out.println("------------testRetrieveContact(): start -------");
  Contact retrieveContact = contactDAO.retrieveContact(contact.getId());
  System.out.println(retrieveContact);
  System.out.println("------------testRetrieveContact(): end -------");
 }
 

}
As you can see ContactDAOTest uses two annotations at class level:
  • @RunWith: tells the runner class that JUnit will invoke instead of the runner built into JUnit;
  • @ContextConfiguration: tells the path where is located application context to load for this test;
Annotations as @Test, @BeforeClass are the same annotations you use in JUnit.

The file shown below is ContactDAOTest-context that represents the application context loaded by the class ContactDAOTest.
In this file, four important beans are declared:
  • dataSource: the datasource c3p0 used to connect to HSQLDB (in memory mode);
  • transactionManager: org.springframework.orm.jpa.JpaTransactionManager;
  • entityManagerFactory: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean. It has an attribute depends-on="schemaGenerator" which it means that entityManagerFactory depends on the bean schemaGenerator. This bean is called by the container before initializing entityManagerFactory ;
  • schemaGenerator: a bean that creates the schema where entity beans will be stored.

ContactDAOTest-context

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
 xmlns:cxf="http://cxf.apache.org/core"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.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/jee  http://www.springframework.org/schema/jee/spring-jee-3.0.xsd    http://www.springframework.org/schema/tx   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

 <!-- annotation support -->
 <context:annotation-config />

 <!-- support for transaction -->
 <tx:annotation-driven />

 <!-- scan package for @Repository annotations -->
 <context:component-scan base-package="com.simonefolinojavablog.persistence.dao">
  <context:include-filter type="annotation"
   expression="org.springframework.stereotype.Repository" />
 </context:component-scan>


 <!-- HSQLDB datasource -->
 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="org.hsqldb.jdbcDriver" />
  <property name="jdbcUrl" value="jdbc:hsqldb:mem:ex" />
  <property name="user" value="sa" />
  <property name="password" value="" />
 </bean>
  
 <bean id="entityManagerFactory" depends-on="schemaGenerator"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitName" value="persistenceUnitTest" />
  <property name="dataSource" ref="dataSource" />
  <property name="jpaVendorAdapter">
   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
    <property name="generateDdl" value="true" />
   </bean>
  </property>
 </bean>

 <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  <property name="entityManagerFactory" ref="entityManagerFactory" />
  <property name="dataSource" ref="dataSource" />
 </bean>

 <bean id="schemaGenerator" class="com.simonefolinojavablog.persistence.test.SchemaGenerator">
  <property name="schema" value="ExampleSchema" />
  <property name="dataSource" ref="dataSource" />
 </bean>

</beans>
SchemaGenerator.java
package com.simonefolinojavablog.persistence.test;

import javax.sql.DataSource;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;


public class SchemaGenerator implements InitializingBean {

    private String schema;
    private DataSource dataSource;

    public String getSchema() {
        return schema;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public DataSource getDataSource() {
        return dataSource;
     }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

     public void afterPropertiesSet() throws Exception {
     JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.execute("CREATE SCHEMA " + schema + " AUTHORIZATION DBA");
    }
}
Finally you have to declare the dependencies in your pom.xml in order to use the features described above. In this snippet i'll show the main dependencies you need. It's important to notice that hsqldb and c3p0 have test scope because they are only used for test aims.

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>3.0.4.RELEASE</version>
   <scope>compile</scope> 
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
   <version>3.0.4.RELEASE</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
   <version>3.0.4.RELEASE</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>3.5.5-Final</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate.javax.persistence</groupId>
   <artifactId>hibernate-jpa-2.0-api</artifactId>
   <version>1.0.0.Final</version>
  </dependency>
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-log4j12</artifactId>
   <version>1.5.8</version>
   <exclusions>
    <exclusion>
     <artifactId>slf4j-api</artifactId>
     <groupId>org.slf4j</groupId>
    </exclusion>
   </exclusions>
  </dependency>
  <dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
   <version>1.8.0.10</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>c3p0</groupId>
   <artifactId>c3p0</artifactId>
   <version>0.9.1.2</version>
   <scope>test</scope>
  </dependency>

What you'll see from the console is the following output:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.simonefolinojavablog.persistence.test.ContactDAOTest
------------testSaveContact(): start -------
Hibernate: 
    insert 
    into
        ExampleSchema.Contacts
        (number, id) 
    values
        (?, ?)
------------testSaveContact(): end -------
------------testRetrieveContact(): start -------
Hibernate: 
    select
        contact0_.id as id0_0_,
        contact0_.number as number0_0_ 
    from
        ExampleSchema.Contacts contact0_ 
    where
        contact0_.id=?
Contact [id=1, number=22xxxx]
------------testRetrieveContact(): end -------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.596 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

Sunday, May 13, 2012

Maven Dependency Mediation vs Dependency Management


Transitive Dependencies


Maven manages transitive dependencies with a mechanism to discover and include dependencies automatically.
Maven first reads the dependencies inside the pom.xml of your project and then it navigates the pom.xml of those dependencies with no limit in the number of levels analyzed. Problems are only caused by cyclic dependency.
To manage this automatic mechanism of discovering transitive dependencies , you can use a specific area inside the pom.xml intended for dependencies.
These sections are: <dependencymanagement> and <dependencies>.

In the next part of this post we'll see the difference between two techniques used to control dependencies: Dependency Mediation and Dependency Management.

Dependency Mediation


Dependency Mediation determines which version of the dependencies will be used in a situation where, in the same project there are different versions of the same artifact. Maven 2.0 only supports the mechanism of the "nearest definition" which means it will be used only version dell'artifact whose dependency is closest to the project in the tree of dependencies. As an example, if the arrows indicate the dependencies between an artifact and the other:
  • A-> B-> C-> D (2.0)
  • A-> E-> D (1.0) WINNER
Wins the version 1.0 of D for the build of the artifact A, because the path from A to D is shorter passing through E rather than through B. If you want to change this behavior would simply add the dependence D (version 2.0) to A to force the use of D with that version.

Dependency Management


The Dependency Management provides:
  1. Consolidate and centralize the management of versions of the dependencies without the addition of dependencies that are inherited by all children. This is particularly useful when you have a number of projects (ie more than one) who inherits a common parent.
  2. Having control over the versions of artifacts used in the transitive dependencies
  3. Define a standard version of an artifact to be used on multiple projects
  4. Allows you to specify, for a certain project, the version of the artifact to be used when it is encountered in the transitive dependencies or independencies where the version has not been defined. Given a project A, it may include D as a dependency (in the Dependency Management) in order to check the version of D in the case it should be be used

Dependency Mediation vs Dependency Management


The Dependency Management has priority over Dependency Mediation , but only for transitive dependencies. If the dependence is not transitive but is direct, it's taken into account the direct one.

Saturday, May 12, 2012

SoftReference vs WeakReference and Cache Implementation

The main difference between SoftReferences and WeakReferences is that SoftReferences are less aggressive.
A WeakReference tells the Garbage Collector that it can remove an object because there's no need to give it long live, instead a SoftReference tells the Garbage Collector that an object can stay in memory as long as it has no memory needs. A SoftReference, for this reason, is a better candidate than a WeakReference to implement a Cache.
In this post we are going to compare two different caches: the first made with SoftReferences and the second made with WeakReferences. Both the caches work in this manner:
  • Cache hit:vthe system return an entry;
  • Cache missed: the system retrieves the entry out of the cache and then it puts the entry in the cache before it returns.

In the code shown below, there are two classes called ImageLoader. The former makes use of a cache implemented with SoftReference (SoftReferenceCache), the latter makes use of a cache implemented with WeakReference (WeakReferenceCache). As you can see if a cache hit occurs the entry is returned and if a cache missed occurs, a new ValueCache is created and put in the cache. Actually this is an escamotage because ValueCache is usually retrieved in a different manner.

ImageLoader.java (SoftReferenceCache)

package com.simonefolinojavablog.softreferencecache;

import java.util.logging.Level;

public class ImageLoader {

 private static SoftReferenceCache<String, ValueCache> cache = new SoftReferenceCache<String, ValueCache>();

 public static ValueCache getImage(String key) {
  
  ValueCache result = null;

  ValueCache valueCache = (ValueCache) cache.get(key);

  if (valueCache == null) {
   ProjectLogger.PROJECT_LOGGER.getLogger().log(Level.INFO,"entry: " + key + " result: cache miss");
   ValueCache newValue = new ValueCache();
   newValue.setKey(key);
   cache.put(key, newValue);
   result = newValue;
  } else {
   ProjectLogger.PROJECT_LOGGER.getLogger().log(Level.INFO,"entry: " + key + " result: cache hit");
  }
  return result;
 }
}

SoftReferenceCache.java

package com.simonefolinojavablog.softreferencecache;

import java.lang.ref.SoftReference;
import java.util.HashMap;

public class SoftReferenceCache<K extends Comparable<K>, V> {

 private HashMap<K, SoftReference<V>> map = new HashMap<K, SoftReference<V>>();
 
 public V get(K key) {
  SoftReference<V> softReference = map.get(key);

  if (softReference == null) {
   return null;
  } 
  return softReference.get();
 }

 public void put(K key, V value) {
  map.put(key, new SoftReference<V>(value));
 }

}
ImageLoader.java (WeakReferenceCache)

package com.simonefolinojavablog.weakreferencecache;

import java.util.logging.Level;

public class ImageLoader {

 private static WeakReferenceCache<String, ValueCache> cache = new WeakReferenceCache<String, ValueCache>();

 public static ValueCache getImage(String key) {

  ValueCache result = null;

  ValueCache valueCache = (ValueCache) cache.get(key);

  if (valueCache == null) {
   ProjectLogger.PROJECT_LOGGER.getLogger().log(Level.INFO,"entry: " + key + " result: cache miss");
   ValueCache newValue = new ValueCache();
   newValue.setKey(key);
   cache.put(key, newValue);
   result = newValue;
  } else {
   ProjectLogger.PROJECT_LOGGER.getLogger().log(Level.INFO,"entry: " + key + " result: cache hit");

  }
  return result;
 }

}

WeakReferenceCache.java


package com.simonefolinojavablog.weakreferencecache;

import java.lang.ref.WeakReference;
import java.util.HashMap;

public class WeakReferenceCache<K extends Comparable<K>, V> {

 private HashMap<K, WeakReference<V>> map = new HashMap<K, WeakReference<V>>();
 
 public V get(K key) {

  WeakReference<V> WeakReference = map.get(key);

  if (WeakReference == null) {
   return null;
  } 
  return WeakReference.get();
 }

 public void put(K key, V value) {
  map.put(key, new WeakReference<V>(value));
 }

}

These two different caches have different behaviour. Suppose that the Heap increases because of many Strong References, then the cache made with WeakReferences returns many cache miss sooner than the cache made with SoftReferences.

In a future post i'll describe the usage of WeakHashMap

Example of Spring Interceptors - Tutorial

In this post we'll see an example of a Spring Interceptor.
The Interceptor shown in this post is called LoggerInterceptor. It writes on the console before and after the Controller serves the request. Actually it writes on the console to make simple this example.

Step-1: Create Interceptor class


LoggerInterceptor class extends HandlerInterceptorAdapter and overrides preHandle, postHandle and afterCompletion.

LoggerInterceptor.java

package com.simonefolinojavablog.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoggerInterceptor extends HandlerInterceptorAdapter {

 @Override
 public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
  System.out.println("Before handling the request");
  return super.preHandle(request, response, handler);
 }

 @Override
 public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  System.out.println("After handling the request");
  super.postHandle(request, response, handler, modelAndView);
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
   throws Exception {
  System.out.println("After rendering the view");
  super.afterCompletion(request, response, handler, ex);
 }

}

Step-2: Spring Context


In the Spring Context configuration we have to activate the support to annotations. Then we have to declare the interceptor created in the first step (LoggerInterceptor) and the intercepted request paths using <mvc:interceptors/> tag as shown below.

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <context:annotation-config />

 <context:component-scan base-package="com.simonefolinojavablog.spring.controller" />


 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/firstcontroller/*.htm" />
   <bean id="loggerInterceptor" class="com.simonefolinojavablog.spring.interceptor.LoggerInterceptor" />
  </mvc:interceptor>
 </mvc:interceptors>
 
</beans>

Friday, May 11, 2012

Spring MVC Custom Validator

In this post we'll see an example of a form data validation. This form has two fields: number and type. I use a Controller to manage the request and a custom Validator to validate the form.
If some errors occur during validation, we'll show error messages just above each field that has caused the problem.

Step-1: Create a POJO class representing the object you want to validate and the JSP page containing the form


As you can see Contact is a class that has two fields: number and type. This class contains exactly the fields of the form.

Contact.java

package com.simonefolinojavablog.spring.bean;

public class Contact {


 private int number;

 private String type;

 public int getNumber() {
  return number;
 }

 public void setNumber(int number) {
  this.number = number;
 }

 public String getType() {
  return type;
 }

 public void setType(String type) {
  this.type = type;
 }

 @Override
 public String toString() {
  return "Contact [number=" + number + ", type=" + type + "]";
 }
}


The following JSP has a form with two input text: type and number. The form tag specifies both the modelAttribute (the bean that maps the form) and the action (the request URL).

form.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>


<html>
<head>
<title>Form Page</title>
</head>

<body>

 <form:form id="" action="/springmvc-validator/contacts/save.htm" modelAttribute="contact"
  method="POST">
  <table>
   <thead>
    <tr>
     <th>Fields</th>
    </tr>
   </thead>
   <tbody>
    <tr>
     <td> <form:errors path="number" cssClass="error" element="div" />
     number: <input type="text" name="number" value="" /></td>
    </tr>
    <tr>
     <td> <form:errors path="type"  ssClass="error" element="div" />
      type: <input type="text" name="type" value="" /></td>
    </tr>
    <tr>
     <td><input type="submit" name="save" value="save" /></td>
    </tr>
   </tbody>
  </table>
 </form:form>

</body>


</html>




Step-2: Create a Validator


In the following code is shown a subclass of Validator: CustomValidator. We have to override two methods of Validator class: supports that tells which kind of bean has to be validated and validate that contains the logic of validation.

ContactValidator.java

package com.simonefolinojavablog.spring.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.simonefolinojavablog.spring.bean.Contact;

@Component
public class ContactValidator implements Validator {

 @Override
 public boolean supports(Class clazz) {
  return Contact.class.equals(clazz);
 }

 @Override
 public void validate(Object target, Errors errors) {
  Contact contact =(Contact)target;
  System.out.println("contact:"+contact+"  validating...");
  ValidationUtils.rejectIfEmptyOrWhitespace(errors, "type", "errors.empty.type","error occur");
 }

}

Step-3: Create a Controller class


ContactController is a controller that makes use of a Validator to validate instances of Contact.
In this controller i use two annotations:
  • @InitBinder(value = "contact") to bind the object of type Contact whose name is contact and to register a custom validator for instances of Contact class.
  • @Valid to validate binding instance of Contact class with the Validator registered

If errors occur the controller returns to form View otherwise it returns to result.

ContactController.java

package com.simonefolinojavablog.spring.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.simonefolinojavablog.spring.bean.Contact;
import com.simonefolinojavablog.spring.validator.ContactValidator;

@Controller
@RequestMapping(value = "/contacts")
public class ContactController {

 @InitBinder(value = "contact")
 protected void initBinder(WebDataBinder binder) {
  binder.setValidator(new ContactValidator());
 }

 @RequestMapping(value="/save",method = RequestMethod.POST)
 public String saveContact(@ModelAttribute(value = "contact") @Valid Contact contact,BindingResult errors, ModelMap modelMap) {
  
  if (errors.hasErrors()) {
   System.out.println("some errors occur");
   return "form";
  }
  return "result";
 } 
}

Step-4: Create an errors.properties file


We have to create a file that contains error messages, and declare the location of this file in Spring configuration.

errors.properties
errors.empty.number=number field is empty
errors.empty.type=type field is empty
typeMismatch.contact.number=type mismatch Contact Number
typeMismatch.java.lang.NumberFormatException=5. Invalid value for {0}, accepts only numbers. 
typeMismatch.java.lang.Integer=Must specify an integer value. 
typeMismatch.java.lang.Long=Must specify an integer value. 
typeMismatch.java.lang.Float=Must specify a decimal value. 
typeMismatch.java.lang.Double=Must specify a decimal value.  
typeMismatch.int=Invalid number entered 
typeMismatch=Invalid type entered

In Spring configuration we use a special bean called ResourceBundleMessageSource that points the properties files managed by Spring context.

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <context:annotation-config />

 <context:component-scan base-package="com.simonefolinojavablog.spring" />

 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
     <property name="basenames">
      <list>
       <value>errors</value>
      </list>
     </property>
    </bean>
      ...

</beans>


Step-5: Put into web.xml the information to load the root web application context


As you can see, we have to declare ContextLoaderListener because we need to load the root application context and not just the web application context. I'm going to speak about the difference between root application context and web application context in another post.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">
    <display-name>SpringMVCValidator</display-name>
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:META-INF/spring/springcontext-*.xml</param-value> 
   </context-param>
   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>  
   <servlet>
        <servlet-name>SpringMVCValidator</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/spring-mvc.xml</param-value>
        </init-param>
          <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
         <servlet-name>SpringMVCValidator</servlet-name>
         <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

</web-app>

Wednesday, May 9, 2012

Spring MVC - First Controller

In this post we are going to see how to write a simple controller in Spring using annotation support.

Step-1: Load Spring Servlet Context


First of all we have to declare the servlet of Spring that acts as a Front Controller. Besides we have to declare the URLs served by the DispatcherServlet.
web.xml

<web-app version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>SpringMVCExample</display-name>
   <servlet>
        <servlet-name>SpringMVCExample</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/spring-mvc.xml</param-value>
        </init-param>
          <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
         <servlet-name>SpringMVCExample</servlet-name>
         <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

</web-app>

Step-2: Create Controller class


In the following code there's a simple controller FirstController. The annotations involved in this class are:
  • @Controller : tells Spring that this class is a Controller
  • @RequestMapping on the class level means the controller serves the requests sent to this path: protocol://hostname:<port>/<context>/firstcontroller/
  • @RequestMapping on the method level means that the method serves the requests sent to this path: protocol://hostname:<port>/<context>/firstcontroller/method1

FirstController.java

package com.simonefolinojavablog.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/firstcontroller")
public class FirstController {
 
 @RequestMapping("/method1")
 public String processRequestMethod1(){
  System.out.println("processRequestMethod1");
  return "example";
 }

 @RequestMapping("/method2")
 public String processRequestMethod2(){
  System.out.println("processRequestMethod2");
  return "example";
 }

}

Step-3: Spring Context Configuration


In the web.xml we have specified spring-mvc.xml as the configuration file. In spring-mvc.xml we specify that we are going to use annotation support and the package to search for annotation as @Service,@Controller etc...
  • <context:annotation-config>:support to annotations
  • <context:component-scan base-package="com.simonefolinojavablog.spring.controller">: search the annotations as @Service, @Controller
  • InternalResourceViewResolver: special bean that makes possible to refer to Views using simply the name of JSP

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           ">

 <context:annotation-config />


 <context:component-scan base-package="com.simonefolinojavablog.spring.controller" />



 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

</beans>


Step-4: Create a JSP to redirect the web flow


The method of the FirstController returns example that is the name of the JSP to put in the directory WEB-INF/pages/example.jsp
example.jsp
<html>
<head>
<title>Landing Page</title>
</head>

<body>Hi, your first controller works fine!

</body>


</html>


Step-5: Client

Now we have to call the web application at the link http://localhost/${context}/firstcontrollert/method1.htm or http://localhost/${context}/firstcontrollert/method2.htm.
The controller redirects the web flow to example.jsp and you can see processRequestMethod1 or processRequestMethod2 in the console, depending on which method has served the request.

Sunday, May 6, 2012

Container Managed Transaction (CMT) vs Bean Managed Transaction (BMT)

The main difference between BMT and CMT is:
  • BMT means the Bean manages the transaction.
  • CMT means the container manages transactions.

BMT Example


In the following example you can see ReservationService, it is a Session Stateless Bean that manages the transaction using explicitly calls as begin, commit and rollback.
ReservationServiceRemote.java

//package and import

@Remote
public interface ReservationServiceRemote {

 public Reservation prenota(String nomeFilm, int numPosti, int clientId);
}

ReservationService.java

//package and import

@Stateless
@TransactionManagement(TransactionManagementType.BEAN) 
public class ReservationService implements ReservationServiceRemote {

 @Resource
 private UserTransaction tx;


 @Override
 public Reservation prenota(String nomeFilm, int numPosti, int clientId) {
  Reservation reservation =null;
  try {
   tx.begin();
   System.out.println("transaction begin");
    reservation= .....
   tx.commit();
   System.out.println("transaction commit");
  } catch (Exception e) {
   try {
   tx.rollback();
   System.out.println("transaction rollback");
   } catch (IllegalStateException e1) {
       // log
   } catch (SecurityException e1) {
       // log
   } catch (SystemException e1) {
       // log
   }
  } 
  return reservation;
 }

Example CMT


CMT doesn't need to use explicitly begin, commit, etc.. The container does it for you. As you can see FilmService is a Stateless Session Bean that uses @PersistenceContext annotation to inject the EntityManager. There's no transaction explicitly opened, it's done by the container as soon as you use a method of the EntityManager. The transaction commits only at the end of the method.

FilmServiceRemote.java

//package and import

@Remote
public interface FilmServiceRemote{
 
 public void addFilm(String filmName);
 
}

FilmService.java

//package and import

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class FilmService  implements FilmServiceRemote{

 @PersistenceContext(unitName = "reservations")
 private EntityManager entityManager;
 
 public void addFilm(String name) {
  Film film = new Film();
  film.setName(name);
  entityManager.persist(film);
 }
 
}


Transaction Propagation


Here it is some rules:
  • A Bean Managed Transaction cannot be shared with other Beans that use BMT.
  • A Container Managed Transaction can join the transactions opened by Beans that make use of a BMT.

Saturday, May 5, 2012

Struts Internationalization

In this post we see how internationalization works in the framework Struts 1.X.

Step 1: Create a Struts Action


We have to create a Java Class that extends an action of Struts framework. The Action in the following code has the only function to forward the requests to a JSP called simpleForward.
InternationalizationAction.java

package com.simonefolinojavablog.struts_internationalization.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;


public class InternationalizationAction extends MappingDispatchAction{

 
 public ActionForward simpleForward(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
  return mapping.findForward("simpleForward");
 }
 
}



Step 2: Declare inside struts-config.xml the presence of internationalization files


In the configuration file struts-config.xml we have to put the location of the files containing labels for the internationalization.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>

 <action-mappings>

  <action path="/internationalization" 
          scope="request"
          parameter="simpleForward" 
         type="com.simonefolinojavablog.strut_internationalization.action.InternationalizationAction">
   <forward name="simpleForward" 
            path="/jsp/simpleForward.jsp" />
  </action>

 </action-mappings>

        <!--ApplicationResources is the name of the file containing labels -->
 <message-resources parameter="ApplicationResources" />

</struts-config>


Step 3: Create files with extension .properties containing labels


You have to create a file for each language you want to provide for your web application. Each file must contain the same set of label keys and the values of these keys have to differ in the language used.
ApplicationResources_en.properties

welcome.label=Welcome!


ApplicationResources_it.properties

welcome.label=Benvenuto!


Step 4: Create JSP that use labels


We have declared for the Action, a View to use (simpleForward.jsp). Now we have to create it.
simpleForward.jsp

<%@ page language="java"%>
<%@ taglib prefix="bean" uri="http://struts.apache.org/tags-bean"%>

<html>
<head></head>
<body>

 <bean:message key="welcome.label" />

</body>
</html>
<br/>


Conclusion


If we connect to the web application, when the InternationalizationAction is called, it forwards us to the JSP simpleForward.jsp. This page has been internationalized, so if you use an italian client agent you can see Benvenuto! otherwise if you use an English client agent you can see Welcome!.

Thursday, May 3, 2012

Java Overriding

In this post we are going to show the main rules to know on Java Overriding.

Example-1 overriding does not work successfully if the return type of the overridden method and the return type of the overriding method are different primitive types


The following class does not compile successfully because the return type of method doThis of the Child class is not covariant with the return type of method doThis of the Parent class

package example;
public class Parent {
 double doThis(double d){}
}

 class Child extends Parent {
 float doThis(double d){} 
}

Example-2 overriding works successfully with covariant return types


The following class, compiles successfully because the return type of method doThis of Child class (String) is covariant with the return type of the method of Parent class (Object).

package example;

public class Parent {
  public Object doThis() {}
}

class Child extends Parent{
  public String doThis() {}
}

Example-3 overriding method can throw less exceptions than the overridden method, but not different exceptions


The following class compiles successfully because the method doThis of Parent class throws IOException, instead the method doThis of class Child doesn't throw any Exception
package example;
public class Parent {
void doThis() throws IOException {}
}

class Child extends Parent {
void doThis() {}
}

Example-4 overriding methods can throw any subclasses of the Exception thrown by the overridden methods


The following class compiles successfully because the overriding method of class Child is throwing a subclass exception (E1) of the exception thrown by the overridden method of class Parent (E).
 
package example;
public class Parent {
 void doThis() throws E {}
}

class Child extends Parent {
void doThis() throws E1{}
}

class E extends Exception {}
class E1 extens E{}
class E2 extends E{}

Example-5 primitive types are not subclasses of wrapper classes


The following class does not compile successfully because wrapper classes are not covariant with Java primitive types.
 
package example;
public class Parent {
public int doThis(){..}

}
class Child extends Parent {
  public Integer doThis(){..}
}

Example-6 private methods can't be overridden


The following class compiles successfully because the private method of Parent class is not visible to subclasses and then it can't be overridden by any subclasses. Therefore you can put a method in the subclass (Child) with the same method signature of doThis method of class Parent.
 

package example;

public class Parent {
   private void doThis() {...}
}

class Child extends Parent{
   public void doThis() {...}
}

Example-7 reduce the visibility of the overridden method is not allowed


The following class does not compile successfully because the method doThis of class Child reduces the visibility of overridden method.

package example;

public class Parent {
 public void doThis() {...}
}

class Child extends Parent{
 private void doThis() {...}
}

Tuesday, May 1, 2012

Example of JSP Custom Taglib


In this post we see how to create a custom taglib using Maven 2.0 to build and manage the project. Most of people working in the IT sector know the usefullness of custom taglib over scriptlet code, but because of projects that require frequent releases, create a custom taglib seems usually a waste of time.
However, many developers can agree with me in saying that a waste of time is analyze code in order to find bugs inside JSP pages made with scriptlet code.
Use a custom taglib, forces the developers to do a deep analysis on the real needs of applications; they have to understand what kind of utilities or macros are needed. In fact, a custom taglib is a sort of macro that may be used in different part of the project. In this post you can see a taglib that performs a trim of a String. Not exactly what you need in a large web application, but suppose you need something more difficult, you can complicate and improve this taglib. The result will be a good feedback in term of clearness and reusability.

Step 1: Add dependencies in your pom.xml


A custom taglib, mainly, consists of : a jar to put inside WEB-INF/lib directory and a file with tld extension to put inside WEB-INF directory. The jar contains the java class that implements your specific logic and the file with tld extension the description of attributes of new tag.
We choose to build it with Maven 2.0 so we have to write in our pom.xml the required dependencies to develop taglib class. As you can see these dependencies have a provided scope, because jsp-api and servlet-api are provided by the container (Tomcat or JBoss for example).

<dependencies>
   <dependency>
    <groupid>javax.servlet</groupid>
    <artifactid>jsp-api</artifactid>
    <version>2.0</version>
    <scope>provided</scope>
   </dependency>
   <dependency>
    <groupid>javax.servlet</groupid>
    <artifactid>servlet-api</artifactid>
    <version>2.4</version>
    <scope>provided</scope>
   </dependency>
 </dependencies>


Step 2: Create a Java Class that extends TagSupport


This Java Class performs only a simple trim of a String after checking it's not null and not empty.

package com.simonefolinojavablog;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class TrimTagLib extends TagSupport {

 private String var;

 private int scope;

 public int doStartTag() throws JspException {

  String attribute = (String) pageContext.getAttribute(var, scope);

  if (attribute != null && !attribute.equals("")) {
   String attributeTrimed = attribute.trim();
   JspWriter out = pageContext.getOut();
   try {
    out.print(attributeTrimed);
   } catch (IOException e) {
   }
  }

  return (SKIP_BODY);
 }

 public String getVar() {
  return var;
 }

 public void setVar(String var) {
  this.var = var;
 }

 public int getScope() {
  return scope;
 }

 public void setScope(int scope) {
  this.scope = scope;
 }

}


Step 3: Create a file trim.tld


Create a file trim.tld and put it under WEB-INF/ directory of your web application. As you can see there are two attributes: var e scope. The former describes the variable you want to trim, the latter describes the scope to search this variable . Both the variables are mandatories.

<taglib version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">

 <description>JSTL 1.1 core library</description>
 <display-name>Custom Taglib</display-name>
 <tlib-version>1.1</tlib-version>
 <short-name>trim</short-name>
 <uri>http://com.simonefolinojavablog/trim</uri>

 <tag>
  <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
  <name>trim</name>
  <tag-class>com.simonefolinojavablog.TrimTagLib</tag-class>
  <body-content>empty</body-content>
  <attribute>
   <name>var</name>
   <required>true</required>
   <rtexprvalue>false</rtexprvalue>
  </attribute>
  <attribute>
   <name>scope</name>
   <required>true</required>
   <rtexprvalue>false</rtexprvalue>
  </attribute>
 </tag>
</taglib>

Step 4: Write the path to your file web.xml


Within web.xml, write the path to your file trim.tld and the URI that identifies the taglib.

<web-app version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        ...
 <jsp-config>
    
    <taglib>
        <taglib-uri>http://com.simonefolinojavablog/trim</taglib-uri>
               <taglib-location>/WEB-INF/trim.tld</taglib-location>
    </taglib>
 </jsp-config>
         ...

</web-app>

Step 5: Use taglib inside a JSP


Inside JSP pages we have to put the declaration of our custom taglib with the prefix that you're going to use in your jsp code. Notice that scope='3' it's a form of hard-coding of PageContext.SESSION_SCOPE whose value is 3. Obviously you can do better, providing a mapping inside TrimTagLib class but i prefered not to get it complex at this time. This JSP is telling to search an attribute with the name "Description" in Session scope.

 <%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@taglib prefix="trim" uri="http://com.simonefolinojavablog/trim" %>
<html>
   <body>
   <trim:trim var='Description'  scope='3'/>
    </body>
</html>

Suggested Pages