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 this tutorial, you first learn a bit about REST and then you are shown how NetBeans IDE supports this architectural style.
Contents
To follow this tutorial, you need the following software and resources.
Software or ResourceVersion Required
NetBeans IDEJava download bundle, version 6.8
Java Development Kit (JDK)version 6 or version 5
Warning: NetBeans IDE 6.9 requires JDK 6
Java EE-compliant web or application serverTomcat web server 6.0 or GlassFish Server Open Source Edition.
Important: If you use Tomcat with this Tutorial, see 
the NetBeans Wiki on Tomcat with REST.
The jdbc/sample database on the
Java DB (Derby) database server
Generated by NetBeans IDE when you install
it with the GlassFish application server

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.
  6. Fully integrated Spring framework, providing Spring transaction handling.
In this tutorial, you will be shown how the IDE supports you in generating, implementing, and testing RESTful web services.

Generating Entity Classes from a Database

The goal of this exercise is to create a project and generate entity classes from a database.
This section uses the JavaDB (Derby) database and the jdbc/sample data source. JavaDB is included with the SDK. The jdbc/sample data source is generated by NetBeans IDE automatically when you install the IDE together with GlassFish.
  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select Java Web. Under Projects, select Web Application and click Next.
    Alternatively, you can create a Maven Web Application. Choose File > New Project (Ctrl-Shift-N). Under Categories, select Maven. Under Projects, select Maven Web Application and click Next.
  2. Under Project Name, enter CustomerDB. Click Next.
  3. Select either EE 6 or EE 5. Under Server, select the server you want to use, but note that EE 6 projects require the GlassFish server 3.0.1. Click through the remaining options and click Finish.
  4. Right-click the CustomerDB node and choose New > Entity Classes from Database. Alternatively, you can select it from the Persistence category in the New File wizard (Ctrl-N).
  5. In the Database Tables panel, if you are using the GlassFish server, select the jdbc/sample data source from the Data Source drop-down field.
    If you are using Tomcat, select jdbc:derby://localhost:1527/sample. If the Derby database server does not start automatically, you need to start it from the Databases tab in the Services window.
  6. 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 now see the following: 

    Click Next.
  7. Under Package, type customerdb. You now see the following. 
  8. Click Create Persistence Unit. The following dialog appears.
    Click Create. You return to the Entity Classes pane. Click Finish, and the IDE creates the entity classes.
  9. Look in the Projects window. You now see the following. 

Generating RESTful Web Services from Entity Classes

The goal of this exercise is to generate RESTful web services from the entity classes that you generated in the previous section.
  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, displaying the entity classes you can select for creating RESTful web services. Click Add All. The Customer and DiscountCode classes are selected. 
  2. Click Next. The Generated Classes panel opens.
    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.
    Accept the defaults and click Finish.
  3. A dialog window opens giving you a choice of how to register REST resources. If you are creating an EE 6 application, you have the option of letting the IDE generate a subclass of javax.ws.rs.core.Application, which then registers all REST resources automatically. In EE6, this is the default option. In an EE 5 application, the default option is to create a REST servlet adaptor in the web.xml deployment descriptor. In either version of EE, you can select to hand-code resource registration instead of letting the IDE do it. You can also customize the path to the resources.
    For the purposes of this tutorial, accept the default options and click OK. The IDE generates the RESTful web services.
Look in the Projects window. You now see the following:

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 test your application. The IDE provides a useful utility for testing RESTful web services. You will make use of it in the next section.

Testing the RESTful Web Services

The goal of this exercise is to try out your application.
  1. Right-click the project node and choose Test RESTful Web Services. The server starts and the application is deployed. When deployment is complete, the browser displays your application, with a link for each of the web services.
    On the left-hand side is the set of root resources. Here they are named customers and discountCodes.
  2. Click the customers node. The browser window shows you a list of parameters for testing the Customers service. 
    You can set the following parameters:
    • Choose method to test: Choose the GET or POST method and the MIME type from a drop-down list.
    • Start: First entity to display. Note that the numbering begins with 0, not 1.
    • Max: Maximum number of entities to fetch. If set to 0, all entities are fetched.
    • Expand level: An advanced feature. Some services return an infinitely repeating tree hierarchy. This parameter specifies what depth of such hierarchies to display in the Raw View.
    • Query: An advanced feature. Searches the XML or JSON document according to JPA syntax.
  3. Click on the Methods drop-down list to select GET(application/xml). Type "3" in the Max field. Leave default values in the other parameters and click Test. The result is displayed in the Test Output section. 
    There are 5 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 Sub Resource tab shows the URLs of the root resource and sub resources. When the RESTful web service is based on database entity classes, the root resource represents the database table, and the sub resources represent the columns.
    • The Headers tab displays the HTTP header information.
    • The HTTP Monitor tab displays the actual HTTP requests and responses sent and received.
    Note that you have 6 results listed although you specified a maximum of 3 entities to display. Open the Raw View tab to see the reason why. Each entity corresponds to a<customer> element, and you have only 3 customers in the test results. However, the Tablular view lists URIs, not entities, and each entity has two URIs, one as an attribute of the parent <customer> element and one as an attribute of the child <discountCode> element. So although there are only 3 customer entities, there are 6 URIs in total.
  4. 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.
  2. Add the following method to CustomerResource:
    @GET
    @Produces("text/html")
    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
    
       return "";
    }
  3. 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. Typehttp://localhost:8080 in that field.
  4. In the IDE, open the Services tab and expand the Web Services node. Under Web Services, expand Google. Under Google, expand Map Service.

  5. Drag the getGoogleMap item and drop it into the body of the getGoogleMap method you created in Step 2, just before the return = ""; line. The Customize getGoogleMap SAAS dialog opens. Accept the defaults and click OK.
    The IDE adds the following try block to the getGoogleMap method in the CustomerResource class.
    @GET
    @Produces("text/html")
    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
            
        try {
                 
             String address = "16 Network Circle, Menlo Park";
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             //TODO - Uncomment the print Statement below to print result.
             //System.out.println("The SaasService returned: "+result.getDataAsString());
        } catch (Exception ex) {
             ex.printStackTrace();
        }
    
        return "";
    
    }
                    
    The IDE also creates the packages org.netbeans.saas and org.netbeans.saas.google, which contain the following classes and resources:
    • RestConnection – A wrapper around HttpUrlConnection
    • RestResponse – A wrapper for the HTTP response
    • googlemapservice.properties – A properties file that stores the API key
    • GoogleMapService – A service wrapper containing the wrapper methods that uses RestConnection to make calls to the Google Map service.
  6. In the try block of getGoogleMap(), replace the commented-out print statement with the line return result.getDataAsString();. The method now looks like this:
    @GET
    @Produces("text/html")
    public String getGoogleMap() {
    // Drag and drop the getGoogleMap operation here
            
        try {
                 
             String address = "16 Network Circle, Menlo Park";
             java.lang.Integer zoom = 15;
             String iframe = "false";
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             return result.getDataAsString();
        } catch (Exception ex) {
             ex.printStackTrace();
        }
    
        return "";
    }
  7. Open googlemapservice.properties. Paste in the API key you got from Google in Step 3.
  8. Right-click the CustomerDB project node and select Test RESTful Web Services. The IDE undeploys and redeploys your project to the server and then opens a browser window with the test client.
  9. Click customers in the left sidebar. Test criteria for customers open in the main pane. Leave the defaults and click Test. A table of customers opens.
  10. From the table, click customer1. A test window for that customer opens in the main pane. From the drop-down menu, select the text/html MIME type. Click Test. The GoogleMap of 16 Network Circle, Menlo Park opens in the Raw View. 
  11. The Google map of the Menlo Park address appears for all customers in the database. To display the Google maps of the actual addresses of the customers, create an instance of Customer for each entity in the database and set the address equal to a concatenation of address variables for each Customer. If you are using an earlier version of the IDE than 6.5, also add a line at the end of the try block to close the instance of Customer. The method now looks like the following (changes in bold):
    @GET
    @Produces("text/html")
    public String getGoogleMap() {
        try {
             Customer c = getEntity();
             String address = c.getAddressline1() + " " + c.getAddressline2() + " " +
                     c.getCity() + " " + c.getState() + " " + c.getZip();
             java.lang.Integer zoom = 15;
             String iframe = "false";
     
             RestResponse result = GoogleMapService.getGoogleMap(address, zoom, iframe);
             return result.getDataAsString();
         
         } catch (Exception ex) {
             ex.printStackTrace();
         } 
    
         //The close() method is only necessary with versions of NetBeans IDE earlier than 6.5
    
             finally {
                 PersistenceService.getInstance().close();
         }
         return "";
                }
  12. Test the RESTful web services again. Again, select the text/html MIME type for one of the customers. A Google map of that customer's address in the database now displays in the Raw View. For customer1, the following map displays: 

RESTful Web Services in the Spring Framework

Starting in NetBeans IDE 6.5 and Jersey 0.8, Jersey is integrated into the Spring Framework. When you create a Java Web application with the Spring framework, a REST-aware servlet is automatically created. The user does not need to perform any additional steps.
To create RESTful Web Services with the Spring framework, repeat the procedures described in the tutorial, with one exception. When you create the Java Web application in the New Project wizard as described in Generating Entity Classes from a Database, after you select the server, click Next instead of Finish. This opens the Frameworks panel. Select Spring Web MVC, then click Finish.
After you create the RESTful services, note the following differences between the Spring project and the project you created without Spring:
  • The Spring project does not have a class called PersistenceService.java in the customerdb.service package.
  • CustomerResource.java imports org.springframework.transaction.annotation.Transactional and contains a number of @Transactional annotations.
Both of these differences are due to the Spring framework handling transactions and entity management, whereas in the other project the IDE had to create a class that usedjavax.transaction.UserTransaction and javax.persistence.EntityManager. The Spring framework results in cleaner code and more efficient transaction handling and entity management.
For more about the features of Spring framework projects in NetBeans IDE, see Introduction to the Spring Framework.