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")));

Saturday, June 2, 2012

Print Diamond Problem with TDD approach

Problem given at the event :
Given a letter print a diamond starting with 'A' with the supplied letter at the widest point.
Development Approach we need to practice : "Test Driven Development"

During the coderetreat event conducted by  Johannes Brodwall  we practiced the same problem over and over with different devs with different approaches. In this post what I am trying to summarize the things I got through out this valuable event. 
The way I looked at the the problem is more biased in to a geometrical view. My observation is that we can put our elements in a 2D Cartesian space as follows. Following is the example for Letter C.
red dot - Letter A
green dot - Letter B
blue dot - Letter C

So if we can find the equation of the line XY then we can find the points by substituting Y=0,1,2 (We can write a simple logic to get the Y's range)

Equation for line XY :  Y = -X +2
by substituting y values we can get following points.
(0,2),( 1,1) and (2,0)

Similarly you can obtain the equation for line LM.
Equation for line LM :  Y = -X -2
by substituting y values we can get following points.(y=0,-1,-2)
(0,-2), (-1,-1) and (-2,0)

Equation for line XM :  Y = X -2
by substituting y values we can get following points.(y=0,-1,-2)
(0,-2),(1,-1) and (2,0)

Equation for line LY :  Y = X +2
by substituting y values we can get following points.(y=0,-1,-2)
(0,-2),(1,-1) and (2,0) 

If you are familiar with the absolute value function you can write above functions with a single function as follows.

| X | + | Y | = 2

so our task has reduced to find a simple liner equation for a given charactor.
So the general form of the equation is |X| + |Y| = c
When it comes to TDD approach first thing we need to do is write a simple test against our business logic which gives an assertion failure. Test should be smaller enough to fail.  
Following are the test cases I wanted to cover :
1).  Find the interceptor of the equation for a given input character :
@Test
 public void test_the_intercept_of_the_line() {
  Diamond diamond = new Diamond();
  Assert.assertEquals(0, diamond.getInterceptor('A'));
  Assert.assertEquals(1, diamond.getInterceptor('B'));
  Assert.assertEquals(2, diamond.getInterceptor('C'));
 } 
Source for this test case is simple as follows.
public class Diamond {

 public int getInterceptor(char c) {  
  return c-65;
 }
}
In this case what you need to make sure is just write enough code which is capable of passing you test case.

2) As for my second test scenario I used Input character 'B' and test the points list where I need to print characters. 
@Test
 public void test_output_diamond_for_input_charactor_B() {
  Diamond diamond = new Diamond();
  Set pointSet = diamond.getPointSet('B');
  Assert.assertEquals(true, pointSet.contains(new Point(0, 1)));
  Assert.assertEquals(true, pointSet.contains(new Point(0, -1)));
  Assert.assertEquals(true, pointSet.contains(new Point(1, 0)));
  Assert.assertEquals(true, pointSet.contains(new Point(-1, 0)));
  Assert.assertEquals(false, pointSet.contains(new Point(-1, -1)));
 }
In order to pass the test case I used following algorithm which i was planing to apply in above explanation.(Implementation of absolute value function with +/- notations)
public class Diamond {

 public int getInterceptor(char c) {
  return c - 65;
 }

 public Set getPointSet(char c) {
  Set pointsSet = new HashSet();
  int interceptor = getInterceptor(c);

  for (int yIndex = interceptor; yIndex >= 0; yIndex--) {
   int xIndex = interceptor - yIndex;
   pointsSet.add(new Point(xIndex, yIndex));
   pointsSet.add(new Point(xIndex, -yIndex));
   pointsSet.add(new Point(-xIndex, yIndex));
   pointsSet.add(new Point(-xIndex, -yIndex));
  }
  return pointsSet;
 }
}
Since I wanted to apply some OOP concepts I created Point class and implement the constructor which we can pass X,Y coordinates. And also I implement the hash code , toString and equals methods in the Point class.(This can be generated by using eclipse IDE). In addition to that I am going to store relevant character with that point object as follows.
 
public Point(int i, int j) {
  this.setX(i);
  this.setY(j);
  this.setCharacter((char)(Math.abs(j)+65));
 }

3) During the workshop I heard that some guys  were taking about write test cases to figure out whether the points are located with in the boundary. But in this approach we don't need such kind of a test since we are substituting the correct range of Y values. That range is indirectly tested by test_interceptor_of_the_line method. I found that it is not compulsory to write a test for figure out the boundary of the grid.
At this point I know my algorithm is working properly. And then I need to print the character pattern in to the console output. In order to do so I just had to write following simple logic.

public void printDiamond(char c) {
  int interceptor = getInterceptor(c);
  int gridArea = 2 * interceptor + 1;
  // Create an array with all 'X' values
  char[][] diamond = new char[gridArea][gridArea];
  for (char[] ds : diamond) {
   for (int i = 0; i < ds.length; i++) {
    ds[i] = 'X';
   }
  }
  Set pointSet = getPointSet(c);

  for (Point point : pointSet) {
   diamond[point.getX() + interceptor][point.getY() + interceptor] = point
     .getCharacter();
  }

  for (int row = 0; row < gridArea; row++) {
   for (int column = 0; column < gridArea; column++) {
    System.out.print(String.valueOf(diamond[row][column]));
   }
   System.out.println();
  }

 }
It will gives the expected diamond for a given input character.

Since my tests are passing I thought of having some refactoring to Dimond class. for and example I do not need to expose getInterceptor method to public. So i can make it private.

Another self finding of this workshop is that we should think the test case as a opposition party  and always write the test cases which will give the maximum pain for the source code end. (Class under Test). At the same time you need to make sure to write a simple test which gives enough potential to fail.

So its about how to treat our code. Overall it was a wonderful event and  I could deal with the people who has different kind of mind sets. At the end of the day what I had is a green color sticky note which says that you should practice some code kata with TDD until you will get the right skill. Kudos for Johannes.

Note : In the case where you need to have a closer look in to the code you can get it from here.

Saturday, May 19, 2012

Spring MVC + Spring Hibernate for basic CRUD operations

Most of java developers are using Spring framework for flexible designs.Specially for web based projects where we apply MVC design pattern. So in this post I am going to explain how to use spring framework to achieve that requirement.

I will explain it with the web.xml file which is easier to understand.

   
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        1
      

    
        dispatcher
        *.do
    

    
        org.springframework.web.context.ContextLoaderListener
    
    
        contextConfigLocation
        classpath:/spring/applicationContext.xml
    
Here you can see I it triggers a dispatcher servlet when the request consist of .do extension. Following is the dispatcher file.
  
 
    
    

    
    
 
It defines the package where the spring should search for controllers. And also you can see it consists of the view resolver which uses by the controllers to resolve the views from the returned ModelAndViews.

And if you have a closer look in to the web.xml file you can see it has load the context configuration which acts as an ioc container of spring framework.

 
    
    
    

    
          

    
    

    
        
        
            
                ${hibernate.dialect}
                ${hibernate.show_sql}
            
        
        
    


    
    

    
DataSource properties are loaded from config.properties files in the resources directory. Then what you have to do is implement domain and its dao class. Here I have mentioned only the dao class. You can find domain class in the svn project.

 
import java.util.List;

import com.exilesoft.contactmanager.domain.Contact;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class ContactsDAO
{
    @Autowired
    private SessionFactory sessionFactory;

    public Contact getById(int id)
    {
        return (Contact) sessionFactory.getCurrentSession().get(Contact.class, id);
    }

    @SuppressWarnings("unchecked")
    public List searchContacts(String name)
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
        criteria.add(Restrictions.ilike("name", name+"%"));
        return criteria.list();
    }

    @SuppressWarnings("unchecked")
    public List getAllContacts()
    {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contact.class);
        return criteria.list();
    }

    public int save(Contact contact)
    {
        return (Integer) sessionFactory.getCurrentSession().save(contact);
    }

    public void update(Contact contact)
    {
        sessionFactory.getCurrentSession().merge(contact);
    }

    public void delete(int id)
    {
        Contact c = getById(id);
        sessionFactory.getCurrentSession().delete(c);
    }
}
Then what you have to do is call those methods from the controller class. I will left the controller code and the jsp codes since it is easy to understand.
You can find the code in following repository.

http://es-code-snippets.googlecode.com/svn/trunk/contactmanager/

Monday, April 30, 2012

Spring Mobile and Sitemesh Integration

In modern technology era mobile based technology plays a major role. Trend has increased to use mobile phones for internet access.So there is new software requirement to add mobile support for existing web sites.

In this post I am going to explain an easy way of doing this using spring mobile and sitemesh. Requirement : Identify the device which the request comes from and apply the decorators according to the device.(css files and other specific images) The easiest way to do is use a filter in web.xml and detect the device. So in this post I use a filter in web.xml as follows.
  
 
      sitemesh
      com.mycompany.sitemesh.SpringMobileSiteMeshFilter
     
  
       sitemesh
       *.do
  

Once the url pattern maps it will trigger above site mesh filter. SpringMobileSitemeshFilter is an sub class of ConfigurableSitemeshfilter (API) Which comes with sitemesh pacage. In this specific implementation I have override applyCustomConfiguration method where we can apply specific decorators programatically.


package com.mycompany.sitemesh;

import org.sitemesh.builder.SiteMeshFilterBuilder;
import org.sitemesh.config.ConfigurableSiteMeshFilter;

public class SpringMobileSiteMeshFilter extends ConfigurableSiteMeshFilter {

    @Override
    protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
      System.out.println("In SpringMobileSiteMeshFilter");
      builder.setCustomDecoratorSelector(
        new SpringMobileDecoratorSelector(builder.getDecoratorSelector()));
    }
}

You can see that I have used SpringMobileDecoratorSelector which uses spring mobile functionality to identify the device and apply the decorator.


import java.io.IOException;

import org.sitemesh.DecoratorSelector;
import org.sitemesh.content.Content;
import org.sitemesh.webapp.WebAppContext;
import org.springframework.mobile.device.site.SitePreference;

public class SpringMobileDecoratorSelector implements
        DecoratorSelector {
    private final DecoratorSelector fallbackSelector;

    public SpringMobileDecoratorSelector(
            DecoratorSelector fallbackSelector) {
        this.fallbackSelector = fallbackSelector;
    }
    
    public String[] selectDecoratorPaths(Content content, WebAppContext context) {

        final SitePreference sitePreference = (SitePreference) context.getRequest().getAttribute("currentSitePreference");

        System.out.println("In SpringMobileDecoratorSelector");
        
        final String decorator;

        if (sitePreference.isMobile()) {
         System.out.println("Mobile");
            decorator = "/WEB-INF/decorators/mobile.jsp";
        } else {
         decorator = "/WEB-INF/decorators/default.jsp";
         System.out.println("PC");
        }

        if (decorator != null) {
            return decorator.split(",");
        } else {
            // Otherwise, fallback to the standard configuration.
            try {
                return fallbackSelector.selectDecoratorPaths(content, context);
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }   
    
}
You might be wonder how this works. And where this request parameter called currentSitePreference is being set. Actually it is not a magic. I use spring mvc interceptor to set that request parameter.
 We can configure it in our dispatcher servlet in following manner.


  
 
       
             
  
Above two beans a responsible of detecting the device and set that parameter. And then we can simply apply the jsp files by checking the isMobile attribute. Final outcome is when the request comes form a mobile device it applies mobile jsp and do the decorating part. If it comes form a normal pc then it applies default. jsp and and do the pc related decorating.

Friday, February 10, 2012

Sending emails using a python script

 I have scene many programmers prefer to use python scripts to send those emails.

So here i am going to show a sample working script.

Pre requirements  : python2.6

  
import smtplib



fromaddr = 'sender@gmail.com'

toaddrs  = 'recipient@gmail.com'

msg = ' i am sending this trough my sample programe. this is really cool.. :-) send me a reply when u recieve this mail.'



# Credentials (if needed)  

username = 'username'

password = 'password'



# The actual mail send

server = smtplib.SMTP('smtp.gmail.com:587')

server.starttls()

server.login(username,password)

server.sendmail(fromaddr, toaddrs, msg)

server.quit()
Save this file as example.py
How to run the script :      
    Go to the location of example.py and run following command.    
          python example.py
Then check you mail. :-)

Monday, January 30, 2012

Creating Objects Using Factory Methods

Consider static factory methods instead of constructors

Normally when we use constructor methods(new key word) to create instances of a class. And in post i am going to explain another way of create object which is static factory methods.For an example we can take one of factory method implemented in java.lang.Boolean.
 
public static Boolean valueOf(boolean b){
 return b? Boolean.TRUE : Boolean.FALSE;
}

Providing factory method to create objects rather than using constructors has both advantaged and disadvantages.
Advantages of having Factory methods to create instances 

  • Factory methods have a valid name 
Imaging you have a Shape class and it has a constructor which accept one int parameter which is the number of edges.If parameter is 3 it returns a triangle.So the client code which use this constructor is not too clear since constructor method does not make a sense about the object which is going to retrieve. But if we have a static factory method called getTriangle() which returns a triangle shape instance, it would be more readable than having a constructor method. 

  • Do not need to create new object in each time 
This is the implementation of singleton pattern. This technique is very useful is cases of cost of creating an instance is too high and where we can share a single object. One of the advantage of using this concept is we don't need equals( ) method for comparisons and we can simple check the equality by == operator.

  • Factory methods can returns any sub type of their return type 
One application of this flexibility is that an API can return object without making their classes public.For an example look at the java.util.Collections. In this case interfaces provide return types for static factory methods. And those static factory methods are put in a non instantiable class. 

  • Reduce the overhead of creating parameterized type instances 



Instead of this kind of constructor methods we can have a factory method which can be reusable with less effort. 



Disadvantages of having Factory methods to create instances 
  • It is hard to distinguish factory static method form other available static methods
  • Non public classes cannot be sub classed(If we have factory method to create instance then we can make that class a private) 

Thursday, January 19, 2012

Continuous Integration( Part Four) : Deploy Web Application to a Remote machine Using MSDEPLOY

As I mentioned in my previous blog bost  there is a better option for deploy a web application in to a IIS location through MSDeploy command line tool rather than using XCOPY. In this post I am going to brief the issues I encounter during web deployment phase and the steps I followed to overcome them.

Issue 1:
When I package my web application from my local machine it creates a MVC-Client.deploy.cmd file which is referring MSDepoly path as :
                 MSDeployPath="C:\Program Files\IIS\Microsoft Web Deploy V2\"
But In the build server machine (Locate in same network) it creates a MVC-Client.deploy.cmd file which has MSDepoly path as
                MSDeployPath="C:\Program Files (x86)\IIS\Microsoft Web Deploy\"

And I have both versions of MS Web Deploy installed on both machines. But there was an issue when I try to deploy web application to the the web server from the build server machine.
                MVC-Client.deploy.cmd /y /M:es-websrv01/MSDeployAgentService
Reason is it refers version 1 instead of version 2. And I can garentee you that I have same MSBuild versions in both my local machine and build server machine. I dig a bit about this issue and I found that we need to install VS2010 service pack one to generate the working MVC-Client.deploy.cmd file. In my development machine i had it and on the build server machine it has not installed. Installing VS2010 service pack 1 fixed this issue.

Issue 2:
Permission Issue
In my case Jenikings is running as a windows service which initiates by a local user(Not In the Active Domain) in the build server machine(Windows NT ). But in order to do the remote deployment that user should have admin privileges in the target remote machine(es-websrv0). So what I did is just add a user in to the AD with the admin privileges for es-websrv0 and did the deployment. 

Another permission issue I encounter is we cant do the remote deployment from the Programs files folder in C:/ since it has special permission level.  

Issue 3:
Required Softwares which should be installed in target web server machine.
As I notice there are two ways of do the remote deployment as follows make sure that you have installed corresponding soft-wares on the destination machine.
M: Destination server name or Service URL
    If this flag is not specified, the package is installed on the computer where the command is run. The Service URL can be in the following format:
        https://:8172/MSDeploy.axd
    This format requires that IIS 7 be installed on the destination server and that IIS 7 Web Management Service(WMSvc) and Web Deployment Handler be set up.


    The service URL can also be in the following format:
        http:///MSDeployAgentService
    This format requires administrative rights on the destination server, and it requires that Web Deploy Remote Service (MsDepSvc) be installed on the destination server. IIS 7 does not have to be installed on the destination server.

Sunday, January 15, 2012

Continuous Integration( Part three) Things That can be done from the Build Server Side


Note : If you are interested in installing jenking build server for .Net applications I found an interesting post which has a good step by step explanation. 
Before going through this blog post I would recommend you to go through following blog post which gives you knowledge which is useful to understand the things mention in this post.
As I mentioned in above CI-Part Two we can create a IIS deploy-able packages with different configurations on the built server machine.

 Requirement : 
 "Automate the deployment process on IIS location for every successful  build.Moreover I need to automate multiple deployment with different configurations."

If I breakdown above requirement further, it is obvious that my first task is to create multiple packages with different configurations if and only if the build process is successful. In this case I may need some support of build server side to trigger me after a successful build. Once build server trigger me I have to think of creating packages with different configs. First question arise is as follows.

Me : Hey Jenkings, Do you have a plugin which you can trigger me after a successful build ? 
Jenking : Yes. I do have many which you can get your job done.
Me : Thank god. Then I will be surviving..... :) 

There is a good plugin to get this job done which is called Jenkins post built task plugin. By using above file I can execute any command line operation by checking the status of the build server build report. So what can I do is searching through the build report and find the build status. And then if it successful then execute a batch file or simple command line operation for the deployment. By ticking on the post built task you can get the following post build task. (In this example it runs the script if the build is failed)












So now we have a way to trigger a batch command if the build is successful.Then the next task is to find a way to do deployment automation.First I need to think about a way of creating packages with different configurations.I found following possible approaches of doing the packaging.
  • Assign Multiple jobs to jenkins server for different configurations :
In project configuration section you may find the build task. Here you can explicitly tell jenkins build server the configuration you want to build and package.(Simple it accepts MSBuild external parameters)


In this comamnd line argument section you can pass /t:package /p:buildsever and then it package web project which has the build server configuration. Similarly what you can do is assign new job to the jenkings server and in that job in the build section pass other configuration which you want to create the package.(eg: Live Server Configurations)
  • Build the package with multiple configuration by using a single Jenkings job:
Only change is in the command line argument section you can add two configuration which separated as follows.
              /t:package /p:buildsever;liveServer
But in order to get this job done you need some changes in the sln/csproj file which you are referring in the build server. This post will helps you to get this project file configuration done. 

     
At this point we are almost done with the packaging process.Next remaining thing to be done is deployment process of multiple package.Here I would suggest following approaches to to do it.

  • Use XCOPY command to copy the newly build package in to IIS location :
In this approach what you need to do is execute XCOPY command in Script section in post build plugin section.
 cd to project location in build server          
 XCOPY Views \\ES-WEBSRV01\Library\Views /e /y /i
 XCOPY packages.config \\ES-WEBSRV01\Library /y  


Similarly you need to copy all required folders in to IIS location.
\\ES-WEBSRV01\Library is the place where we deploy our IIS application.If your IIS location is on a another machine rather than the build server machine you need to share the location with the build server machine as above.But here we have a tricky problem. As i mentioned in my previous blog post there is a issue with the web.config file.So what we need to do is go to the project\obj\release\TransformWebConfig\transformed in the build server and get the transformed web.config file and then XCOPY it in to IIS location.(here release means you configuration)

Note : You need to do this for all packages built by the build server
  • Deploy using msdeploy command line tool ;
You can find your installed msdeply.exe in C:\Program Files\IIS\Microsoft Web Deploy

Once build server created the web package you can see a windows batch file named projectName.deploy  in Project\obj\release\Package. In the post built plugin script section what you need to do is run this batch file and it does the deployment.For that you need to go to the file where you can find msdeploy.exe and then run that batch file as follows.
C:\Program Files\IIS\Microsoft Web                               Deploy>H:project\obj\release\Package\MVC-Client.deploy.cmd /T 
It will deploy you web application in to the IIS location with the correct configurations which you want to deploy.

Note : You need to do this for all packages built by the build server


Saturday, January 14, 2012

Continuous Integration( Part Two) :Web Config Transformation


Note : In this post I will use Microsoft based technologies. But the main concept describes in a general manner.

In my previous post I mentioned that a build server should run the tests with its configurations(eg: data base connection strings) and if the test are successful then it should deploy working packages in to many web container location according to your requirement.For an example it should deploy a working package in to productions server as well as in to the live server with their specific configurations.(both application are pointing their own data bases)

production server => production database with tests data for QA guys
Live Server => live data base with the actual data 

In order to do this, build server has to create several packages with different configurations and deploy them in to required locations.There are many packaging tools which facilitate configuration transformation functionality.In this post I will use MSBuild command line tool to create IIS deployable packages.Before Moving on we need to know a bit detail knowledge about web config transformation.

If you have a close look in to your web.config file which created by VS2010 you will notice that there are two config files which named as web.Debug.config and web.release.config. Those two files default files which offer by VS2010.If you want your own you can add since VS2010 provides you an extensible configuration setting environment.

                          Build =>Configuration Manager  => Add your own configuration 

Lets assume we have created configuration for our production server which I mentioned above.Till you cant see it your latest configuration setting appears on web.config file. In order to set it you should do following step.

                         right click the original web.config file and click the context menu command “Add Config Transforms” 
In the Web.BuildServer.config file you can write specific settings which is specific to the build Server settings. Following is the way we do the we web.config transformation. 

 

    
      
     
   

You can see here we have used XML Transformation Engine which does the actual task when we package our project with build Server configurations.Followings are the some of functionality offer by transformation engine.


Other than the xdt:Transform tag you can see we have used a locator which refer the original web.config configurations. 
And following is the MSBuild command which we can transform web.config which has the build server configurations. 

                   /t:TransformWebConfig /p:Configuration=BuildServer" 

Also you can create your web deployment package with the build server settings by following MSBuild command.

           "ProjectName.csproj" /T:Package/P:Configuration=BuildServer;

It creates a ZIP file which has batch file which can be executed from MSDepoly command line tool.And also we can see transformed and original web.config files. Here we have a small problem.That is if we manually unzip this created zip file and then manually copy to the IIS location . then build server specific settings are not applying to it.Since in web.config file refers the transform elements from a external XML file which is used by the MSDeploy command and it is the task of MSDeploy tool to read the external XML property file and replace the matching tokens. So if you do the deployment manually I recommend you to copy the transformed web.config and replace the existing web.config file in the package.Then you can manually copy  package in to the IIS location and your app will work since now you have the build server configurations.

Ok.Now we should back to our main topic again which is Continuous Integration. If we can use above concept in the build server side (through a build server job) we can create a package in build server machine with its specific configurations and then deploy it. Also we can use same strategy for multiple deployment with many configurations.And my next post will describe how we can achieve this task. I hope to use jenkins build server and some of its plugins to do it.