Monday, July 21, 2014

Creating a Java @WebService using @Interceptors

This post will explain how to set up a maven webservice which uses an interceptor class. To do this just create a maven project using maven-archetype-webapp as archetype - e.g., per command line:

mvn archetype:create -DgroupId=package.name -DartifactId=project_name -Dpackage=package.name.project_name -Dversion=1.0-SNAPSHOT -DarchetypeArtifactId=maven-archetype-webapp

As I am using glassfish v 3.1.1 as application server and java 1.6 following pom file is used:
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sjd.simple</groupId>
    <artifactId>SoapService</artifactId>
    <packaging>war</packaging>
    <version>1.0.0</version>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jaxws.plugin.version>2.1</jaxws.plugin.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.2-b06</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!-- Set the name of the war, used as the context root when the app is 
            deployed -->
        <finalName>SoapService</finalName>

        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.1.1</version>
                <configuration>
                    <!-- Java EE 6 doesn't require web.xml, Maven needs to catch up! -->
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <!-- Compiler plugin enforces Java 1.6 compatibility and activates annotation 
                processors -->
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

        </plugins>
    </build>

</project> 
Using annotations, the actual implementation of the WebService is very straight forward. Just add an @WebService annotation to your class. If you want to implement an interceptor you just have to use the annotations @Interceptor and specify the class which should be used. Also we will have to annotate our class as java bean.
@Stateless marks this bean as a Stateless Session Bean, and @WebService causes the application server to make all public methods of this bean accessible as web service calls.
Here the interceptor is used for every method insiede our WebService class (You may also use this annotation for individual methods).
package com.sjd.simple;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jws.WebMethod;
import javax.jws.WebService;

@Stateless
@WebService
@Interceptors( { AuthenticationInterceptor.class } )
public class HelloWorld implements IHelloWorld {

  public HelloWorld() {
    // nothing to do
  }

  @Override
  @WebMethod
  public String sayHello(String bla) {
     return "Hello !";
  }
}

For the interceptor you will have to write a normal POJO class, but add the annotation @AroundInvoke to a method. This annotation may be applied to any non-final, non-static method with a single parameter of type InvocationContext and return type Object of the target class/superclass or of any interceptor class. The annotated method will be called before each method that uses this class as interceptor.
package com.sjd.simple;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class AuthenticationInterceptor {

  @AroundInvoke
  public Object invoke(final InvocationContext ctx) throws Exception {
    if (ctx != null) {
      System.out.println("test");
      return ctx.proceed();
    } else {
      return null;
    }
  }

}


As you can see, implementing a @WebService using an interceptor is fairly easy - but be careful since the interceptor will only work if following requirements are met:

javax.interceptor.Interceptors may be bound to a simple Web Bean, enterprise Web Bean or EJB 3 style session, singleton or message driven bean using the javax.interceptor.Interceptors annotation, or by using a Web Beans interceptor binding. - docs.jBoss

In this case we are using beans as @WebServices, it seems that the URL used to access it changes from:
http://localhost:8080/<application_name>/<class_name>Service?wsdl to
http://localhost:8080/<class_name>Service/<class_name>?wsdl
example:
http://localhost:8080/SoapService/HelloWorldService?wsdl    [without @Stateless]
http://localhost:8080/HelloWorldService/HelloWorld?wsdl       [with @Stateless]
I only figured that one out because of this report: @WebService and @Stateless not showing endpoint in GlassFish 4.0 admin console

Of course you may change this default URL by the serviceName and name attribute of the @WebService annotation: e.g., @WebService(serviceName="soap", name="testservice"), which would result in following URL to access our webservice: 
http://localhost:8080/soap/testservice?wsdl 
 
I hope I could provide some help on how to implement a webservice, while using interceptors. Also here is another link to a nice much more detailed tutorial on WebServices in general.



Monday, July 14, 2014

Eclipse: How to change the version of project facet Dynamic Web Module

I sometimes run into a maven problem while using eclipse, when trying to change the version number of my project facet Dynamic Web Module. There are two things you can do to solve this issue:
  • Check your web.xml for correct attributes:
    <?xml version="1.0" encoding="ASCII"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns="http://java.sun.com/xml/ns/javaee"
                   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
                   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
                   version="3.0">

    </web-app>
  • Edit the org.exlipse.wst.common.project.facet.core.xml, located in the .settings folder of your eclipse maven project. Change the version number of the following tag to the one you desire for your Dynamic Web Module:
    <installed facet="jst.web" version="3.0"/>
Dont forget do execute a Maven -> Update Project after you are finished.

Thursday, July 3, 2014

Database exception handling

When working with databases (Connection, Statement, ResultSets) you might have run into problems because of wrong excpetion handling. If done like in the following example, you will most definitly run into problems as soon as an Exception is thrown:
Connection dbConnection = DbConnectionManager.getInstance().getConn();

if (dbConnection != null) {
  String sqlStatement = "...";

  try{
    Statement stmt = dbConnection.createStatement();
    // do something (which might also throw an SQLException)

    try{ 
      ResultSet rs = stmt.executeQuery(sqlStatement);
      // do something (which might also throw an SQLException)
      rs.close();
    } catch (SQLException e2) {
      // handle exception
    }
    stmt.close();
  }catch(SQLException e1){
    // handle exception
  }
}

Just imagine an exception being thrown after executing a query and successfully creating a ResultSet. Due to the exception the ResultSet will not be closed. This may very well result in an ORA-01000: maximum open cursors exceeded Exception. That is why it is always a good idea to close your resources in a finally block. The finally block ensure, that code is processed even if an unexpected exception occurs. (It is always executed when the try block exits).
Connection dbConnection = DbConnectionManager.getInstance().getConn();

if (dbConnection != null) {
  String sqlStatement = "...";

  try{
    Statement stmt = dbConnection.createStatement();
    // do something (which might also throw an SQLException)

    ResultSet rs = stmt.executeQuery(sqlStatement); 
    try { 
      // do something (which might also throw an SQLException)
    } catch (SQLException e2) {
      // handle exception
    } finally {
      rs.close(); // is closed even if an exception is thrown 
                  // while processing the ResultSet
    }
  } catch(SQLException e1) {
    // handle exception
  } finally {
    stmt.close(); // is closed even if an exception is thrown 
                  // when calling executeQuery
  } 
}

Monday, June 30, 2014

Command pattern

Command pattern: Encapsulates a request as an object, thereby letting you parametrize
other objects with different requests, queue or log requests, and support
undoable operations.
.
The command pattern allows you to decouple the requester of an action from the object actually performing the action. By introducing 'command objects' into the application design, we can encapsulate a request to do something.
command pattern uml
(command pattern)
A nice example would be programming a software for a remote. This remote should work with various devices and therefore does not know what it should do for each device. For each button we will assign a command object that knows how to communicate with the right object (receiver) that gets the work done. Using an API (application programming interface) command objects can be loaded into button slots, allowing the remote code to stay very simple.
// every class you want to use as a command object will have
// to implement this interface
public interface Command {
  public void execute();
}
Each 'command object' is bound to a specific object before it is assigned to the remote (e.g., create one LightOnCommand object for the kitchen light and one for the living room light). 
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on(); // here we execute everything we want to do with the receiver object
  }
}
public class SimpleRemoteControl() { // in the UML: invoker
  Command[] commands;

  public SimpleRemoteControl() {
    commands = new Command[5];
    // it might be a good idea to initialize all commands with a NullObject
    // (an object implementing the Command interface, which does nothing -
    // this way you wont have to check if an element of commands is null)
  }

  // the command object may be changed at runtime
  public void setCommand(int slot, Command command) {
    commands[slot] = command;
  }

  // if the remote button is pressed we call the execute method of
  // our Command object
  public void buttonWasPressed(int slot) {
    commands[slot].execute();
  }
} 
The remote object does not care what command object is in its slot, as long as it implements the Command interface. The command pattern is extremely useful as the following sections will show (besides what you have already read):

Undo
With the command pattern it is very easy to implement undo actions. Simply add another method to the Command interface. When implementing this method, perform the exact opposite action/s you implemented in execute. You will also have to add a reference to the last Command that was performed (set whenever method buttonWasPressed() is called), as well as a new method undoButtonWasPushed() to our SimpleRemoteControl class.
public interface Command {
  public void execute();
  public void undo();
}
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on();
  }

  public void undo() {
    light.off(); // oposite action of turning a light on
  }
}
This is easy for objects, which have only two states. If there are more states you will have to maintain a variable storing the previous state every time a new state is set. In case of an undo action you will just have to set the current state equal to the previous state.
Sometimes you want to be able to press an undo button multiple times. To implement such an undo history, instead of keeping track of just the last Command executed, you keep a stack of previous commands. Every time the undo button is pressed, you can pop a command object off the stack and execute its undo method.

Macro command
If you have a situation where several commands should be executed at once you can still use our usual command interface, but use an Array of commands for the constructor. Neat isn't it?:
public class MacroCommand implements Command() {
  Command[] commands; // command array

  public MacroCommand(Command[] commands) {
    this.commands = command;
  }

  public void execute() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].execute();
    }
  }

  public void undo() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].undo();
    }
  }
}

Queuing requests
The command pattern offers the possibility to package a piece of computation and pass it around as first class object. The actual computation may be invoked long after some client application creates the command object. This is very nice if you are working with multiple threads. You can use this for schedulers, thread pools, job queues, ...
Furthermore threads don't even have to be assigned for specific tasks. One time a thread may be computing a math problem, and the next time it may be sending something over the network. Using the command pattern, the job queue classes are totally decoupled form the objects that are doing the computation.

Logging requests
You may store and load command objects on disk, using java object serialization. Take a spreadsheet application for example: You might want to implement a failure recovery by logging the actions on a spreadsheet rather than writing a copy of the spreadsheet to disk every time a change occurs.

I hope this post gives you an idea of the usefulness of the command pattern. See you next time.

Tuesday, June 24, 2014

StreamSources

If you happen to use StreamSource for whatever reason, you might have encountered FileSystemExceptions if you used it like that:
  File xmlFile = new File("asdf.txt");
  final StreamSource source = new StreamSource(xmlFile.toFile());
  // other operations
If you try to move or delete this file later on you will get: java.nio.file.FileSystemException the process cannot access the file because it is being used by another process. The reason for this is simple. By passing File directly into StreamSource you lose control of how/when to close the file handle. Using a FileInputStream will solve this problem:
  final FileInputStream inputStream = new FileInputStream(xmlFile.toFile());
  final StreamSource source = new StreamSource(inputStream);
  // do anything you want
  inputStream.close();
We should never forget to close a stream after using it. To be certain that a stream is closed, even if something goes wrong, we have to do proper exeption handling:
   FileInputStream inputStream = null;
   try {
      inputStream = new FileInputStream(xmlFile.toFile());
      final StreamSource source = new StreamSource(inputStream);
      // other code here
   } catch (final Exception e) {
     // handle your exceptions
   } finally {
      if(inputStream!=null){
        try {
          inputStream.close();
        } catch (final IOException e) {
          // report      
        }
   }
This way the sream gets closed, even if an exception was thrown by another part of the code inside the try block.

Singleton pattern

Singleton pattern: Ensures a class has only one instance, and provides
a global point of access to it.
.
There are often situations where you want an object to exist once and only once during run time of an application (e.g., for preferences, logging, thread pools, caches ...). Instantiating more than one of these objects often causes incorrect program behavior, overuse of resources or inconsistent results (due to multiple copies of objects).

The classic implementation of a singleton uses a private constructor, which is called by a static method - acting as the global point of access, preventing other classes to create new instances on their own:

public class SingletonClass{
  private static SingletonClass instance;

  private SingletonClass(){
  }

  // the static instance variable will only get instantiated once
  // after that it wont be null and therefore the private constructor
  // wont be called again
  public static SingletonClass getInstance(){
    if(instance==null){
      instance = new SingletonClass();
    }
    return instance;
  }
}

Another effect of the singleton is that the instance variable is instantiated in a lazy fashion. The object will only be created when really needed (the moment getInstance() is first called). A global variable might be created when you application begins. If an object is resource intensive and an application does not always ends up using it, using a singleton might be the better choice.

Multithreading

You have to be careful though when using multiple threads. If two threads call the getInstance() method at the same time, it may result in creating two instances of the SingletonClass. To prevent this from happening you can add synchronized to the getInstance() method:

public static syncronized SingletonClass getInstance(){
  if(instance == null){
    instance = new SingletonClass(); 
  }
  return instance;
}


Synchronized forces every thread to wait its turn before it can enter the method. No two threads may enter the method at the same time. This is expensive, particularly because the only time synchronized is relevant/needed is the first time through this method (after that instance is not null anymore).

You have three options:
  1. Use syncronized if the performance of getInstance() is not critical to your application.
  2. Use an eagerly created instance rather than an lazily created one. The JVM guarantees that the instance will be created before any thread accesses the static instance variable.
    public class SingletonClass{
      private static SingletonClass instance = new SingletonClass();
    
      private SingletonClass(){
      }
    
      public static SingletonClass getInstance(){
        return instance;
      }
    }
  3. Use double-checked locking to reduce the use of syncronization in getInstance(). We first check to see if instance is created, and if not, we syncronize. This way we only synchronize the first time, when instance is still null.
    public static SingletonClass getInstance(){    
        if(instance==null){
          synchronized (Singleton.class){ 
            if(instance==null){
              instance = new SingletonClass();
            } 
          }
        }
        return instance;
    }
You have to be careful though if you use multiple classloaders. Each classloader defines its own namespace and therefore more than one version of a class can exist, resulting in more than one instance of the singleton. By specifying the classloader yourself you can solve this issue.

Monday, June 23, 2014

Abstract Factory Pattern

Abstract Factory Pattern: Provides an interface for creating families of
related or dependent objects without specifying their concrete
classes.
.
Often the abstract factory is mistaken for a factory method. While they are both good at decoupling applications form specific implementations, it is done in different ways. Both patterns create objects, but the factory method (factory method pattern) does it through inheritance, while the abstract factory uses object composition.

To create an object using the factory method pattern, you need to extend a class and override a factory method - which will create a concrete object. The abstract factory pattern provides an abstract type for creating a family of products (groups together a set of related products). Subclasses of this type define how those products are produced. Often you can use the factory method pattern to program an abstract factory: concrete factories implement a factory method to create their products (purely to create products).


abstract factory pattern uml
(abstract factory uml)
Using our pizza store from my previous post as an example (factory method pattern), this is how it could be implemented using the abstract factory pattern:

public class AustrianPizzaStore extends PizzaStore{
  protected Pizza createPizza(String type){
    Pizza pizza = null;
    // this is our abstract factory
    PizzaIngredientFactory ingredientFactory = new AustrianPizzaIngredientFactory();
    if(type.equals("cheese")){
      // the concrete factory is passed as argument when creating a new pizza
      pizza = new CheesePizza(ingredientFactory); 
      pizza.setName("Austrian Style Cheese Pizza");
    }else if(type.equals("veggie"){
      pizza = new VeggiePizza(ingredientFactory);
      pizza.setName("Austrian Style Veggie Pizza");
    }
    return pizza;
  }
} 

public class CheesePizza extends Pizza{
  PizzaIngredientFactory ingredientFactory;

  public CheesePizza(PizzaIngredientFactory ingredientFactory){
    this.ingredientFactory = ingredientFactory;
  }

  // the abstract pizza classhas membervariables for all
  // ingredients (e.g., Cheese, Sauce, ...)
  void prepare(){
    dough = ingredientFactory.createDough();
    sauce = ingredientFactory.createSauce();
    cheese = ingredientFactory.createCheese();
  }
}

public class AustrianPizzaIngredientFactory implements PizzaIngredientFactory {
  public Dough createDough(){
    return new ThinCrustDough();
  }
  public Sauce createSauce(){
    return new TomatoSauce();
  }
  public Cheese createCheese(){
    return new GudaCheese();
  }
  // this class has to implement every method defined in the 
  // PizzaIngredientFactory interface (Veggies, Pepperoni, Clams ...)
}
As you can see, to use the factory, one subclass is instantiated and passed into some code (AustrianPizzaFactory, CheesePizza) that is written against the abstract type. A disadvantage is that if a set of related products is extended (e.g., adding another ingredient) the whole interface has to change, which means that you have to change the interface of every subclass ... lots of work.

But the PizzaIngredientFactory allows us to handle groups of different ingredient objects. As you can imagine Austria will use different ingredients than lets say Russia or America for their cheese pizzas due to different local availability of those ingredients, or regional preferences of the population. Even though our pizza stores are using the same brand name, Austrian stores might have to use thin crust dough, gouda cheese and frozen fish, while American stores can use thick crust dough, mozzarella cheese and fresh fish.

So keep in mind to use the abstract factory whenever you have families of products that you need to create and you want to make sure that your clients create products that belong together. Use factory methods to decouple client code form concrete classes you need to instantiate, or if you don't know ahead of time which concrete classes you are going to need.