Monday, February 16, 2015

How to use ExecutorService to create and maintain a thread pool in java

The ExecutorService interface and its implementations which are found in java.util.concurrent package are very useful when you need to maintain a thread pool in your application.

What is a thread pool and why it is used? 
Well, first of all think that a thread pool as a collection of threads. Assume that you have a runnable class and assume that you need 'n' number of threads of this class run in parallel. If one thread finished its task and exit you may need to start another thread to make sure that 'n' number of threads are running in parallel.
The ExecutorService can do this and more other stuff for you.
You can add any number of threads in to the ExecutorService. You can tell the ExecutorService how many threads that you want to run in parallel. The ExecutorService is responsible of keeping the given number of threads running in parallel. If one thread went down by finishing its task, the ExecutorService starts another thread to guarantee that given number of threads are running in parallel. ExecutorService does this until all the threads in its pool are executed or until we signal it to stop.
Below example will show you how to create a thread pool using ExecutorService.

As I mentioned earlier you need to have a runnable class which acts as a thread. My runnable class is as below.

import java.text.SimpleDateFormat;
import java.util.Date;

public class MyThread implements Runnable {
  @Override
  public void run() {
    System.out.println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted.......");
    }
  }
}

This is my code which creates and executes the thread pool.

 java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PoolTest {
  public static void main(String[] args) throws InterruptedException {
    int poolSize = 5;
    ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < 20; i++) {
      MyThread thread = new MyThread();
      threadPool.execute(thread);
    }
    System.out.println("All threads are added to the pool....");
    threadPool.shutdown();
    System.out.println("All Executed....");
  }
}

Run and inspect the output of the above method and you will see that five threads have been executed at the same time.
I'll explain the above code line by line.
ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
This line creates the thread pool. The integer value passed to this method is the number of threads run in parallel.

threadPool.execute(thread);
The execute() method is used to add threads in to the thread pool. As soon as the execute() method is called first time, the ExecutorService starts execution of threads.

threadPool.shutdown();
After adding all the elements in to the thread pool, we calls this method to tell the ExecutorService, that we are not goint to add more threads in to the pool and it may gracefully shuts down after all the threads provided are executed. It should be noted that, this line does not shuts the thread pool down immediately. Instead it permits the thread pool to shuts down after it completely executed all the threads provided. Another thing to keep in mind is that you can't add more threads in to this thread pool after the shutdown() method is called. It will throw a runtime exception.

If you want to tell the ExecutorService to abort all the tasks and shuts down immediately, you can call threadPool.shutdownNow().

If you inspect the output of the above code carefully, you will see that the line "All Executed...." has been printed before the execution of all threads are finished. What is the reason for that. Yes, as you have already understood the thread pool does its job in background and the main thread which contains the line System.out.println("All Executed...."); gets executed in parallel.

What we can do if we need to print this line after all the threads were executed?
The easiest way is to call awaitTermination() after the shutdown() method. This method blocks the main thread until all tasks have completed execution after a shutdown request(or the given timeout occurs, or the current thread is interrupted, whichever happens first).
After adding the awaitTermination() method, the last lines of the above code will be as below.

System.out.println("All threads are added to the pool....");
threadPool.shutdown();
threadPool.awaitTermination(1, TimeUnit.MINUTES);
System.out.println("All Executed....");

Now run the code and you will see that the line "All Executed...." is printed after all the threads are executed.

The other way is to use the ExecutorService.isTerminated() together with Thread.sleep() to check and wait until ExecutorService has been shut down. For an example you can replace the line threadPool.awaitTermination(1, TimeUnit.MINUTES); with below lines.

while (!threadPool.isTerminated()) {
  try {
Thread.sleep(500);
  } catch (InterruptedException e) {
e.printStackTrace();
  }
}

Working with multiple threads is some what tricky and you should act carefully. This tutorial demonstrated the basic usage of ExecutorService to handle thread pools. I think that would help you to design your next multi threaded program in more efficient way.

How to use dynamic parameters in strings in java

In programming it is common to keep commonly used strings in a properties file or as constants and use them in multiple places in your code.

For an example below message can be put in a properties file to be used in different places.
message=The user is not authorized for this operation.

Then you can use this in various places.
But what happens if you need to include the "username" of the user in to this message?
For an example if the username is "john", the message should be

"The user john is not authorized for this operation."

If the username is "tom", the message should be

"The user tom is not authorized for this operation."

In this kind of situations you can use a parametrized messages in your property file as below.
message = The user {0} is not authorized for this operation.

In the places where you use this message you can use java.text.MessageFormat class to replace the parameter with the proper value as below.

String message = properties.getProperty("message");
String formattedMessage = MessageFormat.format(message, "john");

This will print
The user john is not authorized for this operation.

Similarly if you want you can have multiple parameters in the string.
String message = "The user {0} is not authorized for {1} operation.";
String formattedMessage = MessageFormat.format(message, "john", "billing");
System.out.println(formattedMessage);

This will print
The user john is not authorized for billing operation.

Friday, February 13, 2015

How to get/calculate the remaining time for session time out

In Servlet API there is no straight forward method to get the remaining active time of the session. But you can use below two methods provided in HttpSession to calculate this time.

HttpSession.getLastAccessTime() - This method returns the time(in milliseconds) that the client associated with this session sent the last request to the server.
HttpSession.getMaxInactiveInterval() - This is the configured session time out period.

In your servlet you can calculate remaining time as below.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
long now = new Date().getTime();
long lastAccessed = session.getLastAccessedTime();
long timeoutPeriod = session.getMaxInactiveInterval();
long remainingTime = ((timeoutPeriod * 1000) - (now - lastAccessed))/1000;
System.out.println("Remaining time is " + remainingTime + " seconds");
}

Note that if you are using JSF, you can get the associated session as below.
FacesContext ctx = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) ctx.getExternalContext().getSession(false);

Friday, December 19, 2014

Adapter Design Pattern - Simple tutorial with an example in Java

Adapter Design Pattern belongs to the Structural Design Patterns group. You can use this pattern when you need to plug your existing code base to another code base which is not fully compatible with your existing code base. In such cases this pattern guarants the minimal change to your existing code.
Below I am showing you a very simple example which illustrates the use of this pattern. But note that in real world there are more complex situations where this pattern is used.

Assume that you have StudentData class which contains a list of ages of students.
public clas StudentData {
  private List<integer> ages;
}

Now think that for some reason you need to use a third party library which do some complex calculation using ages of students. This is that third party class.
public class ComplexCalculator {
  public int doComplexCalculation(String csv) {
    int result = 0;
    String[] ages = csv.split(",");
    //do complex calculation using ages
    //result = .....
    return result;
  }
}

Look, unfortunately the input type accepted by above method is csv. If you need to use this method you need to convert the list of ages in to a csv string. What do you do now? Change your StudentData class to include the csv generation logic. No. There is a cleaner way. Just create an adapter class(ComplexCalculatorAdapter) and let it do that dirty mediation job for you.
public class ComplexCalculatorAdapter {
  public int callComplexCalculator(List<integer> ages) {

    String csv = null;
    //Logic to create csv string from list
    //String csv = .......
    return new ComplexCalculator().doComplexCalculation(csv);
  }
}
Now in your StudentData class you can call this adapter method as below.
int complexResult = new ComplexCalculatorAdapter().callComplexCalculator(ages);

That is all.
Note that by using Adapter Design Pattern you were able to accomplish the above task with minimal modifications to the existing code.

Thursday, November 27, 2014

Bridge Design Pattern - Simple tutorial with an example in Java

Bridge Design Pattern belongs to the Structural Design Patterns category.
As GOF says what you do by using this pattern is "Decouple an abstraction from its implementation so that the two can vary independently."

If I explain it further, in Bridge Design Pattern you decouple a functionality from a class hierarchy and create another interface and a class hierarchy which support that functionality and then create a bridge between these two hierarchies by creating a "has-a" relationship between two interfaces.

You will not understand this at once. But after carefully reading this lesson you will get a good understanding.

As usual Ill take our Vehicle interface to explain this pattern.
Assume that you have an interface called Vehicle which contains createVehicle() method.

public interface Vehicle {
    public void createVehicle();
}

Think that you need to have four types of vehicles. Those are Black Car, White Car, Back Motorbike and White Motorbike. So you will simply create below four classes which implements Vehicle interface.

public class BlackCar implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class WhiteCar implements Vehicle {
@Override
public void createVehicle() {
  installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class BlackMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in black...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

public class WhiteMotorbike implements Vehicle {
@Override
public void createVehicle() {
installCarParts();
  paintInBlack();
}

private void paintInBlack() {
  System.out.println("Painting in white...");
}
private void installCarParts() {
  System.out.println("Installing motorbike parts...");
}
}

You see that this is not the best design. For an example your paintInBlack() and paintInWhite() methods are duplicated. This design becomes more complex and less maintainable when the number of implementation classes are higher.
In this kind of situations Bridge Pattern comes to your help.
In Bridge Pattern what you do is create another interface(Painter) which does the painting job and then create another hierarchy of classes which implements this interface. Then you keep a reference to the Painter interface in Vehicle interface.
Now you have two class hierarchies which implement separate two interfaces. Having a reference to Painter interface in Vehicle interface is the bridge between these two hierarchies.
This is the Bridge Design Pattern.
With this pattern, your interfaces and implementation classes will be as below.

public abstract class Vehicle {
  protected Paint painter;
  public abstract void createVehicle();
}

public class Car extends Vehicle {
public Car(Paint painter) {
  this.painter = painter;
}

@Override
public void createVehicle() {
installCarParts();
  painter.paint();
}

private void installCarParts() {
  System.out.println("Installing car parts...");
}
}

public class Motorbike extends Vehicle {
public Motorbike(Paint painter) {
this.painter = painter;
}

@Override
public void createVehicle() {
  installMotorbikeParts();
  painter.paint();
}

private void installMotorbikeParts() {
  System.out.println("Installing motorbike parts...");
}
}

public interface Paint {
  public void paint();
}

public class BlackPaint implements Paint {
@Override
public void paint() {
System.out.println("Painting in black...");
}
}

public class WhitePaint implements Paint {
@Override
public void paint() {
  System.out.println("Painting in white...");
}
}

In your client class now you can create various types of vehicles as below.
public class Test {
    public static void main(String[] args) {
Car whiteCar = new Car(new WhitePaint());
Car blackCar = new Car(new BlackPaint());
Motorbike whiteBike = new Motorbike(new WhitePaint());
Motorbike blackBike = new Motorbike(new WhitePaint());
    }
}

Saturday, November 22, 2014

Abstract Factory - Simple tutorial with an example in Java

    In Factory Method pattern we used a method called factory to create objects.

The concept of Abstract Factory Pattern is having a Factory Class which creates other factories according to the information given. If you remember the Factory Method tutorial you had a Vehicle interface and multiple classes which implement it. You had a factory called VehicleFactory which constructs the correct type of vehicle instance(car bus or van).
This pattern also belongs to the creational patterns group.

The difference in Abstract Factory Pattern is instead of having one VehicleFactory you have multiple factories such as WaterVehicleFactory and LandVehicleFactory ana there is another class which creates the correct factory for you.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below four classes implement above interface.

public class Bus implements Vehicle {
}
public class Car implements Vehicle {
}
public class Ship implements Vehicle {
}
public class Boat implements Vehicle {
}

We can categorize above four classes in to two groups, Land Vehicles and Sea Vehicles. So similarly we can have two factories to create them such as LandVehicleFactory and SeaVehicleFactory.
First we create an super abstract factory class or an interface (AbstractVehicleFactory) and extend LandVehicleFactory and SeaVehicleFactory classes from it as below.


public interface AbstractVehicleFactory {
public Vehicle getVehicle(String size);
}

public class LandVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if ("large".equals(size)) {
return new Bus();
} else {
return new Car();
}
}
}

public class SeaVehicleFactory implements AbstractVehicleFactory {
public Vehicle getVehicle(String size) {
if("large".equals(size)) {
return new Ship();
} else {
return new Boat();
}
}
}

Finally you need a separate class which is responsible to create and return the correct factory according to the requirement.


public class FactoryCreator {
public static AbstractVehicleFactory getFactory(String terrainType) {
if("sea".equals(terrainType)) {
return new SeaVehicleFactory();
} else if("land".equals(terrainType)) {
return new LandVehicleFactory();
} else {
return null;
}
}
}

I think now you understand this pattern well. You can use below class to test it.


public class Test {
public static void main(String[] args) {
AbstractVehicleFactory factory = FactoryCreator.getFactory("sea");
Vehicle ship = factory.getVehicle("large");
System.out.println(ship.getClass().getSimpleName());
}
}

Thursday, November 20, 2014

Factory Method - Simple tutorial with an example in Java

Factory Method design pattern belongs to the creational design pattern group. Factory method is responsible of creating the correct object according to the information given.

For an example assume that you have an interface called Vehicle and multiple classes which implement it such as Bus, Car and Van. Then when you need to create an instance from one of above classes according to the passenger count, the factory method is responsible to construct and return the correct type of object.

See below example.

This is the Vehicle interface.
public interface Vehicle {
}

Below three classes implement above interface.
public class Bus implements Vehicle {
}

public class Car implements Vehicle {
}

public class Van implements Vehicle {
}

I put my factory method in a separate class so that other classes can use this method easily. This is my class which contains my factory method. When I call the getVehicle() method it returns me the correct type of object according to the passenger count I pass.

public class VehicleFactory {
public static Vehicle getVehicle(int passengerCount) {
if(passengerCount <= 4) {
return new Car();
} else if(passengerCount <= 18) {
return new Van();
} else {
return new Bus();
}
}
}

You can test this method as below.
public class Test {
public static void main(String[] args) {
Vehicle car = VehicleFactory.getVehicle(3);
Vehicle bus = VehicleFactory.getVehicle(25);

System.out.println(car.getClass().getSimpleName());
System.out.println(bus.getClass().getSimpleName());
}
}

Singleton Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The concept of this pattern is can be described as below.

"This pattern does not let creating more than one instance of a certain object."

It means you can use this pattern when you want to restrict other classes creating more than one instance of a certain class.
How can we do that.
Think that the name of your class which is needed to be singleton is MySingleton. You can make the class singleton as below.

public class MySingleton {
private static MySingleton mySingleton;

//Make the constructor private so that
//any body cant use this to create instances
private MySingleton() {
}

//Calling this method is the only way of creating an
//instance of this class. If there is no previously created
//instance this method creates an instance and returns
//that. Otherwise returns the previously created instance.
public static MySingleton getInstance() {
if(mySingleton == null) {
mySingleton = new MySingleton();
}
return mySingleton;
}
}

You can test this class as below.

public class Test {
public static void main(String[] args) {
MySingleton ms1 = MySingleton.getInstance();
MySingleton ms2 = MySingleton.getInstance();

System.out.println(ms1 == ms2);//returns true because two instance are the same
}
}

Wednesday, November 19, 2014

Prototype Pattern - Simple tutorial with an example in Java

This pattern belongs to the category of creational design patterns. The core of this pattern can be described simply as below.

"If you want to construct multiple instances of an expensive object, just create one object and clone it multiple times."

✔  Create one instance of expensive object
✔  Clone it when you need another instance of that type
✔  Modify the properties of new(cloned) instance as required.

☞  Note that this pattern suits only if those instances should have nearly similar properties.
☞  It is not a must to use Object.clone() method to duplicate the object. You can write your own copy method to do this. To keep this lesson short in my Car class I implements the Cloneable interface and use Object.clone() method in CarCreator class.

Assume that you have a class called Car which can be used to build various types of cars. When using Prototype Pattern what you do is create a car initially and duplicate it when you need more cars.
See this example. This is the Car class.

public class Car implements Cloneable {
int doorCount = 0;

public Car() {
  // complex construction logic here
}

public int getDoorCount() {
return doorCount;
}

public void setDoorCount(int doorCount) {
this.doorCount = doorCount;
}

protected Object clone() {
try {
return super.clone();
} catch (Exception e) {
return null;
}
}

//..more lines here...
}

Ok. Now you should have another class(CarCreator) which is used when you need to create a new Car instance. At the very first time you call this class it goes through the expensive logic and creates an instance of Car object. As well this class keeps that instance for later use. When you request a new car instance at later time it clones the previously saved object and returns.

This is your CarCreator class.

public class CarCreator {
  private Car car;
  
  public Car createCar() {
    if(car == null) {
      car = new Car();//This construction is expensive
      return car;
    } else {
      //since we already have a car in hand we return a clone of that
      return (Car) car.clone();
    }
  }
}

Your client class to check above functionality would be as below.

public class Test implements Cloneable {
  CarCreator carCreator = new CarCreator();
  
  public static void main(String[] args) {
    Test test = new Test();
    //create a luxury car
    Car luxuryCar = test.createVehicle(4);
    //create a sports car
    Car sportsCar = test.createVehicle(2);
    
    System.out.println(luxuryCar.getDoorCount());
    System.out.println(sportsCar.getDoorCount());
  }
  
  private Car createVehicle(int doorCount) {
    Car vehicle = carCreator.createCar();
    vehicle.setDoorCount(doorCount);
    return vehicle;
  }
}

Builder Pattern - Simple tutorial with an example in Java

Builder design pattern belongs to the creational design pattern group. In Builder Pattern you arrange all the steps used to create an object in one separate class(Builder class).
Assume that you have a class or an interfaces called Vehicle. You can create various types of vehicles which are instances of this class(or interface). For an example an instance can be a car or a motorcycle.
Assume that the below class is your Vehicle class which contains complex methods.(Since I need to keep this tutorial short, I am not using an interface here. But note that the best design is making the vehicle class an interface and implementing the Car and Motorcycle classes using that.)

public class Vehicle {
  String name;
  public void addWheels(int count){}
  public void addController(){}
  public void addFuelTank(){}
  public void setName(String name){this.name = name;}
  public String getName(){return this.name;}
}

Building a car or a motorcycle is a complex and multi stepped process. In such cases you can use a VehicleBuilder to make this process organized. In a VehicleBuilder instance there is an instance of Vehicle class and getVehicle() method returns that after constructed.

This is your VehicleBuilder interface.

public interface VehicleBuilder {
  public void setWheels();
  public void setController();
  public void setFuelTank();
  public void setName();
  public Vehicle getVehicle();
}

You can have multiple implementations of this interface. For an example CarBuilder and MotorcycleBuilder.

public class CarBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 4 wheels (complex logic)
    vehicle.addWheels(4);
  }
  public void setController() {
    //Fix a steering wheel complex logic
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing car fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //seting name (complex logic)
    vehicle.setName("car");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

public class MotorcycleBuilder implements VehicleBuilder {
  Vehicle vehicle = new Vehicle();
  public void setWheels() {
    //Fixing 2 wheels (complex logic)
    vehicle.addWheels(2);
  }
  public void setController() {
    //Fixing a handle (complex logic)
    vehicle.addController();
  }
  public void setFuelTank() {
    //Fixing motorcycle fuel tank (complex logic)
    vehicle.addFuelTank();
  }
  public void setName() {
    //setting name (complex logic)
    vehicle.setName("Motorcycle");
  }
  public Vehicle getVehicle() {
    return vehicle;
  }
}

Now in your class you can use this builders to create cars or motorcycles as below.

public class Test {
  public static void main(String[] args) {
//Building a Car
    VehicleBuilder carBuilder = new CarBuilder();
    carBuilder.setName();
    carBuilder.setWheels();
    carBuilder.setController();
    carBuilder.setFuelTank();
    Vehicle car = carBuilder.getVehicle();
    System.out.println(car.getName());
    

//Building a Motorcycle
    VehicleBuilder motorcycleBuilder = new MotorcycleBuilder();
    motorcycleBuilder.setName();
    motorcycleBuilder.setWheels();
    motorcycleBuilder.setController();
    motorcycleBuilder.setFuelTank();
    Vehicle bike = motorcycleBuilder.getVehicle();
    System.out.println(bike.getName());
  }
}

Sunday, November 16, 2014

Simple Jersey client to consume a RESTful web service

In this quick tutorial you will learn to write a Jersey client to consume a RESTful web service.
Below is the web service for which I am going to write a client. You have to start this service first. (You can get a quick knowledge about Jersey RESTful web services by looking at this tutorial)

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloService {
@GET
@Path("/{company}")
@Produces("text/plain")
public Response getWelcomeMessage(@PathParam("company") String company, 
                                   @QueryParam("username") String username) {
String retVal = "Welcome to " + company + " " + username + ".!";
return Response.status(200).entity(retVal).build();
}
}

This is the client which can consume above service.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class MyClient {
  public static void main(String[] args) {
    try {
      Client client = Client.create();
      WebResource webResource = 
          client.resource("http://localhost:8090/MifeRest/hello");
      ClientResponse response = webResource.path("ABC org") //setting path param
.queryParam("username", "John") //setting query param
.accept("text/plain") //setting accept MIME type
.get(ClientResponse.class); //send GET request
      if (response.getStatus() != 200) {
        System.out.println("Error : " + response.getStatus());
      }

      String responseText = response.getEntity(String.class);
      System.out.println(responseText);  //response body
      System.out.println(response.getHeaders().get("content-type"));  //header value
      } catch (Exception e) {
e.printStackTrace();
      }
  }
}

Saturday, November 8, 2014

Quick and Simple RESTful web service example with Jersey

What is Jersey?
Jersey is a implementation of JAX-RS which is a standard for RESTful Web Services.

Why Jersey is needed when creating RESTful web services?
Jersey is not a must when creating RESTful web services. But Jersey makes our lives easier when creating RESTful services. Below tutorial will show you how.

First create a new web project and name it as RestExample.
Download and add asm-all-x.x.x.jar and jersey-bundle-x.x.x.jar to your project.

Configure the Jersey ServletContainer in your web.xml as below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app .....>
  <servlet>
   <servlet-name>jersy-servlet</servlet-name>
   <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
   <servlet-name>jersy-servlet</servlet-name>
   <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

Note that all the requests match the above configured url pattern(/*) are sent through the Jersey ServletContainer and if any of them matches with a url pattern of a registered web service(@Path) Jersey point the request to that service.
Now you are ready to create your first RESTful web service with Jersey. Create a new java class and name it as UserManagementService. Now change your class as below and your web service is ready.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@Path("/user")
public class UserManagementService {
@GET
@Path("/profile")
@Produces("application/xml")
public Response getUserProfile() {
String retVal = "<user>" +
                  "<username>John</username>" +
                  "<email>john@example.com</email>" +
                "</user>";
return Response.status(200).entity(retVal).build();
}
}
This simple web service returns a user profile in xml format.
Enter below url in your browser.
http://localhost:8080/RestExample/user/profile

You will get below result.


Note that the annotations are the most important part which convert your plain java class in to a RESTful web service. Those are explained below.

@Path("/user") - If a request url matches this pattern Jersey redirects the request to this class.
@Path("/profile") - If a request redirected to this class matches the pattern "/profile", this method is responsible to serve the request.
@GET - Indicates that this method supports HTTP GET requests. Similarly other valid annotations are " @POST, @PUT, @DELETE and @HEAD". Note only one of these annotations can be applied for one method.
@Produces - This is the response type of this service. This is set as the Content-Type header of the http response. As you know this is used by the browsers to render the output.

Following annotations are also frequently used.

@Consumes - This can be used to specify the media types that can be consumed by the service.
@QueryParam - This is used to extract query string parameters from the request URL.
@PathParam - This is used to get data from request url.

Below is a simple web service which uses @QueryParam,  @PathParam and @HeaderParam annotations.

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class HelloService {
 @GET
 @Path("/{firstname}/{lastname}")
 @Produces("text/plain")
 public Response getWelcomeMessage(@QueryParam("company") String company,
                                                        @PathParam("firstname") String firstName, 
                                                        @PathParam("lastname") String lastName
                                   @HeaderParam("Authorization") String token) {
  System.out.println("Auth token is " + token);
 String retVal = "Welcome to " + company + " " + firstName + " " + lastName;
  return Response.status(200).entity(retVal).build();
 }
}

Enter below url in your browser and see the result.
http://localhost:8080/RestExample/hello/John/Daniel?company=ABC

The output will be as below.

Wednesday, November 5, 2014

In Javascript how to iterate over the properties of a JSON object?

When you are working with javascript and JSON you may have faced situations where you need to iterate over the properties of a JSON object.
For an example assume that you receive a JSON response for a http request. Think that you don't know the properties of the object. In such a case you may need to iterate over the properties of the JSON response to get the properties and corresponding values.
There are several ways to do this. But you can do this easily by converting the JSON object in to a javascript.

I will show that below.
Since I need a JSON object for this example I create a JSON objcet by using JSON.stringify() method. The name of my JSON object is jsonObj.

var jsonObj = JSON.stringify({name:'John', age:18});

Ok, now we have a JSON object and lets start.
In order to iterate over the properties you first need to convert the JSON object in to a javascript object as below.

var javascriptObj = JSON.parse(jsonObj);

Now you can iterate and access the properties and values as below.

for (var prop in javascriptObj) {
   alert(prop);//property
   alert(javascriptObj[prop]);//value
}