Saturday, 14 July 2012

Java Web Service Client - Proxy Configuration

Over the past few days I’ve been integrating an application with the Experian bank account validation service. I’ve been using an Axis2 web service client to generate requests and call the service. My web service client worked fine in our office but when I deployed it on our customers sever (Tomcat running on Windows Server 2008) the client was unable to connect to the target URL.

The Axis client was throwing an UnknownHostException which meant that it wasn't able to resolve the service URL. Strangely though, on the same machine I was able to paste the same URL into a browser and view the service WSDL. After a little heading scratching I realised that all HTTP requests to public URLs had to be routed through our customers ‘bluecoat’ proxy server. I looked around and found a few different ways of doing this - I’ll document each approach and hopefully it’ll help out someone else.

Solution 1 - Set Proxy Details On Axis2 Web Service Stub
Axis provides a convenient way for you to set proxy configuration details if your web service request has to be routed through a proxy. The sample code below shows how this is done.
    
TokenServiceStub tokenService = new TokenServiceStub("https://secure.authenticator.uat.uk.experian.com/WASPAuthenticator/TokenService.asmx");

HttpTransportProperties.ProxyProperties proxyProperties = new HttpTransportProperties.ProxyProperties();
proxyProperties.setDomain("mydomain");
proxyProperties.setProxyName("192.192.135.189");
proxyProperties.setProxyPort(80);
proxyProperties.setUserName("myusername");
proxyProperties.setPassWord("mypassword");
tokenService._getServiceClient().getOptions().setProperty(HTTPConstants.PROXY, proxyProperties);

This code is pretty straight forward and simply sets the proxy details on a HttpTransportProperties.ProxyProperties object. That object is then set on the ServiceClients Options.
When the service stub (TokenServiceStub) is used to call a service method the HTTP request will be routed through the proxy defined above. This approach is very straight forward but is specific to this particular service stub. The next solution is a little more generic and can be used to proxy all web service requests sent by your application.

Solution 2 - Set Proxy Details programmatically as Java System Properties
This approach allows your application to set proxy details as Java system properties. The advantage of this approach is that it will ensure that all HTTP requests generated by your application will be affected which is convenient if you have an application with multiple web service clients. Rather than set proxy properties on each Service stub you can simply set them once as system properties and these values will automatically be used by all web service clients in your application. The code below shows how you can set target proxy details as system properties.
    
System.setProperty("http.proxyHost", "192.155.1168.101");
System.setProperty("http.proxyPort", "80");
System.setProperty("https.proxyHost", "192.167.134.103");
System.setProperty("https.proxyPort", "81");
System.setProperty("http.nonProxyHosts","192.168.170.105|192.168.170.104");
Note
If you need to support HTTPS proxying you can change http.proxyHost to https.proxyHost and http.proxyPort to https.proxyPort

By default these settings will ensure that all HTTP traffic is sent via the specified proxy. But what if you have exceptions to this rule? Luckily the nonProxyHosts setting allows you to specify one or more exceptions to the proxy rule. For example your application may connect to a number of internal and external services. You may only want to route the external service requests through the proxy and let internal requests go directly to their target URL. If this is the case you specify the hosts that you do not want to route through the proxy using nonProxyHosts. You can wildcard values using * and multiple entries are delimited by |.

Solution 3 - Set Proxy Details declaratively as JVM arguments
Another approach (this is the approach I went for) is to set the proxy values as JVM arguments. This means that your application code is free from having to set the proxy details programmatically. For a simple command line application you would set these values as follows.
java -Dhttp.proxyHost=192.164.162.103 -Dhttp.proxyPort=80 –jar StandaloneApp.jar
In most instances though your application will be deployed inside a servlet container like Tomcat. If this is the case you can add these values as JVM arguments that are read on server startup. In my case I had Tomcat set up as a windows service, so to add the proxy settings as JVM arguments I followed these steps.

1.       Go to $TOMCAT_HOME/bin
2.       Open Tomcat6W.exe and the following options will be displayed.
3.       Click on the Java tab
4.       Add your proxy settings to the existing list of JVM parameters as shown in the screenshot below.

Tomcat JVM Proxy Settings

If Tomcat is not running as a windows service you’ll need to add the start up parameters to Catalina.bat or Catalina.sh (depending on what platform you’re running Tomcat).

Sunday, 8 July 2012

Singleton Pattern

The Singleton pattern allows you to take control of object creation by ensuring that only one instance of a class is instantiated. This can be useful when you want to restrict resource use, or you have a sensitive object whose data shouldn’t be accessed by multiple instances (a registery object for example).
Imagine you have an object containing a large amount of reference data that you want to share across your application - you may want to ensure that you have only one instance of that object. Multiple instances of such a large object would unnecessarily increase the memory footprint of your application.

Typically objects are instantiated using the new operator - the following 3 lines of code will create 3 new ReferenceData objects.
    
    ReferenceData refData1 = new ReferenceData();
    ReferenceData refData2 = new ReferenceData();
    ReferenceData refData3 = new ReferenceData();
The Singleton pattern restricts the use of the new operator and ensures that only one instance of a class is created and shared across the application. But how do we actually stop our application creating more than once instance of a class? We simply make the constructor private so that it cannot be called form outside its own class as shown below.
    
public class ReferenceData
{
     private ReferenceData()
     {

     }
}    
Implementing the Singleton Pattern
At this point you’re probably thinking, if we can’t use the ReferenceDataSingleton constructor then how do we actually create an instance of the object?
We take care of this by using a static utility method to create and return an instance of the class as shown below. The standard naming convention for such a utility method is getInstance.
The code above is pretty simple but I’ll explain it below anyway.
public class ReferenceDataSingleton
{
     // because referenceDataSingleton is private it cannot be 
      // accessed from outside this class - the only way it can be 
      // accessed is via the static getInstance utility method below
      private static ReferenceDataSingleton referenceDataSingleton;

      private ReferenceDataSingleton()
      {

      }

      public static ReferenceDataSingleton getInstance()
      {
           // if referenceDataSingleton is null then we'll create a 
           // new instance of this object. We use the constructor
           // (even though its private) because we're creating the object 
           // inside the class itself */
           if(null==referenceDataSingleton)
           {
                referenceDataSingleton = new ReferenceDataSingleton();
           }

           // return the single instance of referenceDataSingleton 
           // each time this method is called
           return referenceDataSingleton;
      }
}
Line 6 - a reference to ReferenceDataSingleton is marked as private so that it cannot be accessed from outside the class. It’s also marked as static so that the reference is tied to the class and not an instance of the class - this means it can be referenced from the getInstance static utility method.

Line 8 - a private constructor ensures that instances of this class cannot be created from outside the class and forces external code to access this object via its static utility method as opposed to creating a new instance using the new operator.

Line 13 - Static utility method returns an instance of this class to the calling code. A new instance is only created and assigned to the static class variable if it does not already exist. Subsequent calls to this utility method will return the existing ReferenceDataSingleton reference. This ensures that no matter how many times this function is called it will always return a reference to the same instance of this class.
Calling the getInstance method returns a ReferenceDataSingleton object
Calling getInstance for a second time will return the same object as before. No matter how many times getInstance is called the same object is always returned.
Ensuring Thread Safety
While the code above will work fine in most instances there is still a potential flaw.
Can you spot the issue? Take a look at line 19 - here we check whether or not the class variable referenceDataSingleton has already been set and we only create a new instance if it is null. Imagine we have 2 threads that both check this condition at the same time - both threads could check this condition at the same time and find referenceDataSingleton is null, then both threads would create new instances of ReferenceDataSingleton on line 21. This would result in 2 separate instances of ReferenceDataSingleton being created, which could lead to havoc if our application thinks its dealing with a singleton.
At this point you're probably wondering how we get around this issue  - don't worry because I've described 2 possible solutions to this problem below.

Solution 1 - Mark method as synchronised
    
public static synchronized ReferenceDataSingleton getInstance()
{
      // if referenceDataSingleton is null then we'll create a
      // new instance of this object. We use the constructor
      // (even though its private) because we're creating the object
      // inside the class itself 
      if(null==referenceDataSingleton)
      {
           referenceDataSingleton = new ReferenceDataSingleton();
      }

      // return the single instance of referenceDataSingleton
      // each time this method is called 
      return referenceDataSingleton;
}    
By marking our getInstance method as synchronised we ensure that only one thread can execute the method at any time. While this is effective it can introduce a significant performance overhead by blocking new threads entering the method until the currently executing thread is finished.

Solution 2 – Create new instance outside of getInstance method
This approach removes the object creation code form the getInstance method and makes sure that the object is already created before the method is even called. We do this by instantiating ReferenceDataSingleton when the class is created and simply returns the reference to this object from getInstance.
    
public class ReferenceDataSingleton
{
      // because referenceDataSingleton is private it cannot be
      // accessed from outside this class - create a new instance of
      // this class which will be returned by the getIndssdtance utility
      // method below 
      //
      private static ReferenceDataSingleton referenceDataSingleton = new ReferenceDataSingleton();

      private ReferenceDataSingleton()
      {

      }

      public static synchronized ReferenceDataSingleton getInstance()
      {
            // return the single instance of referenceDataSingleton
     // each time this method is called             
     return referenceDataSingleton;
      }
}
This approach means we no longer have the performance overhead of a synchronised utility method yet we are still guaranteed that only one instance of the object will ever be created. Given there are no performance implications I’d recommend this approach over the synchronised method solution mentioned above.

Side Note
If you are using multiple class loaders with Singletons you may run into issues. Each class loader uses its own namespace so you may in fact end up with multiple Singleton objects (one per class loader). You’ll need to take the necessary steps to ensure that this doesn’t happen - I’ll not get into this now as it’s beyond the scope of this post but it’s definitely something you should be aware of.

Summary
The Singleton pattern allows you to ensure that only one instance of an object is created and shared across your application. This can be useful when you want to restrict resource use or have a sensitive object whose data shouldn’t be accessed by multiple instances.

Saturday, 7 July 2012

Observer Pattern

The observer pattern allows objects to communicate and exchange information using notifications. An observer object registers with and receives notification from a subject object. Any number of observers can register with a subject and when an event occurs a notification is sent to each of the registered observers. The observer pattern allows loose coupling between the object triggering the event and the objects that respond to the event. The diagrams below should help explain this a little better.

Figure 1.0 shows 2 observers registering with a subject.

Figure 1.1 shows the subject sending notifications to all 
registered observers when an event occurs.

Figure 1.2 shows one of the observers deregistering the subject. This 
object is no longer observing the subject and will not receive any further notifications. 

Figure 1.3 shows the subject sending a notification to the single registered observer.

Creating the Subject interface
We’ll start off by creating the Subject interface which should be implemented by any object that wants to send event notifications to other objects. The Subject interface is defined as follows.
public interface Subject
{
     public void registerObserver(Observer observer);
     public void unregisterObserver(Observer observer);
     public void notifyObservers(String event);
}
The 3 method signatures above are pretty intuitive - they provide a means of adding a new Observer, removing an existing Observer and sending a notification to all registered Observers. 

Creating the Observer interface
The Observer interface should be implemented by any object that wants to receive notification of events. The observer interface is defined as follows.
public interface Observer
{
     public void update(String event_p);
}
The update method is invoked (on the implementation class) by the Subject to notify the Observer that an event has occurred.

Creating a concrete Subject
Now we’re going to create a class called EventTrigger that implements the Subject interface.  I’ll explain each part of this class below.
public class EventTrigger implements Subject
{
     private List observers_i;

     public EventTrigger()
     {
          observers_i = new ArrayList();
     }

     @Override
     public void registerObserver(Observer observer_p)
     {
          observers_i.add(observer_p);
     }

     @Override
     public void unregisterObserver(Observer observer_p)
     {
          observers_i.remove(observer_p);
     }

     @Override
     public void notifyObservers(String event_p)
     {
          for(Observer observer: observers_i)
          {
              observer.update(event_p);
          }
     }
}
Line 3 - Defines a list that will hold all Observers registered with this object. New Observers registered with Event Trigger it will be added to this list.

Line 5 to 8 - The class constructor instantiates a new ArrayList that will be used to hold registered Observers.

Line 11 to 14 – Adds new Observer objects to EventTrigger.  The method parameter is added to our list of Observers and as a result will receive notification of events fired by EventTrigger.

Line 17 to 20 - Removes an existing Observer from EventTrigger.  The parameter is removed from the list of Observers and as a result will no longer receive notification of events fired by EventTrigger.

Line 23 to 29 – Notifies all Observers by iterating over each registered object and invoking its update method.

Creating concrete Observers
Next we’ll create the Observers that will register with the EventTrigger above. We’ll have 2 observers, EventHandler1 and EventHandler2 which must both implement the update method. Both classes are defined below. 
public class EventHandler1 implements Observer
{
     public EventHandler1()
     {

     }

     @Override
     public void update(String event_p)
     {
          System.out.println("Event handler 1 received event: " + event_p);
     }
}

public class EventHandler2 implements Observer
{
     public EventHandler1()
     {

     }

     @Override
     public void update(String event_p)
     {
         System.out.println("Event handler 1 received event: " + event_p);
     }
}
You’ll notice that both EventHandlers are pretty much identical and simply log the event triggered by
the Subject they’re registered with. I’ve created 2 events handlers so that I can show multiple observers registering with a subject.
Note: We could have replaced both the Observer and Subject interfaces with abstract classes. Interfaces 
however give us greater flexibility as the implementing class is free to implement multiple interfaces but extend only one class. By implementing interfaces in this example we are leaving the implementation classes free to participate in a different inheritance hierarchy.

Testing the Observer pattern
We’re now ready to put the observer pattern to the test with a simple test harness.
public class TestObserverPattern
{
     public static void main (String[] args_p)
     {
          Observable eventTrigger = new EventTrigger();
          eventTrigger.registerObserver(new EventHandler1());
          eventTrigger.registerObserver(new EventHandler2());

          eventTrigger.notifyObservers("This is a test event!!");
     }
}
Line 5 - Creates a new EventTrigger (subject) object - this is the Subject that Observers will register with for notifications.

Line 6 and 7 - Creates and registers a new EventHandler (observer) with the EventTrigger.

Line 9 - Sends a notification to each of the registered EventHandlers.

Running the test harness prints the following to the console. I’ve attached the code to this article so that you can download and run it yourself.

Event handler 1 received event: This is a test event!!
Event handler 2 received event: This is a test event!!

Summary
The observer pattern allows objects to communicate using a notification mechanism while remaining loosely coupled. This results in components that are easier to debug and maintain. You should consider the observer pattern for situations where you have objects triggering events that you want other objects to react to.