Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Web Development

SOA, Web Services, and RESTful Systems


A REST Service Framework

Although web services tend to be more complex than REST services, there are web-service tools and libraries to help you avoid duplicating code and test effort. However, there aren't many available for REST; at least not for Java developers. To remedy this, I've built a REST service framework (available electronically; see "Resource Center," page 5) that helps avoid writing duplicate code for each service I need. This Java-based framework lets me focus on the interface and functionality I need to implement instead of the skeleton code required to implement a Java Servlet, and map URL query parameters to data.

There are two main components in the REST framework:

  • The REST Server, which is the Java Servlet that maps HTTP URL queries to application code.
  • The REST Worker, which is the Java class that is dynamically invoked by the framework when a request is made, and subsequently generates a response.

The REST worker objects are what you develop to provide service functionality. Every worker must implement the RestWorker interface as in Example 2.


public interface RestWorker 
{
    public String onRequest(Map paramMap);
    public boolean cacheReference();
}

Example 2: The RestWorker interface definition.

The RestWorker interface defines the following methods:

  • onRequest is called when an HTTP request arrives for the worker object, which is determined by the object's class name.
  • cacheReference is called by the REST Server to determine if the reference to this worker object should be cached. If so, the object reference is stored and used in all subsequent HTTP requests for this object's URL key; otherwise, a new object is instantiated for each request.

The REST Server defines a common HTTP URL query parameter, request, which is used to determine which REST worker object should be called. The value of this parameter is matched to the name of the class to invoke. For instance, when this request arrives:

http://<rest_server_name>   /restserver?request=EmpBenefits

the REST Server attempts to load a class with the name EmpBenefits, which implements the RestWorker interface, and calls its onRequest method. All of the additional URL query parameters, if there are any, are passed as a java.util.Map of named-value pairs.

Listing Two shows the doPost method for the Rest Server Java Servlet, where this work is done. After the request parameter is retrieved, the entire set of URL query parameters is retrieved via the call to HTTPServletRequest.getParameterMap. The request parameter is removed from this map because it's meaningful to the REST Server only, and not the worker object. Next, a call is made to getWorker, which first attempts to locate a reference to this request's worker object within a cache. If a precached reference is not found, a call is made to createWorker (see Listing Three).

protected void doPost( HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
{
    ServletOutputStream out = resp.getOutputStream();
    String response;

    // Determine which worker this request is for
    String urlKey = req.getParameter("request");
    if ( urlKey == null ) {
        out.println("REST Server Ready");
        return;
    }
    // Get the URL query parameters (remove param "request")
    Map paramMap = req.getParameterMap();
    HashMap params = new HashMap(paramMap);
    params.remove("request");

    // Lookup the correct worker for this request and call it
    RestWorker worker = getWorker(urlKey);
    if ( worker != null )
        response = worker.onRequest(params);
    else
        response = "No REST worker for " + urlKey;
    // Output the response from the worker
    out.println(response);
}
Listing Two



public RestWorker createWorker(String className)
{
    try {
        Class compClass = Class.forName( className );
        if ( compClass != null )
        {            
            Object obj = compClass.newInstance();
            return (RestWorker)obj;
        }
    }
    catch ( Exception e ) {
        log(e.getMessage(), e);
    }
    return null;
}
Listing Three

The method createWorker uses the Class.forName library call to load a reference to the specified class name's java.lang.Class object, using Java Reflection. With a standard Java Servlet container, such as Apache Tomcat, only classes within the WEB-INF/classes directory of the web application will be located by default. Therefore, for this algorithm to work, you must place your RestWorker objects within this directory. Once the class is located, and its java.lang.Class object is loaded, the actual RestWorker object is instantiated via a call to Class.newInstance.

Next, a call is made to the worker object's cacheReference method. If True is returned, a reference to this object is stored in an in-memory cache to make subsequent requests perform a bit faster (the Java reflection code just described will no longer need to be invoked). If this method returns False, then the object reference is used for this call only. This lets you dynamically update your worker object on a running server by simply copying a new class object to the WEB-INF/classes directory. Subsequent requests should use this new class.

Finally, the worker object's onRequest method is called with the Map of parameters from the original HTTP request. The return value from this method (a String) is used as the response, and is returned to the web client. Therefore, your object can return HTML, comma-delimited data, XML, or a human-readable sentence. For instance, the output of a simple "echo" worker object (see Listing Four), as seen from a web browser, is in Figure 2. HTTP Requests made to this RestWorker object are sent back in the form of a paragraph that includes all of the request parameters and values.



public String onRequest(Map params)
{
    String resp = "Thank you for calling EchoWorker. ";
    if ( params.size() == 0 )
        return resp;
    resp += "\n\nHere are the parameters you passed: ";
    Set keys = params.keySet();
    Iterator keyIter = keys.iterator();
    while ( keyIter.hasNext() )
    {
        String key = (String)keyIter.next();
        String[] val = (String[])params.get(key);
        resp += "\n " + key + "=" + val[0];
    }
    return resp;
}
Listing Four

Figure 2: The HTTP Response from an "echo" RestWorker object as seen in a browser.

Conclusion

I've built many RESTful services, as well as web services, in different production systems with great success. In my experience, it's quicker and easier to build, deploy, and consume a REST service than a full-blown web service. If you haven't jumped into the world of SOA-based development because of the complexities of web-service development, give REST and this framework a try.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.