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.