Tuesday, October 16, 2012

Java Coding Tips with New Features

Every release of JDK involves few minor enhancements, which are majorly overlooked under the shadow of major ones, but can be very handy in day-to-day coding. In this article I tried to collate a list of such minor enhancements (taken from JDK 5, 6 and 7), which can really make your code efficient, clean and less error-prone.

Catching Multiple Exceptions in Single Catch Block (Since JDK 7)

Consider  an example where your try block can throw multiple exceptions and those are caught separately but the codes within catch blocks are same, as shown below
 
try {
    //some code which can throw IOException and ParseException
            } catch (ParseException exception) {
             //log the error
            //create new custom exception
            //throw exception
} catch (IOException exception) {
           //log the error
           //create new custom exception
           //throw custom exception
            }
 
The multiple catch blocks can be combined together as shown below
try {
//some code which can throw IOException and ParseException
            } catch (ParseException | IOException exception) {
                 //log the error
                //create new custom exception
                //throw custom exception
            }
 
This can improve the code reusability, exception handling and overall code structure.

Try with Resources (Since JDK 7)

How many times you needed to take care of closing the streams and other resources after performing write/read operations. Typically we use finally blocks for these mandatory actions. But now the same can be auto-close by Java, if you use try-with-resource blocks as shown below.
Older way:
            FileInputStream fis = null;
       try {
              fis = new FileInputStream("SomeFile")
              //Do something with File input stream, but you needn't to close it.
             } catch (IOException ioException) {
              //Do something      
       } finally {
              fis.close();
       }
 
Try with resource statement:
           try (FileInputStream fis = new FileInputStream("SomeFile")) {
              //Do something with File input stream, but you needn't to close it.
           } catch (IOException ioException) {
              //Do something
           }
 
 
This will allow developers to avoid error of not closing the resource and extra repeating code. Any implementation of AutoCloseable interface can be used as resource with try block.

Switch with String (Since JDK 7)

A much awaited feature of Java. Prior to 7, only int or enums were allowed inside switch statement, but with jdk 7, you can also work with Strings inside switch, as shown below:
 
           String day = "Tuesday";
           switch (day) {
              case "Monday" : //do something
              break;         
              case "Tuesday" : //do something
              break;            
              default : //for all other days
              break;
           }

Underscore in Numeric Literals (Since JDK 7)

Many times, while using numerical literals, you found it difficult to read its value for e.g.
 
long bankAccountNumber = 1007876345678L;
How good it would be, if we can use some separator for better readability (for e.g. if first 3 digits indicates bank’s state wise code, while next 4 for bank code and rest as individual number)? JDK 7 allows you to use as many underscores as you need within the numeric literals. For e.g.
 
long bankAccountNumber = 100_7876_345678L;
This greatly improves the readability of your code.

Type Inference for Generic Instance Creation (Since JDK 7)

Prior to Java 7, if you use generics, you need to pass type arguments to call appropriate constructor, but with JDK 7 now that is options hence the code,
 
Map> mapofMap = new HashMap>(); 
Can now be replaced with
Map> mapofMap = new HashMap<>();
This enhances the code readability, and avoid unnecessary repetition of generic parameters.

Varargs (Since JDK 5)

How many times you need to create an array, may be of single value, just because your method needs array as input? Let’s see the code below

public class Test { 
       public static void main(String[] args) {
              String inputsingle = "SingleString";
              new Test().needArray(new String[]{inputsingle});
       }
       private void needArray(String[] input) {
              //do something with string array
       }
}
But now with JDK 5, the last parameter of the method can have 3 dots to represent varargs, which means, the compiler will create the array while invoking this method for you. Hence the above code can be written as shown below:
public class Test { 
       public static void main(String[] args) {
              String inputsingle = "SingleString";
              new Test().needArray(inputsingle);
              new Test().needArray(new String[]{"a", "b","c"});     
       }
       private void needArray(String...input) {
              //do something with string array
       }
}  

Static Imports (Since JDK 5)

If you fade up using class name for static variables, you can use static import as shown below.
Instead of writing code like
       Color black = Color.BLACK;
       Color red = Color.RED;
You would write like
import static java.awt.Color.*;
and then use the static variable directly
Color black = BLACK;
       Color red = RED;
This avoids the repeating prefixing of class name. But beware, it can reduce the code readability as well. Read More: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

Rethrowing exceptions with improved types (Since JDK 7)

There are instances where, although you catch the higher level exception but still, you want to throw specific exceptions. Let’s consider the code below which is valid for JDK 6 and prior versions:

public void method() throws Exception {
              try {
         //Some code which can throw Exception1 and Exception 2 (sublcasses of Exception)
             } catch (Exception e) {
                     throw e;
             }
       }
With the improved types in throws clause in JDK 7, now you can also throw specific exceptions, thus the above method can also be written as
public void method() throws Exception1, Exception2 {
              try {
         //Some code which can throw Exception1 and Exception 2 (sublcasses of Exception)
              } catch (Exception e) {
                     throw e;
              }
       }
As complier can understand that the code can only throw Exception1 and Exception2, it allows to define method which can throw specific exception, along with allowing the catch of higher level exception object.
 
 

Sunday, October 7, 2012

Web & Business Service Integration Approaches


In one of my recent projects, during finalizing the technology stake for a new web application, I got to a situation where I needed to decide the integration strategy between different layers including web and business service layer. The key point to decide here is whether to use the smooth and out-of-the-box integration mechanism provided by the frameworks or use standard J2EE design pattern for framework agnostic integration.

To be specific, we were using Struts 1.3 (I love the simplicity of Struts 1.x MVC framework, apart from all other reasons why we selected it) at web tier, and Spring IoC at business service tear. And the decision to make is whether to use the Spring supported integration with Struts framework (using ContextLoaderPlugIn, extending ActionSupport class, using DelegatingRequestProcessor etc) OR using Business Delegate pattern to completely separate the two layers.

The below 2 diagrams further depicts the 2 possible scenarios.



In other words, we had the option of either using Spring support for Struts (using ContextLoader plugin, extend to Actionsupport class etc). The Spring’s Actionsupport class provides easy-to-use methods to get the Spring IOC’s context to get access to service beans. OR we use Business Delegate pattern, in which a separation layer will be introduced between web and service layer. This layer will delegate calls to service layer and provide abstraction. Also, the task of locating the services can be handed over to service locator.

Here is the list of advantages and cons with each of these approaches.
Using Spring provided smooth integration approach
1.      It provides an easy mechanism of integration. The Spring provided ActionSupport class provides an easy way to get the Spring beans, through web context.

2.      Being a direct communication between web and business service tier, it doesn’t involve other layers and hence a bit advantageous from performance perspective.

3.      The biggest issue with this approach is tight coupling between the 2 layers. Web tier not only knows about the business service tier but also has information about with what name the bean is registered and how to get handle of the bean.

4.      Another issue being that the service tier has direct exposure to web tier and hence web tier knows each core business service. This may result in multiple network calls from web to service tier.

5.      Practically, it would be difficult to deploy web and service tier in distributed manner.

Using Business Delegate Pattern
1.      The web and service tiers are loosely coupled and separated by business delegate layer.

2.      Business delegate pattern provides abstraction over the core business services. For e.g. to accomplish a particular task, business delegate may need to call multiple services but web tier needs to call a single method on delegate. In other words, orchestration of services can be accomplished in much better manner with business delegate pattern.

3.      Business exceptions can be handled more efficiently at delegate layer.

4.      The services are located using service locator, which is the only entity has knowledge as where and how services are registered and deployed. This could be very useful in case of distributed environment.

5.      The only drawback is to have additional layer (delegate) and service locator entity in the architecture.

Finally we decided to adopt the 2nd approach, using business delegate pattern and results were quite satisfactory.

Conclusion: Spring provides direct integration with different web frameworks, but to choose it or adopt business delegate pattern, should be pondered well in the given situation. Loose coupling, separation of concerns and abstraction, would always be helpful in long run.

References:
1.       http://static.springsource.org/spring/docs/2.5.5/reference/web-integration.html
2.       http://corej2eepatterns.com/Patterns2ndEd/BusinessDelegate.htm

Monday, July 16, 2012

JAXB XmlAdapter – Customized Marshaling and Unmarshaling

JAXB (Java Architecture for XML Binding), is an easy to use and efficient framework for working with XML documents in Java. A developer can easily convert an XML into Java objects (Unmarshaling) and vice versa (Marshaling) using JAXB. Although simple Java types (String, int) can be directly maps to XML types, sometimes a customized representation is required. For e.g. consider an XML snippet below

<config>
   <properties>
      <property name="name 1" value="value 1"/>
      <property name="name 2" value="value 2"/>
   </properties>
</config>

By default JAXB will bind it to the following Java object structure

@XmlRootElement
public class Config {
       @XmlElement (name="properties" type=Properties.class)     
        public Properties properties;
       …….
}

@XmlType
public class Properties {
        @XmlElement
       public List property;
       …………
}

@XmlType
public class Property {
      @XmlAttribute
       public String name;
       @XmlAttribute
       public String value;
       ……….
}

But imagine a scenario where you want the domain object to look like this

public class Config {
      public HashMap properties; //Map of property name and value
}

This is a typical case where you want to read an XML configuration file and maintain the properties in a Map.

To achieve this, you need a mechanism to intercept the default marshaling and unmarshaling of JAXB. And this can be done using XMLAdapter.

JAXB provides interceptors, in the form of XMLAdapters, to customize the marshaling and unmarshaling during binding. The below screen explains the concept.

Let’s consider the above example and see how can we achieve the expected output using adapters.

First of all, note that XMLAdapter is a customization on the top of default binding and hence the default classes, mentioned above, i.e. Config, Properties and Property need to be there. Now write a custom adapter. Customer adapters are provided with 2 parameters, one which JAXB will bind and one which you need as output of binding. Within adapter, you need to implement the logic of converting one to another. Here is how our custom adapter would look like.

public class CustomAdapter extends XmlAdapter> {
       @Override
       public Properties marshal(HashMap map) throws Exception {
              Iterator> itr = map.entrySet().iterator();
              ArrayList list = new ArrayList(map.entrySet().size());
              while (itr.hasNext()) {
                     Entry entry = itr.next();
                     Property property = new Property();
                     property.setName(entry.getKey());
                     property.setValue(entry.getValue());
                     list.add(property);
              }
              Poperties properties = new Properties();
              properties.setProperties(list);
              return properties;
       }
       @Override
       public HashMap unmarshal(Properties properties) throws Exception {      
              List list = properties.getProperties();      
              HashMap map = new HashMap(list.size());
              for (Property property : list) {               
                  map.put(property.getName(), property.getValue());
              }
              return map;
       }
}

Along with this, now we need to change the root element class a bit, since we want the Hashmap as the value holder now.
@XmlRootElement
public class Config {      
       @XmlJavaTypeAdapter (CustomAdapter.class)
       @XmlElement (name="properties", type=Properties.class)
       private HashMap properties;
       ………………
}

Now write a method to test the unmarshaling.

public void testUnmarshal() {
       try {
              JAXBContext context = JAXBContext.newInstance(Config.class);
              Config config = (Config) context.createUnmarshaller().unmarshal(new File("config.xml"));
              Iterator> itr = config.getProperties().entrySet().iterator();
              while (itr.hasNext()) {
                     Entry entry = itr.next();
                     System.out.println(entry.getKey() + "  " + entry.getValue());
              }                   
       } catch (JAXBException e) {
              e.printStackTrace();
       }
}

The output of the above test method would be
name 1   value 1
name 2   value 2


Conclusion: JAXB provides XMLAdapters as a way to the developer to intercept the marshaling and unmarshaling process and write code to custom mappings.

Sunday, July 15, 2012

Hibernate Inverse Attribute – Re-Explained

It was few years ago, when I started working on the newer version of Hibernate, the first and the most confusing term I encountered is ‘inverse’ attribute. Although soon I realized that it is not that complex and perplex, however its name and the way people explained it, added lot of confusion around it.

This blog is yet another endeavor to explain this attribute, and possibly in the most simple way using easily understandable examples.

Before we start, note that inverse attribute is used in bidirectional mapping including one-to-many and many-to-many (soon you will realize that it make sense).

Now, whenever you get an inverse attribute with true value in collection mapping (for e.g. set) of an entity mapping, read it like this: “I am not the one who is responsible for maintaining this relationship, but the inverse is true i.e. the other entity in the relationship is responsible for this”.

Let’s explore this with examples.

We’ll consider an example which includes both one-to-many and many-to-many relationship. Assume 3 entities, Employee, Department and Certification. The relationship between Department and Employee is one-to-many from Department side (i.e. One department can have many employees, but an employee belongs to one department only). While the relationship between Employee and Certification is many-to-many (i.e. an employee can have many certifications while a certification can belong to multiple employees). Here is how this would look like



The relationship between Employee and Certification is maintained using a relationship table (Emp_Cert) as shown below.
 

 
The domain and mapping of the 3 entities would look like this:

public class Employee {

     private int id;
     private String name;
     private Department dept;
     private Set certs;
    //Setters Getters…
}

<class name="Employee">
     <id name="id">
        <generator class="sequence"/>
     </id>
     <property name="name"/>
     <many-to-one name="dept" class="Department" column="dept_id"></many-to-one>
     <set name="certs" inverse="false" table="emp_cert">
        <key column="emp_id"/>
        <many-to-many column="cert_id" class="Certification"/>
     </set>
</class>


public class Department {

      private int id;
      private String name;
      private Set emps;
      //Setters Getters…..
}

<class name="Department">
     <id name="id">
       <generator class="sequence"/>
     </id>
     <property name="name"/>
     <set name="emps" inverse="false">
        <key column="dept_id"/>
        <one-to-many class="Employee"/>
     </set>
</class>

public class Certification {

      private int id;
      private String name;
      private Set emps;
      //Setters Getters…..
}

<class name="Certification">
     <id name="id">
        <generator class="sequence"/>
     </id>
     <property name="name"/>
     <set name="emps" inverse="false" table="emp_cert">
        <key column="cert_id"/>
        <many-to-many column="emp_id" class="Employee"/>
     </set>
</class>

Note that inverse attribute is used only in collection mapping for e.g. set.

Let’s first discuss the one-to-many relationship.

In the Department mapping above, since the inverse attribute has false (default) value for employee set, it indicates that you can also add Employees through Department class.

Consider the code below:

//Set ID from DB.
int empID = 1;
int deptID = 1;

SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, empID);
Department dept = (Department) session.get(Department.class, deptID);
dept.getEmps().add(emp);//This will be saved in DB as inverse is false.
tx.commit();
session.flush();

The execution of above code will result in an Update SQL statement to update the dept_id value of given Employee.

Now consider the case of inverse=”true”. The mapping would look like this:

<class name="Department">
     <id name="id">
        <generator class="sequence"/>
     </id>
     <property name="name"/>
     <set name="emps" inverse="true">
        <key column="dept_id"/>
        <one-to-many class="Employee"/>
     </set>
</class>

This tells hibernate that Department entity is not responsible for maintaining the relationship.

Thus if the same above code is executed again, Hibernate won’t execute any update SQL and employees’ dept_id won’t be updated.


Thus in one-to-many, we use inverse always in the side which is ‘one’ in the relationship and which indicates that this is not the side which will maintain relationship.

Now consider the case of many-to-many relationship. In this example, relationship between Employee and Certification is many-to-many. An employee can do any number of certificates while a certification can be done by more than one employee.

In many-to-many relationship, both sides or one of them can be responsible for maintaining the relationship. Thus inverse attribute can be set true at any side, which you think is not responsible for maintaining relationship. Consider the code snippet below

//Set ID from DB.
int empID = 1;
int certId = 1;

SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = (Employee) session.get(Employee.class, empID);
Certification cert= (Certification) session.get(Certification.class, certId);

//If inverse is false in both employee and certification mappings, you can execute any of the below 2 statements. Both will result in same (insertion in emp_cert table)
//But if inverse is true in certification mapping, statement 2 won't work.
//If inverse is true in employee certification, statement 1 won't work.
//emp.getCerts().add(cert); //statemet 1
//cert.getEmps().add(emp); //statement 2

tx.commit();
session.flush();

If inverse is false at both end, any of the below 2 statement can result in insertion of an entry in emp_cert table.

emp.getCerts().add(cert); //statemet 1
cert.getEmps().add(emp); //statement 2

But assume that inverse is true in Certification mapping, then statement 2 won’t result in SQL insert statement for emp_cert table and hence no row will be inserted in this table.

<class name="Certification">
     <id name="id">
        <generator class="sequence"/>
     </id> <property name="name"/>
     <set name="emps" inverse="true" table="emp_cert">
     <key column="cert_id"/>
       <many-to-many column="emp_id" class="Employee"/>   
     </set>
</class>

Similarly, if inverse attribute is true in Employee mapping, then statement 1 above will not insert any row in emp_cert table.

Conclusion: I hope after reading this article and understanding this example, you will realize that inverse attribute in hibernate is an easy to understand and very helpful parameter in optimizing the bidirectional relationship.