Using Jersey with Orion

This article will show how to get started with RESTful Web-Services on the Orion Application Server, using the reference implementation of JAX-RS (Java API for RESTful Web-Services, JSR 311) which is the open source project Jersey of the Glassfish project.

1 Introduction

    1.1 REST

      The concept of REST (REpresentational State Transfer) was created by Roy Fielding around year 2000 in his doctoral dissertion , chapter 5 . It is basically an architecture for communication between machines.

      The idea behind REST is to expose Resources with unique identites in the form of URI:s, just like the World Wide Web. These resources are then accessed by Consumers through standard HTTP methods (such as GET, POST, PUT, OPTIONS, etc), and the Resource then respond with a suitable representation of its content based upon negotiation of mime-types based upon the closest match between what the Consumer says it can handle (through the Accepts header) and what the Resource can provide. The basic principles of a RESTful system are:

        an applications functions and state are abstracted into a Resource

        every Resource has a unique address using a universal syntax that can be used in hypermedia links

        every Resource share a uniform interface through which state can be transfered between the Consumer and the Resource

        the interface is based upon standard HTTP methods (such as POST, GET, OPTIONS, etc) for the Consumer to use

        the interface has a set of Representations (based on mime-types) for the Resource to represented as

      Compared to SOAP, REST is much lighter, said to be faster to implement and is based on far less standards.

    1.2 JAX-RS

      JAX-RS is a Java API for RESTful Web Services. The specification was developed through JSR 311. The JSR homepage is at http://jcp.org/en/jsr/detail?id=311, from where the specification and API docs can be downloaded.

    1.3 Jersey

2 Setting up the environment

    2.1 Download Orion

      Before we can get started with our firs steps in JSP programming we need to install the Server. If you have already installed Orion, then please skip to the next section.

      1. Download the latest version of the Orion Application Server from http://www.orionserver.com/download.jsp

      2. Unzip the orion zip file. Unzipping the file creates a directory-hierarchy under an orion/ directory

      3. copy the tools.jar file from your Java (J2SE 1.2 or later) installation to the orion/ directory.

      Now orion is installed and ready to use with the default configuration. This means Orion will install itself using port 80 for the web server part.

      If you require more information about setting up the Orion Application Server, please read this article.

      If you look in the installation directory you will notice a directory named default-web-app. This directory holds the default Web-module that is shipped with Orion. When you access the server at http://localhost/ the response is generated by the file named index.html from the default-web-app directory. The examples directory holds a number of example JSP pages and Servlets that you can play around with later and use as samples for further experimenting with dynamic content. We will use the default-web-app directory as home for the REST resources that we will develop throughout this article.

    2.2 Download Jersey

    2.3 Enable Development-mode

      Edit the file [path]/orion/config/global-web-application.xml so that the <orion-web-app> tag looks something like in listing 1 below.


      <orion-web-app
      jsp-cache-directory="./persistence"
      servlet-webdir="/servlet"
      development="true"

      Listing 1: Enable development-mode

      In the listing above, we set the attribute development to "true" which will tell the Container to run the Web-module in development-mode, which amongst other things allow sfor automatic compilation of Servlets and other classes these might be dependent upon. We will utilize this feature to let the Container compile our REST Resources for us, as will be explained later.

    2.4 Enable Jerseys ServletAdaptor

      We will be using Jerseys ServletAdaptor to hook Jersey into Orion.

      In your favourite editor, open the file [path]/orion/default-web-app/WEB-INF/web.xml and add the following lines after the <web-app> tag:


      <servlet>
      <servlet-name>Jersey Test</servlet-name>
      <servlet-class>com.sun.jersey.impl.container.servlet.ServletAdaptor</servlet-class>
      <load-on-startup>1</load-on-startup>
      </servlet>

      <servlet-mapping>
      <servlet-name>Jersey Test</servlet-name>
      <url-pattern>/*</url-pattern>
      </servlet-mapping>

      Listing 2: Enable Jersey

      The <servlet> tag will configure a Servlet by the name Jersey Test, and the <servlet-mapping> tag will tell the Container that this Servlet will handle any requests to this Web-module.

    2.5 Verify your setup

      From the Orion root directory, issue the command java -jar orion.jar. Which should result in console output similar to the sample below:


      C:\Program\orion>java -jar orion.jar
      2008-okt-15 15:55:06 com.sun.jersey.api.core.ClasspathResourceConfig init
      INFO: Scanning for root resource and provider classes in the paths:
      C:\Program\orion\rest-web-app\WEB-INF\lib
      C:\Program\orion\rest-web-app\WEB-INF\classes
      2008-okt-15 15:55:07 com.sun.jersey.impl.application.WebApplicationImpl processRootResources
      ALLVARLIG: The ResourceConfig instance does not contain any root resource classes.
      Orion/2.0.8 initialized
      Listing 3: Sample windows XP console output

      Do not let the warnings alarm you. That is just Jersey tellling us that there are currently no Root Resources available. Something we will attend to shortly.

3 Writing your first Resource

    In the [path]/orion/default-web-app/WEB-INF/classes directory, create a file named HelloWorldResource.java and open it up for editing with your favourite editor.

    First, lets add the neccessary imports:


    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.PathParam;
    Listing 4: Imports

    Now, continue with the following:


    @Path("/helloworld")
    public class HelloWorldResource {
    Listing 5: Class-definition

    Root Resources are POJOs (Plain Old Java Objects) with atleast one @path annotation and/or a resource method designator annotation such as @GET or @PUT, All of these annotations mentioned are JAX-RS annotations and you can find out more about JAX-RS here.

    The @Path annotation above is used to specify a relative URI path where the Resource will be hosted. In the listing above, we specify that this Resource will be hosted at "/helloworld" which will resolve to the URL "http://localhost/helloworld". As we will soon see, the @Path annotation can be used on class and/or method level.

    Continue with the following:


    @GET
    @Produces("text/plain")
    public String sayHello() {
    return "Hello world!";
    }
    Listing 6: A Representation

    The @GET annotation above is a resource method designator defined by JAX-RS and is used to define that a certain method of a Resource should be used to handle requests to this Resource with the corresponding HTTP Method.

    The @Produces annotation above is used to describe that this method can be used to retreive a certain Representation (mime-type) of a Resource. If the annotation is used on method-level, that will override any usage on class-level.

    More than one mimetype can be given by using a comma-sign as separator, like this: @Produces("text/plain","text/xml","text/html"). The mimetype that the Consumer defines as having the highest acceptance-rating will have precedence. In case of equality, the leftmost mimetype will be used.

    Lets try and not say anything witty about the method itself as all it does is returning the text "Hello world!" to the consumer.. Instead, lets hurry onwards to the next method that will be just a tad more interesting. Continue with the following:


    @GET
    @Path("/{name}")
    @Produces("text/plain")
    public String sayHello(@PathParam("name") String name) {
    return "Hello "+name+"!\n";
    }
    }
    Listing 8: A Sub-Resource taking a variable

    Again, the @GET annotation above is a resource method designator used to define that this method should be used to handle request with the http method GET, nothing special there.

    Now we got a @Path annotation above that, on a method level, means that this method should be treated as a sub-resource and that its URI should be added to the URI of the class @Path annotation which, in this case, would resolve to a URL of "http://localhost/helloworld/someName" where someName is a variable embeded in the URI (variables are defined by curly brackets in the value of the @Path annotation).

    By using method-level @Path annotations it is possible to group resources together and potentially reuse them.

    By now, your HelloWorldResource.java should look like this. Store the file in the [path]/orion/default-web-app/WEB-INF/classes directory as HelloWorldResource.java.

4 Compiling the Resource

    As we have enabled development-mode for our web-module, lets take advantage of that and let Orion compile our Resource for us.

    Fire up your browser and open the URL http://localhost/servlet/HelloWorldResource. Do not let the empty response page throw you off.. All is well.

    Look in the [path]/orion/default-web-app/WEB-INF/classes directory. You should see that Orion has generated HelloWorldResource.class for us. Why? Well, we tricked Orion into believing that we were trying to invoke an uncompiled Servlet. As we are running our web-module in development-mode, the first thing Orion does is to compile the sourcefile into a class and then to try and invoke it, which it won't as it doesn't appear to be a Servlet after all.

    It is possible that Jersey won't notice the newly added Resource for quite some time. You might want to quickly restart Orion in order for Jersey to locate it.

5 Testing the Root Resource

    Fire up your browser and open the URL http://localhost/helloworld. The respone should be a text/plain page containing the message "Hello world!"

    Congratulations! Your Root Resource is working as expected! If you were a machine in dire need of communicating with other machines, I bet you would be humming happily right now!

6 Testing the Sub-Resource

    Fire up your browser and open the URL http://localhost/helloworld/John. The respone should be a text/plain page containing the message "Hello John!"

    Congratulations! Your Sub-Resource is working as expected! You just utilized a Sub-Resource and even provided it with a variable!

7 Summary

    Throughout this article you have learned how to configure Orion to use Jersey in order to be able to develop and host RESTful applications. You have also tried out writing both Root Resources and Sub-Resources as well as used Orions development-mode to automatically compile these classes for you. You then confirmed that everything worked by acting as a Consumer of your newly created Resources.

    If you are new to REST, you might want to learn more through some of the REST tutorials out there, or you could try another of the Orion tutorials and introductions available here.

Copyright © 2008 IronFlare AB