First Steps with RestLet 1.1RC2 in JDeveloper 11g – restful services 101

1

WebServices are hot. Some more so than others. SOAP based WebServices are frequently seen as not very lean and agile. Robust – perhaps. Widely supported – no doubt about it. Key element of almost any SOA infrastructure – sure. Easy, lightweight to deploy or to program a client against – no, not really. Inituitive? Bookmarkable? Addressable? – none of those. Restful web-services are the easy to use, lightweight, navigation oriented complement to the more heavy weight WS* SOAP based web services. REST is the natural extension of HTTP – leveraging a lot of its potential in a very direct way. REST services focus on Resources – that are searched & retrieved, created, updated and deleted. Resources can refer to each other – through hyperlinks that equal new REST service calls. The representation of Resources – the format of the response received or sent by a client has to be agreed upon; it usually is XHTML, XML or plain text.

Under JSR-311, a formal specification for REST is being developed, with project Jersey – nearing its completion – the reference implementation. An even more mature Java project for RESTful services is RestLet – a fairly easy to use library that allows for easy publication of Restful services. Its main job is interpreting the URIs in requests sent to the server/service and routing them to the appropriate resource handler and more particularly the right method depending on the nature – GET, POST/PUT, DELETE – of the HTTP request.

In this article I will demonstrate a very first introduction to the use of RestLet with JDeveloper 11g.....
Note: the example shown here is based on the tutorial published on the RestLet’s website.

Steps:

1) Open JDeveloper 11g. Create a new application, create a new project

2) Create a new JSP – accept all defaults (for example the name untitled1.jsp); the jsp is just a convenience to get our web.xml configured and to run/deploy the application on the embedded application server

3) download sources.zip and extract the three jar-files from the WAR file (com.noelios.restlet.ext.servlet_2.5.jar, com.noelios.restlet.jar, org.restlet.jar).Copy the jar files to a new directory lib under WEB-INF in the project. Add these three jars to the project.

4) create class RestfulApplication in package nl.amis.rest.controller. The class extends org.restlet.Application. This class will set up the various resources and the URLs that route to them. Well, for starters it will set up just a single resources (things) and one url (/things) that maps to this resource. The class also initializes a list of Thing objects, the pretty pointless resource that our REST service will expose.

package nl.amis.rest.controller;<br /><br />import java.util.ArrayList;<br />import java.util.Collection;<br /><br />import nl.amis.rest.resources.Thing;<br />import nl.amis.rest.resources.ThingsResource;<br /><br />import org.restlet.Application;<br />import org.restlet.Restlet;<br />import org.restlet.Router;<br /><br /><br />public class RestfulApplication extends Application {<br />    public RestfulApplication() {<br />        things.add(new Thing(&quot;FirstThing&quot;, &quot;Wildlife in South America&quot;,<br />                             &quot;American President&quot;, 2008, 42));<br />        things.add(new Thing(&quot;OneMoreThing&quot;, &quot;Officer Orange&quot;,<br />                             &quot;Sixteen Degrees&quot;, 8, 305));<br />    }<br /><br />    private Collection&lt;Thing&gt; things = new ArrayList();<br /><br />    /**<br />     * Creates a root Restlet that will receive all incoming calls.<br />     */<br />    @Override<br />    public synchronized Restlet createRoot() {<br />        // Create a router Restlet that defines routes.<br />        Router router = new Router(getContext());<br /><br />        // Defines a route for the resource &quot;list of things&quot;<br />        router.attach(&quot;/things&quot;, ThingsResource.class);<br /><br />        return router;<br />    }<br /><br />    public void setThings(Collection&lt;Thing&gt; things) {<br />        this.things = things;<br />    }<br /><br />    public Collection&lt;Thing&gt; getThings() {<br />        return things;<br />    }<br />}<br />&nbsp;

The Thing class referred to here is defined as follows:

package nl.amis.rest.resources;<br /><br />public class Thing {<br />    <br />    private String name;<br />    private String someOtherProperty;<br />    private String andThisToo;<br />    private int    importantValue;<br />    private int    thisValueAsWell;<br />    <br />    public Thing() {<br />    }<br />    public Thing(String name, String someOtherProperty, String andThisToo, int importantValue, int thisValueAsWell) {<br />        this.name = name;<br />        this.someOtherProperty = someOtherProperty;<br />        this.importantValue = importantValue;<br />        this.andThisToo = andThisToo;<br />        this.thisValueAsWell = thisValueAsWell;<br />    }<br /><br />    public void setName(String name) {<br />        this.name = name;<br />    }<br />... and other accessor methods<br />}<br />&nbsp;

The more interesting class ThingsResource is created like this:

package nl.amis.rest.resources;<br /><br />import java.io.IOException;<br /><br />import java.util.Collection;<br /><br />import nl.amis.rest.controller.RestfulApplication;<br /><br />import org.restlet.Context;<br />import org.restlet.data.MediaType;<br />import org.restlet.data.Request;<br />import org.restlet.data.Response;<br />import org.restlet.resource.DomRepresentation;<br />import org.restlet.resource.Representation;<br />import org.restlet.resource.Resource;<br />import org.restlet.resource.ResourceException;<br />import org.restlet.resource.Variant;<br /><br />import org.w3c.dom.Document;<br />import org.w3c.dom.Element;<br /><br /><br />public class ThingsResource extends Resource {<br /><br />    Collection&lt;Thing&gt; things;<br /><br />    public ThingsResource(Context context, Request request,<br />                          Response response) {<br />        super(context, request, response);<br />        // Declare the kind of representations supported by this resource.<br />        getVariants().add(new Variant(MediaType.TEXT_XML));<br />        things = getThings();<br />    }<br /><br />    /**<br />     * Returns a listing of all registered items.<br />     */<br />    @Override<br />    public Representation represent(Variant variant) throws ResourceException {<br />        // Generate the right representation according to its media type.<br />        if (MediaType.TEXT_XML.equals(variant.getMediaType())) {<br />            try {<br />                DomRepresentation representation =<br />                    new DomRepresentation(MediaType.TEXT_XML);<br />                // Generate a DOM document representing the list of<br />                // items.<br />                Document d = representation.getDocument();<br />                Element r = d.createElement(&quot;things&quot;);<br />                d.appendChild(r);<br />                for (Thing thing : things) {<br />                    Element eltThing = d.createElement(&quot;thing&quot;);<br /><br />                    Element eltName = d.createElement(&quot;name&quot;);<br />                    eltName.appendChild(d.createTextNode(thing.getName()));<br />                    eltThing.appendChild(eltName);<br /><br />                    Element eltDescription = d.createElement(&quot;description&quot;);<br />                    eltDescription.appendChild(d.createTextNode(thing.getSomeOtherProperty()));<br />                    eltThing.appendChild(eltDescription);<br /><br />
 Element eltAndThisToo = d.crea
teElement(&quot;andThisToo&quot;);<br />                    eltAndThisToo.appendChild(d.createTextNode(thing.getAndThisToo()));<br />                    eltThing.appendChild(eltAndThisToo);<br /><br />                    Element eltImportantValue =<br />                        d.createElement(&quot;importantValue&quot;);<br />                    eltImportantValue.appendChild(d.createTextNode(Integer.toString(thing.getImportantValue())));<br />                    eltThing.appendChild(eltImportantValue);<br /><br />                    r.appendChild(eltThing);<br />                }<br />                d.normalizeDocument();<br /><br />                // Returns the XML representation of this document.<br />                return representation;<br />            } catch (IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br /><br />        return null;<br />    }<br /><br /><br />    /**<br />     * Returns the collection of things managed by this application.<br />     *<br />     * @return the collection of things managed by this application.<br />     */<br />    protected Collection&lt;Thing&gt; getThings() {<br />        return ((RestfulApplication)getApplication()).getThings();<br />    }<br /><br /><br />}<br />&nbsp;

Note that this class extends org.restlet.resource.Resource. ThingsResource specifies in its constructor that it supports only the representation in TEXT_XML. Regardless of the specific wishes of a client, that format is all that is available for this resource. It then overrides the represent() method. This method is called to deal with a GET request. Other methods would be overridden to handle POST, PUT and DELETE. The represent method creates an XML document with a <things> root element and <thing> child elements, based on the contents of the things collection retrieved from RestfulApplication. Note that the XML document (fragment) is created inside a (RestLet) DomRepresentation object. When the document is complete, this DomRepresentation object is returned as the result from this method.

5) Configure web.xml

We need to ensure that all requests that try to access one of the RESTful Resources are handled by the RestLet Servlet. In our case that means all requests period. Therefore, we create a servlet mapping with a URL pattern consisting of the wildcard /*. The Restlet Servlet is configured through the context parameter org.restlet.application that is set in the web.xml. This parameter tells the servlet about the Application class to instantiate to learn about all resources and the url’s that lead to them. In our application that Application class obviously is RestfulApplication.

Add the following fragment to the web.xml file that was created when you created the untitled.jsp.

 &lt;!-- Application class name --&gt;<br /> &lt;context-param&gt;<br />  &lt;param-name&gt;org.restlet.application&lt;/param-name&gt;<br />  &lt;param-value&gt;nl.amis.rest.controller.RestfulApplication&lt;/param-value&gt;<br /> &lt;/context-param&gt;<br /> &lt;!-- Restlet adapter --&gt;<br /> &lt;servlet&gt;<br />  &lt;servlet-name&gt;RestletServlet&lt;/servlet-name&gt;<br />  &lt;servlet-class&gt;com.noelios.restlet.ext.servlet.ServerServlet&lt;/servlet-class&gt;<br /> &lt;/servlet&gt;<br /> &lt;!-- Catch all requests --&gt;<br /> &lt;servlet-mapping&gt;<br />  &lt;servlet-name&gt;RestletServlet&lt;/servlet-name&gt;<br />  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;<br /> &lt;/servlet-mapping&gt;<br />

6) To deploy and access the RESTFul services, run untitled1.jsp

When you run the JSP, the entire Web Application in our project gets deployed on the internal/embedded/integrated/associated (I do not know the exact term for the WebLogic container used for deployment from within JDeveloper 11g) WebLogic server. The JSP does not show up, as all requests are handled by the RestLet Servlet. However, the URL to the JSP is not one the servlet can route forward to a resource handler, hence the browser displays an error.

Now when we change the URL by replacing untitled1.jsp with things. Now we see the typical REST(ful) style URL: the name of the resource that is requested is contained in the URL. In fact, apart from host, port and application context root, the url only contains the name of the resource.

From this point onwards it is fairly easy to add another resource and/or add support for other operations besides GET. Let’s do the former and leave the latter for later.

Add the Thing resource

We would like to remove some of the details from the Things list shown above and only display them when the request comes in for the specific resource in a URL format like: host:port/application/things/{thingName}.

Our intent to support this url must be configured in RestfulApplication by adding this line:

router.attach(&quot;/things/{thingName}&quot;, ThingResource.class);<br />

The ThingResource class referred to here has to take care of handling GET (and other requests eventually) for the Thing resource. The class can get hold of the requested {thingName} from the original request by checking the request parameters.

The class ThingResource:

package nl.amis.rest.resources;<br /><br />import java.io.IOException;<br /><br />import java.util.Collection;<br /><br />import nl.amis.rest.controller.RestfulApplication;<br /><br />import org.restlet.Context;<br />import org.restlet.data.MediaType;<br />import org.restlet.data.Request;<br />import org.restlet.data.Response;<br />import org.restlet.resource.DomRepresentation;<br />import org.restlet.resource.Representation;<br />import org.restlet.resource.Resource;<br />import org.restlet.resource.ResourceException;<br />import org.restlet.resource.Variant;<br /><br />import org.w3c.dom.Document;<br />import org.w3c.dom.Element;<br /><br /><br />public class ThingResource extends Resource {<br /><br />    Thing thing;<br /><br /><br />    public ThingResource(Context context, Request request, Response response) {<br />        super(context, request, response);<br />        // Declare the kind of representations supported by this resource.<br />        getVariants().add(new Variant(MediaType.TEXT_XML));<br />        // get the thingName parameter from the URL /things/{thingName}<br />        String thingName =<br />            (String)getRequest().getAttributes().get(&quot;thingName&quot;);<br /><br />        // Get the items directly from the &quot;persistence layer&quot;.<br />        thing = getTheThing(thingName);<br /><br />    }<br /><br />    /**<br />     * Returns a listing of all registered items.<br />     */<br />    @Override<br />    public Representation represent(Variant variant) throws ResourceException {<br />        // Generate the right representation according to its media type.<br />        if (MediaType.TEXT_XML.equals(variant.getMediaType())) {<br />            try {<br />                DomRepresentation representation =<br />                    new DomRepresentation(MediaType.TEXT_XML);<br />                Document d = representation.getDocument();<br />                Element eltThing = d.createElement(&quot;thing&quot;);<br />                d.appendChild(eltThing);<br /><br />                Element eltName = d.createElement(&quot;name&quot;);<br />                eltName.appendChild(d.createTextNode(thing.getName()));<br />                eltThing.appendChild(eltName);<br /><br />                Element eltDescription = d.createElement(&quot;description&quot;);<br />                eltDescription.appendChild(d.createTextNode(thing.getSomeOtherProperty()));<br />                eltThing.appendChild(eltDescription);<br /><br />                Element eltAndThisToo = d.createElement(&quot;andThisToo&quot;);<br />                eltAndThisToo.appendChild(d.createTextNode(thing.getAndThisToo()));<br />                eltThing.appendChild(eltAndThisToo);<br /><br />                Element eltImportantValue = d.createEle
men
t(&quot;importantValue&quot;);<br />                eltImportantValue.appendChild(d.createTextNode(Integer.toString(thing.getImportantValue())));<br />                eltThing.appendChild(eltImportantValue);<br /><br />                d.normalizeDocument();<br /><br />                // Returns the XML representation of this document.<br />                return representation;<br />            } catch (IOException e) {<br />                e.printStackTrace();<br />            }<br />        }<br /><br />        return null;<br />    }<br /><br /><br />    private Thing getTheThing(String thingName) {<br />        Collection&lt;Thing&gt; things =<br />            ((RestfulApplication)getApplication()).getThings();<br />        for (Thing thing : things) {<br />            if (thingName.equalsIgnoreCase(thing.getName()))<br />                return thing;<br />        }<br />        return null;<br />    }<br />}<br />&nbsp;

We can now access individual things when we know their name (/things/FirstThing):

Resources

Download the JDeveloper 11g Application for this article: MyFirstRestFulService.zip.

The RestLet project’s homesite – it has just released the RestLet 1.1RC2

Quickstart with RestLet

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

1 Comment

  1. Hi,

    Very good example on RESTlet. it is working for me. but i want to send details of the Thing from a JSP page. How i can do so? after entering values in jsp if i submit, this REST service should be invoked, which adds new details to things.

    can you tell me how i can acheive this?