Sunday 25 March 2012

Jersey, JSON and JUnit

In a previous blog entry I got a simple, HelloWorld, Jersey web service working.  Expanding on that, I created a slightly more complex web service that calculates the area of a square, rectangle or triangle.

You can download the completed project here

The slightly more complex web service incorporated the following:

  • read parameters from the path
  • return the result in JSON format
  • unit tests

@PathParam

The parameters are distinguished in the path attribute by the "{" and "}" braces. In the method signature they are referenced by the @PathParam annotation and the variable name. Example:
    
    @Path("/rectangle/{width}/{height}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String calculateRectangle(@PathParam("width") double width, @PathParam("height") double height) {
        double result = calculator.calculateRectangle(width, height);
        return formatter.formatAsJson(result);
    }

JSON

Jersey provides 3 ways of working with JSON:
  • POJO support 
  • JAXB based JSON support 
  • Low-level, JSONObject/JSONArray based JSON support
In my case I used the Low-level method as my needs were very basic and this seemed the simplest approach.

Example:
  JSONObject format = new JSONObject();
  format.put("result", value);
  return format.toString();

You will need to include the "jersey-json" dependency in your pom.xml file to use the JSON support.

Unit Testing


Unit testing was pretty easy.  Jersey provides several test frameworks to choose from.  I used the inmemory framework. 

 <dependency>            
  <groupId>com.sun.jersey.jersey-test-framework</groupId>
  <artifactId>jersey-test-framework-inmemory</artifactId>            
  <version>1.12</version>            
  <scope>test</scope>        
 </dependency>

Accessing the Web Service

Examples of accessing the 3 area calculations:

Square 
http://localhost:8080/calculate/area/square/{side}
Example: http://localhost:8080/calculate/area/square/4
Result: {"result":16}

Rectangle
http://localhost:8080/calculate/area/rectangle/{width}/{height}
Example: http://localhost:8080/calculate/area/rectangle/4/2
Result: {"result":8}

Triangle
http://localhost:8080/calculate/area/triangle/{base}/{height}
Example: http://localhost:8080/calculate/area/triangle/4/3
Result: {"result":6}

Well that's it for now.  Next step is to figure out how to write an iPhone app to access this web service.

References

http://jersey.java.net/nonav/documentation/latest/index.html - Jersey user's guide.

No comments:

Post a Comment