Monday, December 9, 2013

Hibernate Tutorial - Part V

For previous posts, refer:
Hibernate tutorial Part - I
Hibernate tutorial Part - II
Hibernate tutorial Part - III

Hibernate tutorial Part - IV

In this post, we are going to take a look at ' Table per subclass' approach for inheritance.


Table per subclass:

This strategy, represents inheritance relationships as relational foreign key associations.Every class/subclass that declares persistent properties, including abstract classes and even interfaces has its own table.

Unlike the table per concrete class strategy, the table here contains columns only for each non inherited property (each property declared by the subclass itself) along with a primary key that is also a foreign key of the super class table.

Lets take a look at the class definitions and annotations:

User Class:

@Entity
@Table(name = "USER") 
@Inheritance(strategy=InheritanceType.JOINED)  
public class User implements Serializable{
     @Id    
     @Column(name = "USER_ID")
     private String userId;
     
     @Column(name = "USERNAME")
     private String userName;
     
     @Column(name = "PASSWORD")
     private String password;
     
     //setters and getters
}

Customer Class:

@Entity
@Table(name="CUSTOMER") 
@PrimaryKeyJoinColumn(name="USER_ID") 

public class Customer extends User implements Serializable{
     
     @Column(name = "ADDRESS1")
     private String address1;
     @Column(name = "ADDRESS2")
     private String address2;
     @Column(name = "CITY")
     private String city;
     @Column(name = "STATE")
     private String state;
     @Column(name = "COUNTRY")
     private String country;
     
     //setters and getters
}

InternalUser Class:

@Entity
@Table(name = "INTERNAL_USER") 
@PrimaryKeyJoinColumn(name="USER_ID") 
public class InternalUser extends User implements Serializable{
     /*Admin/Non Admin*/
     @Column(name = "ACCESSTYPE")
     private String accessType;
     /*Contract/Permament*/
     @Column(name = "EMPLOYMENTTYPE")
     private String employmentType;
     
     //setters and getters
}

Note:
1. For every record for subclass, there will be a record in USER table as well. For eg, if we save Customer and InternalUser, then there will be one record each in INTERNAL_USER AND CUSTOMER and two records in USER.
2. Hibernate uses outer join to query subclass data


Disadvantage of this approach:

Involves a number of joins to join child tables. This could cause issues when there is a huge hierarchy with lot of subclasses.

                                                Continued...

Thursday, December 5, 2013

Hibernate Tutorial - Part IV

For previous posts refer:
Hibernate tutorial Part - I
Hibernate tutorial Part - II
Hibernate tutorial Part - III

In this post, we will take a look at 'Table per class hierarchy' strategy of inheritance.


Table Per Class hierarchy:

In this approach, an entire class hierarchy can be mapped to a single table. This table includes columns for all properties of all classes in the hierarchy. The concrete subclass represented
by a particular row is identified by the value of a type discriminator column.

Lets take a look at the classes and their annotations:

User Class:

@Entity
@Table(name = "USER") 
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(     name="USER_TYPE",     discriminatorType=DiscriminatorType.STRING )
@DiscriminatorValue(value="U") 
public class User implements Serializable{
     @Id    
     @Column(name = "USER_ID")
     private String userId;
     
     @Column(name = "USERNAME")
     private String userName;
     
     @Column(name = "PASSWORD")
     private String password;
     
     //setters and getters
}

Customer Class:

@Entity
@Table(name="USER") 
@DiscriminatorValue(value="C")     
public class Customer extends User implements Serializable{
     
     @Column(name = "ADDRESS1")
     private String address1;
     @Column(name = "ADDRESS2")
     private String address2;
     @Column(name = "CITY")
     private String city;
     @Column(name = "STATE")
     private String state;
     @Column(name = "COUNTRY")
     private String country;
     
     //setters and getters
}

Internal User Class:

@Entity
@Table(name = "USER") 
@DiscriminatorValue(value="I")
public class InternalUser extends User implements Serializable{
     /*Admin/Non Admin*/
     @Column(name = "ACCESSTYPE")
     private String accessType;
     /*Contract/Permament*/
     @Column(name = "EMPLOYMENTTYPE")
     private String employmentType;
     
     //setters and getters
}

Note:
@DiscriminatorColumn - Is used to define the discriminator column for the SINGLE_TABLE and JOINED inheritance mapping strategies. The strategy and the discriminator column are only specified in the root of an entity class hierarchy or sub hierarchy in which a different inheritance strategy is applied.

@DiscriminatorValue- Is used to specify the value of the discriminator column for entities of the given type.

Table Structure:
Single Table User with the following columns. Note the USER_TYPE column is used to distinguish between different entities.

USER_ID
USERNAME
PASSWORD
ADDRESS1
ADDRESS2
CITY
STATE
COUNTRY
USER_TYPE
ACCESSTYPE

EMPLOYMENTTYPE


Disadvantages of this approach:

  1. Columns for properties declared by subclasses must be declared to be nullable.
  2. Schema is not normalized. We’ve created functional dependencies between nonkey columns, violating the third normal form.
The advantage of this approach compared to others is performance. Since we have to query only a single table, this approach provides very good performance.

                                                Continued...




Wednesday, December 4, 2013

Hibernate Tutorial - Part III

For previous parts refer:
Hibernate tutorial Part - I
Hibernate tutorial Part - II


Inheritance Mapping:

In this post, I'm going to write about Inheritance mapping in Hibernate.

Essentially, there are 3 different types of inheritance mapping which could be achieved:
  1. Table per concrete class 
  2. Table per class hierarchy
  3. Table per subclass

1. Table per concrete class

In this type of mapping, we will have a table mapped to every concrete class in the hierarchy. Lets say we have the following class hierarchy for representing different users of the system.

  • Abstract class, User
  • Concrete subclass, Customer
  • Concrete subclass, InternalUser
Lets take a look at the class definitions and the the annotations for each of these classes.

User Class:

@Entity
@Table(name = "USER") 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public class User implements Serializable{
     @Id    
     @Column(name = "USER_ID")
     private String userId;
     
     @Column(name = "USERNAME")
     private String userName;
     
     @Column(name = "PASSWORD")
     private String password;
     
     //setters and getters
}

Customer Class:

@Entity
@Table(name="CUSTOMER") 
    @AttributeOverrides({     
        @AttributeOverride(name="userName", column=@Column(name="FIRSTNAME")),     
        @AttributeOverride(name="password", column=@Column(name="LASTNAME")) })
public class Customer extends User implements Serializable{    
     @Column(name = "ADDRESS1")
     private String address1;
     @Column(name = "ADDRESS2")
     private String address2;
     @Column(name = "CITY")
     private String city;
     @Column(name = "STATE")
     private String state;
     @Column(name = "COUNTRY")
     private String country;
     
     //setters and getters
}

Internal User Class:

@Entity
@Table(name = "INTERNAL_USER") 
public class InternalUser extends User implements Serializable{
     /*Admin/Non Admin*/
     @Column(name = "ACCESSTYPE")
     private String accessType;
     /*Contract/Permament*/
     @Column(name = "EMPLOYMENTTYPE")
     private String employmentType;
     
     //setters and getters
}

Note:@Inheritance defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy.

Table structure:
The table USER will have columns USER_ID,USERNAME,PASSWORD.
The table CUSTOMER will have all the columns as in USER plus additional columns.
The table INTERNAL_USER will have all the columns as in USER plus additional columns.

Notice that the primary key (USER_ID) is present in all the three tables and is shared across these tables.

Disadvantages of this approach:

  1. The columns in the super class are duplicated in all the child tables.
  2. Difficult to represent FK relationships. Lets say we have a class LoginDetails, which has association with User (either Customer or InternalUser). From a schema point of view, LOGIN_DETAILS table should have a FK to the CUSTOMER table or INTERNAL_USER table. We cannot represent this polymorphic representation effectively in SQL, as we will need two columns to represent this FK.
  3. Changes to the super class fields will cause changes to all the child class tables.
  4. The Sql to fetch child class will result in large number of selects.
  5. You cannot use AUTO/Identity column for the primary key.
                                                                                                 Continued...

Sunday, November 10, 2013

Hibernate Tutorial - Part II

For part I refer:
Hibernate tutorial Part - I

In this post we will see how the entity mapping is done. Lets take an example of a library management application for simplicity and take a look at the various possible mappings.

Lets say we need to create an entity 'Book'. We will create a Book POJO. This will be mapped to a table named 'Book'. The book table will have the following columns.

  1. BOOK_ID (Primary Key, Type: Number) driven by sequence book_id_seq
  2. BOOK_NAME (Type: Varchar2(50)
  3. PUBLISH_DATE (Type: Date)
  4. BOOK_PREVIEW (Type: clob)
The Book class with entity annotations will be as below:

@Entity 
@Table(name="book")
@org.hibernate.annotations.Entity(
        dynamicUpdate = true
)
public class Book implements Serializable{

    private static final String BOOK_SEQUENCE = "book_id_seq";

    @Id
    @Column(name="BOOK_ID")
    @SequenceGenerator(
         name=BOOK_SEQUENCE,
         sequenceName=BOOK_SEQUENCE)
         @GeneratedValue(strategy=GenerationType.SEQUENCE, generator=BOOK_SEQUENCE)
    private long number;
    
    @Column(name="BOOK_NAME")
    private String name;
    
    @Temporal(DATE)
    @Column(name="PUBLISH_DATE")
    private Date publishDate; 
    
    @Transient
    private boolean isPopular;
    
    @Column(name="BOOK_PREVIEW")
    @Lob
    @Basic(fetch=FetchType.LAZY)
    private String preview;
    
    public Book(){
    }
    
    //setters and getters

}

The annotations used above are described in detail:
  1. @table is used to map the class to a particular table. There are other options here like the inheritance strategy, which will be explained later.
  2. @column is used to map a field to a particular column. This annotation could be applied at field level or at method level (getter). It is advised to follow a common practice throughout.
  3. @Id is used to indicate primary key columns with an appropriate ID generator strategy as explained in the previous post. In the above example, we are using sequence generator strategy. The sequence name is mapped through 'sequenceName' option.
  4. @temporal is used to map date or timestamp fields. Possible values being TIME/DATE/TIMESTAMP.
  5. @Transient is used for fields which are not persistent and which will not be saved/retrieved to/from the database. In the above example, isPopular could be a derived field and  hence marked as transient.
  6. @lob is used to map CLOB or BLOB columns. In the above example, preview provides a brief description of the book and hence is a CLOB column. For blob types, you might want to use byte[] data type in java to represent the blob data.
  7. FetchType.Lazy is used to indicate lazy loading. By default, hibernate performs eager loading, which means all the properties are loaded when the entity is loaded. This strategy would cause performance issues when the property is a clob/blob field. In the above example, 'preview' is loaded lazily. i.e, loaded when the first call to the getPreview() is performed. 

Dynamic Inserts/Updates:

In the above example, we have annotated the Book class with Entity annotation from the hibernate package. The first one is from 'javax.persistence.Entity' package. The hibernate Entity annotation has two options 'dynamicInsert' and 'dynamicUpdate'.

What this means is that, while inserting or updating the Book table, Hibernate will insert only those columns whose values are non null. SImilarly, if dynamicUpdate is true, Hibernate will update only those columns whose values are not modified. Hibernate will keep track of which columns are modified in the current session. 
These two options will cause an increase in performance, if your tables have large number of columns and you have scenarios wherein, not all columns are inserted/updated every time. 

However, use this option with caution. If you blindly apply this strategy in every single case, then it might actually backfire. Since Hibernate has to keep dynamically prepare the statements and also has to apply additional conditions for null checking or checking for modified fields, this might actually bring down performance.  So exercise this option with care.

                                       Continued.....

Monday, November 4, 2013

Hibernate Tutorial - Part I

Overview:

Hibernate is an Object relational mapping (ORM) tool which will help us map Java objects to the underlying database objects. It will help us perform various operations on objects and hibernate will translate it to the DBMS operations and saves us from writing sql queries.

An equally important aspect is the importance of object orientated principles which need not be compromised when we use Hibernate. If we go with plain old sql style of design, then due to the disconnect between the object oriented design and the DBMS design, often the object oriented design is compromised.

For instance, concepts like inheritance, composition do not have a corresponding representation in the DBMS world. Similarly, we cannot truly represent a bi-drectional navigation and mapping between two entities (say for eg, Author and Book) in the DBMS world. These short comings could be overcome if we use Hibernate and we can minimize the influence of DBMS design on the object oriented design.

When we use Hibernate, we can map the entity classes (i.e POJO classes) to the corresponding database tables and the fields of the classes relate to the columns (explained in detail as we move along).

Hibernate Session:

Session is a single threaded object which keeps track of all the persistent objects within it. It offers CRUD operations for the mapped entity classes.  A transaction starts and ends within a session.

So a typical psuedo code while using session will look like:

  1. Open session
  2. Start transaction
  3. Save/Load objects into the session
  4. Commit transaction
  5. Close session
A session is obtained from a Session factory which is a thread safe object. The factory could be initialized through a Configuration object, by providing the connection details of the database. The configuration could be provided as a xml or as a properties file.
Hibernate supports use of third party connection pools which could be plugged in seamlessly.
C3p0 is a popular connection pool provider which could be used.

Entity Mappings:

The entity to schema mapping could be either provided as a xml file or as annotations within the entity class. We will be using annotations in the examples in the following posts.

The entity objects or the POJOs should follow the following rules:
  1. Needs no-arg constructor
  2. Could be abstract or extend non persistent class
  3. Class cannot be final and no final methods (for Proxy generation)

ID Generators:

For generating primary keys, Hibernate supports various types of ID generators to chose from.
  1. Native  - The native identity generator picks other identity generators like identity,sequence, or hilo, depending on the capabilities of the underlying database. Use this generator to keep your mapping metadata portable to different database management systems.
  2. Identity -This generator supports identity columns in DB2, MySQL, MS SQL Server, Sybase.
  3. Sequence - This generator supports sequences.
  4. Increment - This generator reads the maximum (numeric) primary key column value of the table and increments the value by one each time a new row is inserted.
  5. Hilo - A high/low algorithm is an efficient way to generate identifiers of type long, given a table and column (by default hibernate_unique_key and next, respectively) as a source of high values. The high/low algorithm generates identifiers that are unique only for a particular database. High  values are retrieved from a global source and are made unique by adding a local low value.
  6. Seqhilo - works like the regular hilo generator, except it uses a named database sequence to generate high values.
  7. Uuid.hex - generates a unique value based on appending the following values:IP Address,the startup time of current JVM,the current time,and counter value.It support all database and has no paameter.
  8. Guid - This generator provides a database-generated globally unique identifier string on MySQL and SQL Server.
  9. Select -This generator retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. An additional unique candidate key column is required for this strategy,and the key option has to be set to the name of the unique key column.
In the following posts, we will take a look at the various features of Hibernate along with code examples.

                                                                                                       Continued...

Wednesday, October 23, 2013

Building Webservices using Spring

In this post, I'm going to explain how to write a contract first webservice using Spring.

We are going to create a service for creating a person record. We are going to call the service as 'CreatePersonService'. It will accept first name, middle name and last name as parameters and return a id parameter back as a response.

We need to first define the XSD representing the person record. Also, we need an XSD to represent the request to create the Person record. 

Let us first start with the maven dependencies required:

pom.xml:

We will be using jaxb for generating classes from xsd.

<dependency> 
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws-core</artifactId>
    <version>2.1.3.RELEASE</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>
      
<dependency>
    <groupId>org.dom4j</groupId>  
    <artifactId>dom4j</artifactId>  
    <version>1.0</version>
    <type>jar</type>
    <scope>provided</scope>  
</dependency>   

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.0</version>
      <type>jar</type> 
      <scope>compile</scope>
</dependency>
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <type>jar</type> 
      <scope>compile</scope>
</dependency>
<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
</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</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
</dependency>

<dependency>
        <groupId>org.apache.ws.xmlschema</groupId>
        <artifactId>xmlschema-core</artifactId>
        <version>2.0.3</version>
</dependency>

Also in order to configure jaxb, you will need the following in the plugin section of pom.xml:
<plugin>  
        <groupId>org.codehaus.mojo</groupId>  
        <artifactId>jaxb2-maven-plugin</artifactId>  
        <version>1.4</version>  
        <executions>  
              <execution>  
                 <goals>  
                      <goal>xjc</goal>  
                 </goals>  
                 <phase>generate-sources</phase>  
              </execution>  
        </executions>  
        <configuration>  
            <clearOutputDir>false</clearOutputDir>  
            <outputDirectory>src/main/java</outputDirectory>  
            <schemaDirectory>src/main/webapp/schemas</schemaDirectory>  
            <includeSchema>**/*.xsd</includeSchema>             
            <enableIntrospection>false</enableIntrospection>  
        </configuration>  
</plugin>  


Service Interface and Implementation:

Create the following Interface and impl class:

public interface PersonService {
      public String createPerson(String firstName,String middleName,String lastName);
}

@Service
public class PersonServiceImpl implements PersonService{
       public String createPerson(String firstName,String middleName,String lastName){
                String userId = "";
                //Create Person
  
                return userId;
       }
}

Person XSD:

Create a xsd 'Person.xsd' in webapp/schemas folder to represent Person as below. Note the use of namespace attributes. I have used a namespace "http://schemas.myproduct.myorg.com". It will create package structure of the form "com.myorg.myproduct.schemas" for this namespace usage.


<?xml version="1.0" encoding="UTF-8"?>  
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns="http://schemas.myproduct.myorg.com" 
      targetNamespace="http://schemas.myproduct.myorg.com" 
      elementFormDefault="qualified" attributeFormDefault="unqualified">  

      <xs:element name="Person" type="Person"/>  
      <xs:complexType name="Person">  
           <xs:sequence>  
                <xs:element name="FirstName" type="xs:string"/>  
                <xs:element name="MiddleName" type="xs:string"/>  
                <xs:element name="LastName" type="xs:string"/>  
           </xs:sequence>  
      </xs:complexType>  
</xs:schema> 

CreatePersonOperation XSD:

Create a xsd 'CreatePersonOperation.xsd' in webapp/schemas folder to represent the request operation for our webservice as below.

<?xml version="1.0" encoding="UTF-8"?>  
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns="http://com/myorg/myproduct/webservices/createpersonservice" 
      targetNamespace="http://com/myorg/myproduct/webservices/createpersonservice" 
      elementFormDefault="qualified" attributeFormDefault="unqualified">
  
  
    <xs:element name="CreatePersonRequest">  
           <xs:complexType>  
                <xs:sequence>  
                      <xs:element name="FirstName" type="xs:string"/>
                        <xs:element name="MiddleName" type="xs:string"/>  
                 <xs:element name="LastName" type="xs:string"/>  
                </xs:sequence>  
           </xs:complexType>  
     </xs:element>  
     <xs:element name="CreatePersonResponse">  
           <xs:complexType>  
                <xs:sequence>  
                    <xs:element name="response" type="xs:string"/>  
                </xs:sequence>  
           </xs:complexType>  
      </xs:element>  
  
</xs:schema>

Changes to Spring config xml:

Add the following namespace attributes to the config xml. Also make sure the annotation config is there to allow spring container to create the necessary beans.

<beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:sws="http://www.springframework.org/schema/web-services"
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:context="http://www.springframework.org/schema/context"  
        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/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">  
        
     
       <context:component-scan base-package="com.myorg" />
       <mvc:annotation-driven/>
       <sws:annotation-driven/>
       
       <bean id="CreatePersonService" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition" lazy-init="true">  
         <property name="schemaCollection">  
         <bean class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">  
                <property name="inline" value="true" />  
                <property name="xsds">  
                        <list>  
                        <value>schemas/CreatePersonOperation.xsd</value>  
                        </list>  
                </property>  
                </bean>  
                </property>  
                <property name="portTypeName" value="CreatePersonService"/>  
                <property name="serviceName" value="CreatePersonService" />  
                <property name="locationUri" value="/endpoints"/>  
      </bean>      

</beans>

Changes to web.xml:

The webservice request will go through as a http request and is handled by the container. So we need to configure this in web.xml as below:

<servlet>  
        <servlet-name>webservices</servlet-name>  
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>  
            <init-param>  
                <param-name>transformWsdlLocations</param-name>  
                <param-value>true</param-value>  
            </init-param>  
            <init-param>  
                <param-name>contextConfigLocation</param-name>  
                 <param-value></param-value>  
            </init-param>  
            <load-on-startup>1</load-on-startup>  
       </servlet>  
       <servlet-mapping>  
            <servlet-name>webservices</servlet-name>  
            <url-pattern>*.wsdl</url-pattern>  
       </servlet-mapping>  
       <servlet-mapping>  
            <servlet-name>webservices</servlet-name>  
            <url-pattern>/endpoints/*</url-pattern>  
       </servlet-mapping>
</servlet>       

Endpoint Class:

Create a class which represents the webservice endpoint as below. Note that this class needs to be created after you compile the project once and there by generating the JAXB mapping classes from the xsd. I have also provided the import statements for this class for clarity.

package com.myorg.service.endpoint;

import org.springframework.beans.factory.annotation.Autowired;

import com.myorg.myproduct.webservices.createpersonservice.CreatePersonRequest;
import com.myorg.myproduct.webservices.createpersonservice.CreatePersonResponse;
import com.myorg.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;  
import org.springframework.ws.server.endpoint.annotation.RequestPayload;  
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;


@Endpoint
public class PersonServiceEndPoint {
private static final String TARGET_NAMESPACE = "http://com/myorg/myproduct/webservices/createpersonservice";
 
        @Autowired
        private PersonService personService;

  
        public void setPersonService(PersonService personService) {
                this.personService = personService;
        }




        @PayloadRoot(localPart = "CreatePersonRequest", namespace = TARGET_NAMESPACE)  
        public @ResponsePayload CreatePersonResponse createPerson(@RequestPayload CreatePersonRequest request) {
                CreatePersonResponse response = new CreatePersonResponse();
  
                String userId = personService.createPerson(request.getFirstName(), request.getMiddleName(), request.getLastName());
                response.setResponse(userId);
                return response;
        }
}


After compiling the project, you will notice that additional classes would have been created under com.myorg.myproduct.webservices.createpersonservice and com.myorg.myproduct.schemas  packages. Notice that a WSDL is not generated as a static resource file. Instead, the WSDL file is generated dynamically on the fly by the Spring container.

To test you can run the following in the browser to obtain the wsdl:
http://localhost:8080/testbed/endpoints/CreatePersonService.wsdl

Sunday, October 20, 2013

Popups using Javascript and CSS

In this post, I'm writing about an interesting way of displaying popups using javascript and css.

These popups do not show up in a new window, but rather in the same page as a different box. You might have seen these kind of popups while logging in or during display of your profile details in various social networking sites or email websites like gmail.

The idea here is to use css and div to display a box which embeds a separate html form of its own.
Lets first create a the form elements for login:

<div id="popupbox"> 
<form name="login" action="" method="post">
<div id="centertag">Username:</div>
<div id="centertag"><input name="username" size="14" /></div>
<div id="centertag">Password:</div>
<div id="centertag"><input name="password" type="password" size="14" /></div>
<a href="javascript:document.form.submit();"">
<div id="centertag">
        <span id="squares">
             <div id="1"><span>Login</span></div>    
        </span>
</div>
</a>
</form>
<br />
</div> 

The centertag style is used center align the login fields. The squares style is used to show the square box substitute for button (showing 'Login'). However, the style to look for is the 'popupbox' which will create the login popup box. Note that we have used absolute positioning to place the login box in the required position.

Lets take a look at the css styles:

<style type="text/css">
  #popupbox{
      margin: 0; 
      margin-left: 40%; 
      margin-right: 40%;
      margin-top: 50px; 
      padding-top: 10px; 
      width: 20%; 
      height: 150px; 
      position: absolute; 
      background: #FFFFFF; 
      border: solid #68BEC9 1px; 
      z-index: 9; 
      font-family: arial; 
      visibility: hidden; 
  }
  
  #centertag{
      text-align: center;
      margin-bottom: 5px; 
  }
 
  #squares div {
      display: block;
      float: left;

      width: 112px;
      height: 30px;
      line-height: 30px;
      background: #E0E0E0;
      text-align: center;
      font-family: Arial, Helvetica, sans-serif;
      border: solid #68BEC9 1px; 
      margin-right: 5px; 
  }
  span {
      display: inline-block;
      vertical-align: middle;
      line-height: normal;      
      margin-top: 5px;
  }
 </style>


The last part is the javascript function to show this login popup.

<script language="JavaScript" type="text/javascript">
  function login(showhide){
    if(showhide == "show"){
        document.getElementById('popupbox').style.visibility="visible";
    }
  }
</script>

Invoking the above function will display the login popup as shown below:

<a href="javascript:login('show');">login</a></p>

Wednesday, October 16, 2013

Site Map

All Posts by Category:

1. Patterns:



2. Spring Framework:

Spring AOP:
               Spring AOP Part-I
               Spring AOP Part-II
               Spring AOP Part-III


Spring MVC
              Spring MVC Part-I
              Spring MVC part-II

Spring Webflow:
             Spring Webflow Part-I
             Spring Webflow Part-II
             Spring Webflow Part-III
             Spring Webflow Part-IV



Spring Webservices:
             Building Webservices Using Spring

3. Architecture

Restful Services
          Restful Architecture
       

4. Hibernate 

Hibernate tutorial Series:
                    Hibernate tutorial Part I
                    Hibernate tutorial Part II


Spring Beans Autowiring

In this post I'm going to write about Autowiring feature in Spring.


Overview:

Generally, in Spring, you will define the beans and inject other beans into their properties by configuring them in xml. For eg, if we have a DAO, UserDAO and a service class UserService, which has a property reference for the DAO, then, the bean configuration would look like this:
<bean id="userDAO" class="com.myorg.service.dao.UserDAO">
</bean>

<bean id="userSvc" class="com.myorg.service.UserService">
      <propertyname="userDAO" ref="userDAO"/>
</bean>

Spring provides a feature called Autowiring, wherein the decision to wire the bean properties could be left to the Spring framework and this saves us a lot of configuration hassle.

There are four types of autowiring:
  1. byName
  2. byType
  3. constructor
  4. autodetect

1. Autowiring - byName:

In this type of wiring, Spring attempts to find the beans which has the same name/id as that of the bean property. In our above DAO/Service example, the UserService has a property userDAO. We can ignore the property config for userDAO by specifying autowiring by name as below:

<bean id="userSvc" class="com.myorg.service.UserService"  autowire="byName">
</bean>

2. Autowiring - byType:

In this type of wiring, Spring attempts to find the beans which have the same type as that of the bean property. This overcomes the disadvantage in 'byName', wherein you should always have the beans with same name/id as that of the property.
<bean id="userSvc" class="com.myorg.service.UserService"  autowire="byType">      
</bean>

Pitfalls of bytpe:

Wiring by type has a disadvantage. If Spring finds more than one matching bean, it will throw an exception. 

To overcome this, you can mark a bean as a primary candidate for autowiring. To get this working, you need to set the 'primary' attribute to true for the bean which you want to autowire and also set this attribute to 'false' for all other beans which have the same type (Since by default for all beans Spring treats this value as true).

Another option is, to set the 'autowire-candidate' to false for those beans which you do not want to be considered for autowiring.

3. Autowiring - constructor:

In this type of wiring, Spring attempts to find the beans which match the same type as that of the constructor arguments of a bean. This eliminates the need for constructor-arg configuration. However, note that when you are using constructor wiring, you cannot use constructor-args for some arguments and wiring for some.

For eg.,the UserDAO will need a datasource object to be injected in its constructor. To configure this, we can use constructor wiring as below:
<bean id="userDAO" class="com.myorg.service.dao.UserDAO" autowire="constructor">
</bean>

Spring will automatically detect the DataSource object defined in the bean configuration file and inject it into the UserDAOs constructor.

4. Autowiring - autodetect:

In this type of wiring, Spring attempts constructor wiring first. It it fails to find a matching bean, then it attempts wiring bytype.


Wiring Nulls:

One interesting feature provided by Spring is that we can also wire a null to a property. This feature is helpful, when the properties have some initial value and we need to nullify them.
<propertyname="country"><null/></property>


In general, you can mix and match different wiring types based on your need and this will help in reducing explicit configuration.

Spring Annotations for Autowiring:

Spring provides two configurations for supporting annotations:
1. context:annotation-config: This configuration when placed in your beans config file, will tell Spring to consider some of the annotations. However, you still need to declare your beans in the config file.

2. context:component-scan: This configuration when placed in your beans config file, will completely eliminate the need for declaring your beans in config file. This config provides autowiring and autodiscovery.

Following are some of the annotations provided by Spring to annotate the beans:
  1. @Component - Indicates that the class is a Spring component.
  2. @Controller  - Indicates that the class is a Spring MVC Controller
  3. @Repository - Indicates that the class is a data repository
  4. @Service  - Indicates that the class is a Service
Also, use the @Autowired configuration to make use of the autowiring ability provided by Spring. Note that @Autowiring always wires by type. If there is more than one bean with the same type, then you can use @Qualifier to remove the ambiguity as explained below:

Lets say there is an interface UserDataService which has two implementations.
public interface UserDataService {
       public User getUser(long userId);
}

@Service
public class UserDataServiceImpl implements UserDataService{
        public User getUser(long userId){ ....  }
}

@Service
public class PrivilegedUserDataServiceImpl implements UserDataService{
        public User getUser(long userId){ ....  }
}

@Controller
public  class UserController {   
        @Autowired
        private UserDataService userSvc;
        
        ...
        
}
Since there are two implementations Spring container will not know which one to bind and it will throw an exception "org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.myorg.service.UserDataService] ".

To overcome this, we can use the @Qualifier annotation to specify which bean we want to be injected. 
public interface UserDataService {
       public User getUser(long userId);
}

@Service
public class UserDataServiceImpl implements UserDataService{
        public User getUser(long userId){ ....  }
}

@Service(value="privileged")
public class PrivilegedUserDataServiceImpl implements UserDataService{
        public User getUser(long userId){ ....  }
}

@Controller
public  class UserController {   
        @Autowired
        @Qualifier("privileged")
        private UserDataService userSvc;
        
        ...
        
}
In the above example, we have provided a name "privileged" to the PrivilegedUserDataServiceImpl and then the same name is used in the @Qualifier annotation.

Sunday, October 6, 2013

Spring AOP - Part III

For part I, refer to: Spring AOP - Part I
For part II, refer to: Spring AOP - Part II

Continuing further on AOP examples, in this post, we will see how can we pass arguments to the Aspect classes.


Passing parameters to Aspect classes:

In this example, we will write a very basic auditing service, which will store audit details of who accessed a particular service.

The audit details could be stored in database. But that part is not shown here to keep the details simple.

Let us say we have an Account service, which offers CRUD on the account. The username parameter which is the first parameter for all the methods, indicates the user who will perform a CRUD on the account.
public interface AccountService {
    public long createAccount(String username, Account account);
    public void updateAccount(String username, Account account);
    public void deleteAccount(String username, Account account);
}

Define a corresponding AccountServiceImpl which will actually perform the CRUD. (not shown here).

Define an AuditService to define the audit operation and its implementation. Note that the audit service also has a "username" parameter which will passed from the target class (i.e, AccountService). Note that JoinPoint should always be first parameter, followed by the custom arguments.
public interface AuditService {
    public void performAudit(JoinPoint joinPoint,String username);
}
public class AuditServiceImpl implements AuditService{
        public void performAudit(JoinPoint joinPoint,String username) {
                 //log or store in database
        }
}

Spring config xml:

Note the String parameter passed to AccountService methods and the 'username' parameter name within args. This parameter name should match the actual name in AccountService.

<aop:aspect ref="auditService">  
         <aop:pointcut  id ="audit" expression="execution(* com.myorg.service.AccountService.*(String,..)) and args(username,..)"/>
         <aop:before  method="performAudit"  pointcut-ref="audit"/>
</aop:aspect>

AOP Introductions:

We can add new functionality to existing classes by using AOP Introductions. Internally, Spring will invoke these methods through the proxy implementation and this call will not go to the target class.

Lets say we create a new interface AccountAudit to define some special audits related to Account service.
public interface AccountAudit{
    public void performAudit();
}

We will define an implementation for this;
public class AccountAuditImpl implements AccountAudit{
    public void performAudit(){
        //audit
    }
}
We will need AccountService also to implement the same interface using AOP. We need to define this in the spring context xml as below:
<aop:aspect>
   <aop:declare-parents types-matching="com.org.AccountService+"
          implement-interface="com.org.AccountAudit"
          default-impl="com.org.AccountAuditImpl"/>
</aop:aspect>

Now, effectively this means that the AccountService could be type casted to AccountAudit as below and we can invoke the performAudit() method using AccountService reference.

((AccountAudit) accServ).performAudit();


Applications of AOP:


In general, AOP can be best used in logging, security, transaction, auditing.

However, a word of caution while using AOP.  Though AOP is very powerful, avoid using AOP for implementing business logic, as it will result in a maintenance nightmare since it will be hard to figure out that some part of the business logic is in the aspect classes.




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