FeaturesPluginsDocs & SupportCommunityPartners

Getting Started with RESTful Web Services on Tomcat

REpresentational State Transfer (REST) is an architectural style for distributed hypermedia systems, such as the World Wide Web. Central to the RESTful architecture is the concept of resources identified by universal resource identifiers (URIs). These resources can be manipulated using a standard interface, such as HTTP, and information is exchanged using representations of these resources.

In the Getting Started with RESTful Web Services on GlassFish tutorial, you first learned a bit about REST and then you were shown how NetBeans IDE 6.0 supports this architectural style. For simplicity's sake, that tutorial is specifically for the GlassFish application server. To run RESTful web services on a Tomcat server, you have to perform a number of additional configuration tasks. This tutorial uses the same sources as Getting Started with RESTful Web Services on GlassFish and shows you how to deploy them on a Tomcat application server.

Contents

Content on this page applies to NetBeans IDE 6.0

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE Web & Java EE version 6.0
Java Development Kit (JDK) version 6 or
version 5
Tomcat web server Version 6.0

Tomcat can be installed, optionally, with the Web and Java EE distribution of NetBeans IDE. Alternatively, you can visit the Apache Tomcat downloads page.

This tutorial also requires the RESTful Web Services plugin. In the IDE, go to the Plugin Manager, under the Tools menu, and check whether the RESTful Web Services Plugin is installed, under the Installed tab. If it is not, install it from the Available Plugins tab, as shown below:

restful from plugin manager

Introduction

RESTful web services are services built using the RESTful architectural style. Building web services using the RESTful approach is emerging as a popular alternative to using SOAP-based technologies for deploying services on the internet, due to its lightweight nature and the ability to transmit data directly over HTTP.

The IDE supports rapid development of RESTful web services using JSR 311 - Java API for RESTful Web Services (JAX-RS) and Jersey, the reference implementation for JAX-RS.

For detailed information, refer to the following:

In addition to building RESTful web services, the IDE also supports testing, building client applications that access RESTful web services, and generating code for invoking web services (both RESTful and SOAP-based.)

Here is the list of RESTful features provided by the IDE:

  1. Rapid creation of RESTful web services from JPA entity classes and patterns.
  2. Rapid code generation for invoking web services such as Google Map, Yahoo News Search, and StrikeIron web services by drag-and-dropping components from the RESTful component palette.
  3. Generation of JavaScript client stubs from RESTful web services for building RESTful client applications.
  4. Test client generation for testing RESTful web services.
  5. Logical view for easy navigation of RESTful web service implementation classes in your project.

Before you use this tutorial, you should use Getting Started with RESTful Web Services on GlassFish, which shows you how the IDE supports you in generating, implementing, and testing RESTful web services. This tutorial demonstrates the same service but with the additional configuration steps you need to run it on a Tomcat 6.0+ application server.

Copying Libraries to Tomcat

Tomcat needs a set of toplink, derby, and javax APIs in order to support RESTful web services. These libraries are not only useful for this tutorial, but enable you to run RESTful services on Tomcat in the future.

In the following table, NB_HOME refers to the Netbeans installation directory, TOMCAT_HOME to the Apache Tomcat 6.x installation directory, and GLASSFISH_HOME to the Glassfish v2 installation directory.

After you copy these libraries, restart your computer.

Source directoryLibrary filesTarget directory
NB_HOME/java_n/modules/ext/toplink
toplink-essentials.jar
                    toplink-essentials-agent.jar
TOMCAT_HOME/lib
NB_HOME/java_n/modules/ext/jaxws/api All JAR files TOMCAT_HOME/endorsed

Create this directory if it does not exist.

GLASSFISH_HOME/javadb/lib
derbynet.jar
                    derbyclient.jar
TOMCAT_HOME/lib

Generating Entity Classes from a Database

The goal of this exercise is to create a project and generate entity classes from a database.

To create entity classes from a database:

  1. Choose File > New Project. Under Categories, select Web. Under Projects, select Web Application and click Next.
  2. Under Project Name, enter CustomerDB-Tomcat.
  3. Under Server, select Apache Tomcat 6.0.x. Click Finish.
  4. Right-click the CustomerDB-Tomcat node and choose New > Entity Classes from Database. The New Entity Classes from Database wizard opens in the Database Tables panel.
  5. In the Database Tables panel, select New Data Source from the Data Source drop-down field. The Create Data Source dialog opens.
  6. Type jdbc/sample in the JNDI Name field. From the Database Connection drop-down field, select jdbc:derby://hostname:1527/sample [app on APP], as shown below. Click OK. The dialog closes and you return to the Database Tables panel.
    Create Data Source dialog
  7. Under Available Tables, select CUSTOMER and then click Add. The DISCOUNT_CODE table, which has a relationship with the CUSTOMER table, is automatically added to the Selected Tables list, too. You should now see the following:
    Selected tables list
  8. Click Next. The Entity Classes panel opens.
  9. Under Package, type customer.db.tomcat.
  10. Click Create Persistence Unit. The Create Persistence Unit dialog opens. Accept all the defaults and click Create. You return to the Entity Classes panel. Click Finish.
  11. Look in the Projects window. You should now see the following:
    Projects veiw showing customer db tomcat package

Adding Toplink Library to Project

Although you added Toplink files to Tomcat (see Copying Libraries to Tomcat), you still need to add the TopLink Essentials library to your project in order to avoid class casting exceptions. You must add this library above the REST libraries.

  1. Right-click your project node and choose Properties from the context menu. The Project Properties dialog opens.
  2. In the Categories view, choose Libraries. A tab opens showing the project's compile-time libraries. Compile-time libraries tab in Project Properties dialog
  3. Click Add Library. The Add Library dialog opens, showing a list of available libraries.
  4. Scroll through the libraries for the Top Link Essentials library. Select that library and click Add Library.
    Top Link Essentials library in Add Library dialog
  5. You should now be back in the Project Properties dialog. TopLink Essentials should be listed in the Compile-time Libraries. Make sure the Package box is selected. Select TopLink Libraries and move it to the top of the list of libraries, by clicking Move Up. Your list of compile-time libraries should look like this:
    Project Properties dialog showing Topo Link Essentials added to top of compile time libraries
  6. Click OK. The IDE adds TopLink Essentials to the top of the project libraries. To check that the TopLink Essentials library is there, expand the Libraries node of your project. The list of libraries should look like this:
    list of libraries in project
  7. Restart the IDE for your changes to take effect. After the IDE restarts, restart the Derby database server (Tools > Java DB Database > Start Server).

Configuring the Persistence File

In Generating Entity Classes from a Database, you created a perstence unit. The configuration of this persistence unit is stored in the file persistence.xml. In your Projects view, you can find persistence.xml in your project, in the Configuration Files node.

You need to change this persistence file to use a different transaction type, to not identify the datasource, and to pass necessary properties to the persistence provider. Open persistence.xml in the IDE. Open the XML tab. Edit the file so it matches the following snippet (the parts you add or change are in boldface):

<persistence-unit name="CustomerDB-TomcatPU" transaction-type="RESOURCE_LOCAL">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>

    <!-- <jta-data-source>jdbc/sample</jta-data-source> --> 
    <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
      <property name="toplink.jdbc.user" value="app"/>
      <property name="toplink.jdbc.password" value="app"/>
      <property name="toplink.jdbc.url" value="jdbc:derby://localhost:1527/sample"/>
      <property name="toplink.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
    </properties>
        </persistence-unit>

Generating RESTful Web Services from Entity Classes

The goal of this exercise is to generate RESTful web services from the entity classes that we generated previously (see Generating Entity Classes from a Database).

  1. Right-click the package that contains the entity classes and choose New > RESTful Web Services from Entity Classes. The New RESTful Web Services from Entity Classes wizard opens.
  2. In the Available Entity Classes field, you should see the two classes Customer and DiscountCode. Click Add All, and they move to Selected Entity Classes.
  3. Click Next, and the Generated Classes panel opens.
    Generated classes

    Here you can see everything that the IDE will generate for you. The IDE uses the container-item pattern to generate the resource classes. For example, for the Customer entity class, the IDE generates a container resource called CustomersResource and an item resource called CustomerResource. Also, for each resource class, the IDE generates a converter class used for generating the resource representation from the corresponding entity instance, such as CustomersConverter and CustomerConverter. Furthermore, there is an additional converter class called reference converter, such as CustomerRefConverter, for representing relationships.

    Accept the defaults and click Finish.

  4. Look in the Projects window. You should now see the following:
    project showing web services
  5. The RESTful Web Services node in the Projects window displays all the RESTful web services in your project. The value between the square brackets, such as [/customers/], is the value for the URI template. You can also navigate to the source file by doubling clicking on this node. This view also displays all the HTTP methods and Sub-resource locator methods. Again, you can navigate to the methods by double clicking on the nodes.

Now that our entity classes and RESTful web services have been generated, let's test our application. The IDE provides a useful utility for testing RESTful web services. We will make use of it in the next section.

Testing the RESTful Web Services

The goal of this exercise is to try out our application.

  1. Right-click the project node and choose Test RESTful Web Services.

    The server starts and the application is deployed. Finally, the browser should display your application, with a link for each of the web services:
    First test

  2. On the left-hand side is the set of root resources, here they are named customers and discountCodes.

  3. First select the customers root resource. Click on the Methods drop-down list to select either GET(application/xml) or GET(application/json). Click Test. The result is displayed in the Test Output section:

    Test output listing customers
  4. There are 4 tabs in the Test Output section. The Tabular View is a flattened view that displays all the URIs in the resulting document, which you can navigate to by clicking on the links. The Raw View displays the actual data returned. Depending on which mime type you selected (application/xml or application/json), the data displayed will be in either XML or JSON format, respectively. The Headers Tab displays the HTTP header information. There is also a tab called HTTP Monitor, which displays the actual HTTP requests and responses sent and received.

  5. Exit the browser and return to the IDE.

Adding a Google Map Feature

The goal of this exercise is to add Google map functionality to our RESTful web services.

  1. Open the CustomerResource class in the editor, as shown below. Under the Tools menu, choose Palette. Notice that a palette appears on the right side of the editor, containing code snippets:
    Cutomer Resource class in editor
  2. Sign up for a Google map key at http://www.google.com/apis/maps/signup.html. The Google map key request dialog has a field for your website's URL. Type http://localhost:8080 in that field.
  3. From the Google category, drag the Map item and drop it anywhere in the class. The Customize GoogleMap dialog opens. Enter the Google Map key into the "apiKey" field, as shown here:
    Google Map customization dialog

    Click OK. The IDE creates the GoogleMapResource class. The CustomerResource class accesses it using this method, that the IDE also created:

        /**
    * Returns GoogleMapResource sub-resource.
    */
    @Path("googleMap/")
    public GoogleMapResource getGoogleMap() {
    try {
    customer.db.tomcat.Customer entity = getEntity();
    String apiKey = null;
    String address = entity.getAddressline1();
    Integer zoom = null;
    return new GoogleMapResource(apiKey, address, zoom);
    } finally {
    PersistenceService.getInstance().close();
    }
    }
  4. Right-click the project node and choose Test RESTful Web Services again and, once the browser opens again, click googleMap. You should see the following, with the apiKey filled in:
    RESTful service test showing Google Map node
  5. Click the Test button. Notice that the Google map opens in the Raw View tab:

    Important: In Firefox 2, the test client hangs forever trying to produce the image. Click the http:.../googleMap/ URL under Resource: and the map image will appear in a new browser tab.


    Google Map showing address


See Also

For more information about using NetBeans IDE 6.0 to develop Java EE applications, see the following resources:

To send comments and suggestions, get support, and keep informed on the latest developments on the NetBeans IDE Java EE development features, join the mailing list.

Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by