Thursday, July 18, 2013

Test Your Domain Layer With H2 Embeded Database

In most enterprise level applications testing the persistence unit or the dao layer has a significant advantage since it depends on all upon layers. Here I would explain how you can use spring framework support to unit test your persistence unit.

First have a look on a simple domain class. 
@Entity
@Table(name = "customer", schema = "", catalog = "")
public class Customer {
    private long id;     private String firstName;     private String lastName;     private String address;     @Id     @Column(name = "id", nullable = false, insertable = true, updatable = true)     @GeneratedValue(strategy = GenerationType.AUTO)     public long getId() {         return id;       // remaining getters and setters with mapping annotations
}

Next we need to have a DAO class for persisting operations. (here I have used generic DAO pattern)

 

public interface GenericDao{    public E save(E e);
    public E update(E e);
    public void delete(long id);
}
public abstract class AbstractGenericDao implements GenericDao {

    @PersistenceContext
    protected EntityManager entityManager;

    private Class type;

    @SuppressWarnings("unchecked")
    public AbstractGenericDao() {
        this.type = (Class) ((ParameterizedType) getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
    }
    @Override
    public E save(E e) {
        entityManager.persist(e);
        return e;
    }

    @Override
    public E update(E e){
        entityManager.merge(e);
        return e;
    }

    @Override
    public void delete(long id){
        entityManager.remove(entityManager.getReference(type.getClass(), id));
    }


Next we can extend this base class for DAO implementations such that they will inherit the basic CRUD operations.
public interface CustomerDao extends GenericDao {

        // customer specific method declarations goes here 

}

@Repository("customerDao")

public class CustomerDaoImpl extends AbstractGenericDao implements CustomerDao {
     // customer specific method implementation goes here
}
So now we are done with the DAO implementation. Its time unit test this implementation.

For that I am using a spring test application context with in memory h2 data source as follows.

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    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">


   
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       
       
       
       
   

   
       
       
       
           
               
               
               
           

       

   

   
   
       
   




Here you need to enable package scanning for requires java packaged for injecting the dao instance you need to test. Only difference with your real application context file is the inmemoey data h2 data base.

Then you need to write a junit class with loading the above test application context.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:testContext.xml"})
@TransactionConfiguration
@Transactional
public class CustomerDaoImplTest {
    @Autowired
    private CustomerDao customerDao;

    @Test>
    public void test_save_customer(){
        Customer cm = CommonObjects.getCustomerDomainObj();         Customer afterSave = customerDao.save(cm);         Assert.assertNotNull(afterSave);         Assert.assertNotEquals(0, afterSave.getId());     }       // Remaining assertions goes here
}

Friday, January 25, 2013

Displaytags Integration With Spring MVC3

When it comes to displaying database records as a list view(table) in jsp, we need to provide sorting and pagination functionalists. Basically what we do is use ajax  with pure java script  or using JQuery and call controllers to get the job done. This becomes complicated when you need to provide sorting functionality  for multiple columns. I recently found a tag-library "displaytags" which can take care of pagination and sorting stuff in Client side.
Following is the view of functionality we want to come up with using displaytags. 

   
First you need to include tag declaration in your jsp.
 
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
And the following will take care of generating table for list view.
 
   
    
    
     
    
The name of the display table attribute(which is name==persons) is binded with a list of Persons and it is assigned in MVC controller class.  
final ModelAndView persons = new ModelAndView(VIEW_ALL_PERSONS);
  persons .addObject("persons", getPersonList(request));
                request.setAttribute("personListSize", personService.getRowCount());
  request.setAttribute("pageSize", pageSize);
And the property attribute of display column which is (property="designationName") is binded with the property of the model in MVC pattern. And also you need to set other request parameters which are used to construct the table by display tag library.
public class PersonDetails {
 
 private String designationName;
 
 public String getDesignationName() {
  return designationName;
 }

 public void setDesignationName(String designationName) {
  this.designationName = designationName;
 }
}
Lets say you want to add an attribute which is not in you model class, then display tags allows you to use a decorator and use that attribute in display columns.I have used personLink and editLink property with a decorator and those properties are not included in my model class(PersonDetails). In the display table you can see a property called decorator and its value.(ecorator="se.nextodo.web.util.LinkDecorator"). Properties which are not included in the model class are retrieved from the decorator class. Advantage of using this is you can add a image links or icons in to the table.
import org.displaytag.decorator.TableDecorator;
import com.mycompany.model.PersonDetails;

public class LinkDecorator extends TableDecorator {

 public String getPersonLink() {
  final PersonDetails personDetails = (PersonDetails) getCurrentRowObject();
  final String link = ""+  "";
  return link;
 }

 public String getEditLink() {
  final PersonDetails personDetails = (PersonDetails) getCurrentRowObject();
  final String link = "" +"";
  return link;
 }
}
You can define button icon in you style sheet (in this case edit-btn) and it will render the images as expected.

       Now we are almost done with the creating table in client side and its time to consider how to implement sorting and pagination functionality in server side. From the server side we need to know the field that the client wanted to sort. It is the sortName property in the table column(sortName="firstName). display tag library set request parameter for this, so that we can retrieve it from the server side as follows.
final String attribute = request.getParameter(new ParamEncoder(tableId)   .encodeParameterName(TableTagParameters.PARAMETER_SORT));
In the same way you can retrieve the sorting order (ascending or descending).
 
final String orderKey = request.getParameter(new ParamEncoder(tableId)
    .encodeParameterName(TableTagParameters.PARAMETER_ORDER));
The remaining fact you want to get from the client is the current page position on the jsp.
  final String page = request.getParameter(new ParamEncoder(tableId)
    .encodeParameterName(TableTagParameters.PARAMETER_PAGE));
So its time to implement our dao functionality.
 @SuppressWarnings("unchecked")
 @Override
 public List getPersons(String orderedBy,
   String order, int startPosition, int maxResult) {

  final String queryString = "select p from Person p ORDER BY "
    + orderedBy + " " + order;

  final Query query = entityManager.createQuery(queryString);
  query.setFirstResult(startPosition);
  query.setMaxResults(maxResult);
  return query.getResultList();
 }
Dao call from the controller looks like bellow.
private Collection getPersonList(
   HttpServletRequest request) {

  final String tableId = "personList"; 
  final int pageSize = 10; 

  return personService.getModels( attribute,orderKey,(page - 1) * pageSize),pageSize);
 }
Reference : diplay tag website

Thursday, November 22, 2012

GIT Basics

Version Control Systems

As software developers most of the time we are experienced collaborative development where many guys are working on a single code base. To make this collaborative work efficient the concept called Version Control System was introduced. VSC can be divided in to two main categories.
  • Centralized Version Control Systems (Subversion)
  • Distributed Version Controller Systems (Git, Mercurial)
Centralized Version Control Systems


 Above figure[0] describes how the Centralized Version Control System works. Central server consists of all the version data  and logs. Client computers can checkout a specific version from the central server and the copy only contains the file itself. So the Central server is the only place where you keep version controller files. What happens when the central server is being stopped for maintenance purpose or similar issue ?  You cannot do a single version control operation including commits, taking diffs with server branch , etc. Simply you cannot continue you work collaboratively in offline mode.Even more worst ,think of a scenario where you do not take backups frequently and the server crashed. So you lost entire version history.


To address those drawbacks software industry came up with the concept of Distributed Version Control System.
Distributed Version Controller Systems 


In distributed Version Controller System it has a server computer and all the clients can clone the entire repository into local machine. So that each client repository is a candidate for backups. And also we can do operations on the repository locally and later or synchronize the work with the server repository.

Working with Git
First you need to download git client and install it on your local machine.[2]. It provides you command line client as well as a GUI client. For learning purpose I will use command line client for this post. As for the code hosting server I am going to use git hub and will create a repository called "HelloWorld" and following is the url that repository.
    https://github.com/esudharaka/HelloWorld.git

-Clone a remote repository




- Create HelloWorls.java using internal Vi editor



 - Check the status or current branch (in this case master)
 You can see HelloWorld.java file is un-tracked and we need to add it.
- Add HelloWorld.java using git add command and check the status

 










Now you can see git  says that you have a new file and  suggest the commit command. Before committing the changes locally lets take a look how the git diff command works.

 













In this stage we have not commit HelloWorld.java file yet. But we have added it to the stage state where we can commit the changes in next step. So when we execute git diff command it will show no difference. Because it does consider only the committed files. But if we use --cached argument with the diff command it will show the changes in the staged file. So we can see the content of HelloWorld.java class as the difference.

-Commit HelloWorld.java







After the commit step it mean you have committed the file in to your local repository. Not to the one stay in Git hub.(We will do it latter) 

- Create a branch 

Following are the steps of creating a branch called "feature" and switch to that branch.















Then I will add a new file Feature.java and modify HelloWorld.java and commit them into feature branch. Now Branch looks like this.


Suppose that we finished implementing new feature and we need to merge it with master.
- Merging a branch 


















First we need to switch to master. Then by using git merge command you can merge master with feature branch. In this case luckily we don't have any conflicts. 

For the demonstration purpose I made conflicts in master and feature branch. Now when I run git merge command it says that you have conflicts.





Then you need to use git mergtools command and it will shows available merge tools available in your local machine.


For this purpose i am going to use tortoisemerge tool. Onece you press enter button git will open merge tool for you as bellow.




 Once you resolve conflict you can close this merge tool. Then we will check the status of master branch.









Then you need to do your final commit in to you master branch.







So far we played with our local repository. And now its time to push you changes into remote repository on the github.








There are some more advanced topics like rebase, interactive rebase, making pull requests. References


[0] - http://git-scm.com/book/en/Getting-Started-About-Version-Control
[2] - http://code.google.com/p/msysgit/

Saturday, August 18, 2012

Spring Web Services with Jaxb

In this post I am going to explain how to implement a web service by using spring-ws. For the demonstration purpose I am going to narrow down this sample project as follows.

Functionality of web service : Authenticate a user(I am not going to use any encryption method or a security mechanism since this post is about spring ws :-))

Development/Deployment environment :
  • java 1.6
  • Spring-ws-core with jaxb 
  • Intelij Idea
  • Apache tomcat 
  • SoapUI 4.5.1
 First we need to start with a schema definition which our service is going to support. So for the simplicity I used following definition which is easy to understand.
 



    

    

    
        
            
            
        
    

    
        
            
            
        
    

Above schema definition consist of a simple login request and the corresponding response.Simple it can parse following sample messages.

Request Message
 

   
   
      
         esu
         password
      
   

Response Message
 

   
   
      
         SUCCESS
         esu
      
   

Then you need to create a web project by using your IDE or a build tool like maven. A web service acts like a web app and the the significant difference is that it can identify incoming xml requests and response them with corresponding xml responses as mentioned in above. If you are familiar with Spring mvc you know that we can configure a Dispatcher Servlet in web.xml which can identify HTTP get and post requests from the client browser.In the similar manner you can configure a MessageDispatcherServlet which can identify web server requests.
    
        customer-ws
        org.springframework.ws.transport.http.MessageDispatcherServlet
    
    
        customer-ws
        /*
     
Then you should have customer-ws-servlet.xml where all the spring web service configurations and jaxb marshaling configurations are located. You can find the Servlet here . The important thing to be noticed is the WSDL configuration and schema configuration.
 
    
        
        
        
    

    
        
    
customer service bean creates a wsdl for you according to the schema bean which is configured to the loginschema.xsd. Once you deploy the web service in to the web container you can access the generated wsdl by http://localhost:8080/customerService/customerService.wsdl.

Then its time to implement end point class which the final destination for incoming soap massages. Following is the implementation of the endpoint.
 
@Endpoint
public class CustomerServiceEndPoint {


    @Autowired
    private LoginService loginService;


    @PayloadRoot(localPart = "LoginRequest", namespace = "http://mycompany.com/customer-ws/schemas")
    @ResponsePayload
    public JAXBElement login(@RequestPayload JAXBElement requestElement) throws IOException {
        ObjectFactory objectFactory = new ObjectFactory();
        LoginResponseDetails details = new LoginResponseDetails();

        details.setUsername(requestElement.getValue().getUserName());
        if (loginService.login(requestElement.getValue().getPassword(), requestElement.getValue().getPassword())) {
            details.setStatus("SUCCESS");

            return objectFactory.createLoginResponse(details);
        }
        details.setStatus("FAIL");
        return objectFactory.createLoginResponse(details);

    }
}
You can see the login method is accepting jaxb element called LoginDetails and it passes that details in to service method and authenticate the user and return the response jaxb element. you might be wondering how this happens. It is because we have configure marshalling and unmarshalling in the servlet xml.And also to enable the jaxb class generation I have used jaxb2-maven-plugin in my pom file which you can find the source code on the Google code repository.

Source Code Link : Code
What you have to do is simply check out the source code and then run mvn package command. Then you can see the generated war file. Then deploy it in to apache tomcat. Now you are done.

Following is the screen shot  taken from the soapui to verify that the web service is working or not.


From my next post i hope to show how to write client app to use this web service.

Saturday, June 23, 2012

Producer Consumer Problem - Java solution

Shared Stack and Signaling variables
final Stack stack = new Stack();
final int maxLimit = 5;
final Object obj1 = new Object();
final Object obj2 = new Object();
Producer code
Thread producer = new Thread() {

 @Override
 public void run() {

 while (true) {
  synchronized (obj1) {
   if (stack.size() == maxLimit) {
    try {
     obj1.wait();
    }

    catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
  synchronized (obj2) {
   stack.push("producing items....");
   obj2.notify();
  }
 }

 }
};

Consumer code
Thread consumer = new Thread() {

 @Override
 public void run() {

  while (true) {
   synchronized (obj2) {
    if (stack.size() == 0) {
     try {
      obj2.wait();
     }
     catch (InterruptedException e) {
      e.printStackTrace();
     }
    }
   }
   
   synchronized (obj1) {
    stack.pop();
    obj1.notify();
   }
  }
 }
};
Then start producer thread and consumer thread as follow.
producer.start();
consumer.start();
If this code is a buggy one please feel free to correct me.

Monday, June 18, 2012

Executing a Shell Script From a java Class

In this post I am going to explain the way of executing a shell script through a java class. But this kind of implementations are discourage by java programming language since this will remove the great power of java which is portability. (compile one one machine and can run on anywhere we have JRE). For this purpose we can use java ProcessBuilder and execute shell script file with the help of it.

private static void executeProcess(Operation command, String database) throws IOException,
            InterruptedException {

        final File executorDirectory = new File("src/main/resources/");

      
private final static String shellScript = "./sample.sh";
     
           ProcessBuilder processBuilder = new ProcessBuilder(shellScript, command.getOperation(), "argument-one");
      

        processBuilder.directory(executorDirectory);

        Process process = processBuilder.start();

        try {
            int shellExitStatus = process.waitFor();
            if (shellExitStatus != 0) {
                logger.info("Successfully executed the shell script");
            }
        } catch (InterruptedException ex) {
            logger.error("Shell Script preocess is interrupted");
        }

    }

In this case my shell script is reside in resources folder. You can see I have set the process builder directory to that, so the commands are executing from that directory.And also we can pass any number of arguments to shell script via process builder.In this case we have pass a single parameter to the shell script and from the shell script it can be accessed by $1. Following is the sample shell script we have invoked through the java class.
   echo "Sample script is executing"
   echo "parameter is :" $1 
Same way you can invoke a windows batch file as well.

Friday, June 15, 2012

Unmarshalling XML files with jaxb

In this post I am going to explain how to create a schema definition from a sample xml file and use that schema definition file to marshalling and un-marshalling by using jaxb2.

Following is the sample xml formal I want to handle. (Suppose we have a web service and it can accept this kind of requests)

    
        Eshan
        test@gmail.com
    
    
        
            SE-12
            web camera
        
        
            SE-75
            mobile phone
        
    

You can create the schema definition file (xsd) of a given  sample by using modern IDE's. For this purpose I used Intelij xml to xsd converter which makes life easier. But we need to edit the generated xsd file for our simplicity. So following is the schema definition for the above xml file.

    

    
        

            
                
                    
                
            

            
                
                    
                    
                
            

        
    

    
        
            
            
        
    

    
        
            
        
    

    
        
            
            
        
    


Now we have finished the work with schema related stuff. Then we need to generate generate java classes from this xsd file. So its time to deal with jaxb2. In this case I had a problem which is the generated java classes are not in a proper naming convention. (All tha classes has "Type" postfix). To fix that we can use a bindings xml which can be pass as a parameter to jaxb.

    
        
            
        

        
            
        
        
            
        
        
            
        
        
            
        
        

So now we are almost done. Its time to generate java classes from these two xml files (xsd file and binding xml). For this purpose instead of calling jaxb xjc directly, I used maven jaxb plugin which is more flexible. following is the jaxb plugin confutation which comes in your pom file.
 
        
            
                generated-sources/xjc/com/demo/xsd
            
        
        
            
                org.jvnet.jaxb2.maven2
                maven-jaxb2-plugin
                
                    
                        
                            generate
                        
                    
                
                
                    src/main/resources
                    true
                    true
                    false
                    true
                    
                        bindings.xml
                    
                
            
        
    
Once you invoke the maven target it will create the java classes of the complex types in our schema definition file. SO now its time to write a client program which uses those java classes to unmarshall a sample xml file.
package com.demo.xsd;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import java.io.File;

public class Unmarshalling {
    public static void main(String[] args) {

        try {                 
            //sample xml file to be unmarshall
            File file = new File("path/to/sample.xml");
            javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext
                    .newInstance(Order.class);
            javax.xml.bind.Unmarshaller u = jc.createUnmarshaller();
            JAXBElement orderJAXBElement = u.unmarshal(new StreamSource(file),
            Order.class);
            Order order1 = orderJAXBElement.getValue();
            String itemName =order1.getItems().item.get(0).getName();
            System.out.println("Item name " + itemName );

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

So we are done. One important thing to mention is with the jaxb 2 xml validation part is being lost(for ans example lets say we need to restrict a particular element to have only specific string values, then the unmarshalling process should throw and parsing exception)

 But in case of you need to validate xml you can do it by setting the schema file to the unmarshaller object as follows.
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);  

     jaxbUnmarshaller.setSchema(sf.newSchema(new File("/path/sample.xsd")));