This chapter describes how to create and run web services in OEPE which conform to the Representational State Transfer (REST) architectural style using Java API for RESTful Web Services (JAX-RS).
This document contains the following sections:
OEPE provides tools to create Representational State Transfer (REST or RESTful) projects, configure Java projects for REST and build REST web services for your projects. REST describes any simple interface that transmits data over a standardized interface (such as HTTP) without an additional messaging layer, such as SOAP.
REST provides a set of design rules for creating stateless services that are viewed as resources, or sources of specific information, and can be identified by their unique URIs.
There are a couple steps to enabling REST web services in your OEPE applications:
Create a web project:
For complete details about developing REST web services and clients using JAX-RS, see the following Oracle documentation:
Developing and Securing RESTful Web Services for Oracle WebLogic Server
Jersey: RESTful Web services made easy, at https://wikis.oracle.com/display/Jersey/Main
To use REST in OEPE, first create a project that is configured to support REST (JAX-RS) services. You can do this in a couple steps using the web project wizards in the OEPE interface.
There are two types of projects that you can configure to use REST:
When you create a dynamic web project that is configured for REST, the system adds a web.xml
file and a weblogic.xml
file that contain the REST servlet and servlet mapping detail that your project uses at runtime, as shown in Example 9-1 and Example 9-2.
Example 9-1 web.xml configured for REST
<display-name>REST Project</display-name> <servlet> <description>JAX-RS Tools Generated - Do not modify</description> <servlet-name>JAX-RS Servlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <load-on-startup>1</load-on-startup </servlet> <servlet-mapping> <servlet-name>JAX-RS Servlet</servlet-name> <url-pattern>/jaxrs/*</url-pattern> </servlet-mapping> </web-app
Example 9-2 weblogic.xml configured for REST
<wls:weblogic-version>12.1.3</wls:weblogic-version <wls:context-root>REST_Project</wls:context-root>
To create a dynamic web project configured for REST
Create a WebLogic runtime. Both Weblogic 11g and 12c versions are supported, as well as Glassfish. These steps are for Weblogic 12c. For Weblogic 11g, the wizard interface is slightly different, and adds a weblogic.xml
file with a jax
library reference <wls:library-name> jax-rs</wls:library-name>
.
In the OEPE application, choose File > New > Web > Dynamic Web Project.
Click Next. The New Dynamic Web Project dialog appears, as shown in Figure 9-1. Add the project detail, and choose the target runtime. The target runtime is shown in the Configuration field.
Next to the Configuration field, click Modify to choose what capabilities to enable for your project. The Project Facets dialog appears, as shown in Figure 9-2.
Select JAX-RS (REST Web Services). Click OK.
Click Next. The JAX-RX Capabilities dialog appears with the default servlet and container details. If you accept the defaults click Finish.
Note: When you change the class or project class path in the run configuration wizard, be sure to manually stop the JAXRS application and restart it to reflect your changes. Unless it is stopped and started again, it will not reflect the changes. |
To use REST with your Java web project you need to add the JAX-RS library bundle. To do this, convert your Java project to a JAX-RS faceted project.
Note: JAX-RS tooling in a Java Project does not currently work with a Glassfish Runtime Specific Library Provider. Currently, Glassfish requires a Dynamic Web Project for deployment and to access the JAX-RS Implementation library provider. |
To convert a Java project for REST
Select your Java project. Right-click and choose Configure > Convert to Faceted Form.
In the Facet Page select JAX-RS, and choose the appropriate runtime version, as shown in Figure 9-3.
Notice the "Require Further Configuration" link highlighted in the lower part of the dialog. Click Require Further Configuration to continue to the JAX-RS Facet Install page, as shown in Figure 9-4.
In the JAXRS Facet Install page, select User Library.
Select the download button, or select from the previously configured user libraries available for your JAX-RS Runtime, as displayed in the libraries window. The Jersey Download is now available.
Click OK.
Once you have configured your project for REST, you are ready to create your REST web service.
You can create a new REST web service class or generate a REST web service from an existing Java class using the Create RESTful Service wizard. The wizard creates the deployment files for you. After you create your web service, the final step is to deploy it.
When you create a RESTful web service, the JAX-RS Jersey library is automatically added to your REST project.
You can create are two types of REST web services in OEPE:
There are three options to choose from for your patterned REST web services:
Single Source, - Creates a root-level JAX-RS resource class with GET and PUT methods.
Resource/sub-resources - Creates a pair of JAX-RS resource classes. The 'item' class represents individual resources in a collection, the other class is for the container that houses the collection. If the item resource URI is determined by the client, the item class is created using the PUT method in the item class, instead of the POST method.
Entities Access - Creates JAX-RS compliant web services from JPA entity classes.
To create a Single Source REST web service using the wizard:
In the OEPE application choose New > Other > Web Services > REST Web Service. The Web Service Pattern dialog appears, as shown in Figure 9-5.
The dialog has three REST pattern types from which to choose. Choose the Single Source pattern type and click Next, if you want to configure the REST methods, or click Finish to use the defaults.
If you chose Next, the Web Service Structure dialog appears with the REST Java class and the methods, as shown in Figure 9-7. You can accept the root path default or change it. Under Consumes/produces, choose the format to use to when your REST methods are consumed or produced for the root resource class. For more information see, Section 9.5, "Customizing Media Types for the Request and Response Messages".
Click Next. The Rest Application Class dialog appears. Choose to accept the default, or specify the Package and Class name added to the REST configuration, which is used at runtime to locate all the web services in the project.
To create a Resource/Sub-Resources REST web service:
In the OEPE application choose New > Other > Web Services > REST Web Service. The Web Service Pattern dialog appears, as shown in Figure 9-7.
The dialog has three REST pattern types from which to choose. Choose the Resource/sub-resources pattern type and click Next, to configure the REST methods, or Finish to use the defaults.
If you chose Next, the Web Service Structure dialog appears with the REST Java class and the methods, as shown in Figure 9-7. You can accept the root path default or change it. Under Consumes/produces, choose the format in which you want your REST methods to be consumed or produced for the root resource class. For more information see, Section 9.5, "Customizing Media Types for the Request and Response Messages".
To create a Entities Access REST web service
In the OEPE application choose New > Other > REST Web Service. The Web Service Pattern dialog appears.
The dialog has three REST pattern types from which to choose. Choose the Entities Access pattern type and click Next, if you want to configure the REST methods, or Finish to use the defaults.
If you chose Next, the Web Service Structure dialog appears with the REST Java class and the methods, as shown in Figure 9-7. You can accept the root path default or change it. Under Consumes/produces, choose the format in which you want your REST methods to be consumed or produced for the root resource class For more information see, Section 9.5, "Customizing Media Types for the Request and Response Messages".
Once your project is configured for REST (see Section 9.2, "Creating Projects Configured for REST"), you can use annotations on your POJOs to define your REST web service URIs. You can either do this directly on the file, or using the Rest AnnotationProperties window. The @Path annotation defines the relative URI path for the resource, and can be defined as a constant or variable value (referred to as "URI path template"). You can add the @Path annotation at the class or method level.
To create REST web services in the Java source editor:
To define the URI as a constant value, pass a constant value to the @Path annotation. Preceding and ending slashes (/) are optional, as shown in Example 9-3.
Example 9-3 Using Annotations to Define the Resource Class URI as a Constant
package samples.helloworld; import javax.ws.rs.Path; ... // Specifies the path to the RESTful service @Path("/helloworld") public class helloWorld {. . .}
In Example 9-4 shows the relative URI for the resource class defined using a variable, enclosed in braces.
Example 9-4 Using Annotations to Define the Resource Class URI as a Variable
package samples.helloworld; import javax.ws.rs.Path; ... // Specifies the path to the RESTful service @Path("/users/{username}") public class helloWorld {. . .} }
To create REST web services using the Annotation view
Create a POJO.
Open the Annotations view.
Put Cursor on the type declaration, this will orient the available annotations to this location.
Add the @Path Annotation, specify the value of your path, which is the URI for your resource class. This enable this class as a REST resource, as shown in Figure 9-8.
Select applicable methods and annotate with the appropriate @Path, @Get, @Put, @Post, @Delete.
JAX-RS uses Java annotations to map an incoming HTTP request to a Java method. The process for mapping HTTP Requests/Responses will is a function of the MediaTypes designated by the consumes/produces.
For more information on annotations and mapping, see Mapping Incoming HTTP Requests to Java Methods, in Developing and Securing RESTful Web Services for Oracle WebLogic Server.
A request method designator annotations are runtime annotations, defined by JAX-RS, and which correspond to the similarly named HTTP methods. Within a resource class file, HTTP methods are mapped to Java programming language methods using the request method designator annotations. The behavior of a resource is determined by which of the HTTP methods the resource is responding to. Jersey defines a set of request method designators for the common HTTP methods: @GET, @POST, @PUT, @DELETE, @HEAD.
To map an HTTP Request to a Java method in the REST wizard
These steps assume that you have a JPA faceted project with generated entities. You will also need to have the JAX-RS facet enabled. (See Chapter 9, "Creating Projects Configured for REST".)
Select File > New > Other > Web Services > Rest Web Services.
Select Entities. The HTTP Type is designated given the following rules:
PUT- method to create or update a storage container.
GET - Requests data from a specified resource.
POST-Submits data to be processed to a specified resource.
DELETE-Deletes the specified resource.
HEAD-Same as GET but returns only HTTP headers and no document body.
Open your POJO in the source editor.
Open the REST Annotations View.
Place your cursor on the Class Type and Specify the @Path Annotation, making this a JAX-RS.
Place your cursor on the given method and add the appropriate JAX-RS request method designator annotation as defined by the HTTP type rules.
The javax.ws.rs.GET
annotation transmits a representation of the resource identified by the URI to the client. The format or the representation returned in the response entity body cant be HTML, plain text, JPEG, or another form. Example 9-5 shows how to map an HTTP GET Request to a Java method in a class called BookmarksResource.
Example 9-5 Mapping the HTTP GET Request to a Java Method
import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.Path; ... public class BookmarksResource { ... @Path("{bmid: .+}") public BookmarkResource getBookmark(@PathParam("bmid") String bmid) { return new BookmarkResource(uriInfo, em, userResource.getUserEntity(), bmid); } @GET @Produces("application/json") public JSONArray getBookmarksAsJsonArray() { JSONArray uriArray = new JSONArray(); for (BookmarkEntity bookmarkEntity : getBookmarks()) { UriBuilder ub = uriInfo.getAbsolutePathBuilder(); URI bookmarkUri = ub . path(bookmarkEntity.getBookmarkEntityPK().getBmid()). build(); uriArray.put(bookmarkUri.toASCIIString()); } return uriArray; } ... }
Use the Annotations view to add your request and response requests to your POJOs.
To create REST web services using the Annotation view
Create a POJO.
Open the Annotations view.
Put cursor on the type declaration, this will orient the available annotations to this location.
For the request customization, add the @Consumes annotation and specify the value. This sets the value of the media type for that annotation. Note that when @Consumes is applied at the method level, it overrides any @Consumes annotations applied at the class level.
For the response customization, select the @Produces annotation in the properties view. Select the appropriate media type for your response. Note: If it is applied at the method level, it overrides any @Produces annotations applied at the class level.
Add the javax.ws.rs.Consumes
or javax.ws.rs.Produces
annotation at the class or method level of the resource to customize the media type of the request and response messages, respectively. More than one media type can be declared in each case.
With OEPE, you can customize message types for request and response using one of the following options:
Customize media types for your REST web service by adding the @Produces or @Consumes annotation at the class or method level of the resource. Then you can input the media types values for your produces and consumes attributes, as shown in Example 9-6.
Example 9-6 Customizing the Media Types for the Response using @Produces Annotation
package samples.produces; import javax.ws.rs.Produces; import javax.ws.rs.Path; @Path("/myResource") @Produces("text/plain") public class GetDogTreats { @GET public String doGetAsPlainText() { ... } @GET @Produces("text/html") public String doGetAsHtml() { ... } }
Use the Annotations view to add your media type annotations and properties to your Java classes.
Note: Explicit use of the javax.ws.rs.core.MediaType String constants is not directly supported through the annotations view. |
To create REST web services using the Annotations view
Create a POJO.
Open the Annotation view.
Put cursor on the type declaration, this will orient the available annotations to this location.
Add the @Consumer or the @Produces annotation, and specify the value of your annotation.
Specify the resource value of your annotation. Choose from the available values for that annotation. For example @Produces("text/plain")
, as shown in Figure 9-9.
REST services are validated based on the REST annotations present at the class, method, and method parameters level. The validation is done in the REST annotation processor.
To see the validation messages on a REST service, turn on annotation processing at the project level, through the project properties dialog. By default, annotation processing on a project is not enabled.
There is a quick fix bulb icon on the validation output window which you can select to resolve the following:
Issues with the values in the PathParam annotation.
Issues related to converting a non-public resource method to a public method.
To show annotation validations:
Go to File > Properties.
Select Java Compiler > Annotation Processing.
Select Enable project specific settings, and Enable annotation processing.
For annotations that require values, the Produces and Consumers annotations, for example, you can use Content Assist to show you the available options and choose your value. To use the Content Assist, from the annotations view click the Add symbol. Then select the <empty> field. This enables the value field below under Details. Click the page icon. This brings up a list of available values for that annotations shown in Figure 9-11
There are two types of server scenarios to run your REST projects.
Run on Server - deploys the REST application to the Project Targeted Runtime J2EE Server.
Run on a JAX-RS Resource Application - deploys to a lightweight built-in HTTP Server that designed to quickly deploy a simple JAX-RS resource.
Note: When you change the class or project class path in the run configuration wizard, you need to manually stop the JAXRS application and start to persist changes. Unless it is stopped and started again, it will not reflect the changes. |
To use the run-as feature, your project needs to have an implementation class annotated with @Path
that is packaged with a servlet specified in the web.xml
deployment descriptor.
To Run-As > Run On Server to deploy to a targeted J2EE runtime:
Navigate to the implementation class, right-click and choose Run-as > Run On Server. This publishes the application to the server. Once successfully deployed, the Browser is launched with a url specified to target the application.wadl
that corresponds to this packaged resource.
The targeted browser can be controlled through the Eclipse Workbench by selecting Window > Preferences > General > Web Browser.
Note: Advanced packaging through the application subclass is not supported, as well as the. @Path REST resources specified on super types. |
Use the Run-As > JAX-RS Resource feature to run a basic HTTP Server.
Note: The REST web service is a lightweight HTTP Server, used for running simple REST compliant POJOs. It is not a fully compliant J2EE server. For complex JAXB, JPA, EJB implementations please defer to the project target J2EE runtime container, per the steps in "How to Deploy to a Targeted Runtime J2EE Server" |
To Run-AS > JAX-RS Resource Application
On your JAX-RS annotated simple POJO, right-click and select Run-As > JAX-RS Resource Application. This will launch the Jersey HTTP Server, and by default will direct the browser launch to the application.wadl. By default it uses port 8080, if this port is already in use, you can define another port by doing the following.
Right-click your POJO again, and choose Run As > Run Configurations.
Select the JAX-RS Application with the corresponding class name, as shown in Figure 9-12. Under the Query URL, add your port configuration, as shown in Figure 9-13.
In the JAX-RS Application Run Configuration dialog, create a new configuration by selecting the project and JAX-RS annotated resource. Use the browse and search options to find your available resources.
Change the default Query Url options to customize the browser target url launch behavior. Use the additional tabs to customize the Java runtime behavior, including the VM arguments, environment variables, JRE, classpath, and common.
The Web Application Description Language (WADL) is an XML-based file format that describes your REST web services application. By default, a basic WADL is generated at runtime and can be accessed from your REST web service by adding a GET to the /application.wadl resource at the base URI of your REST application. For example: GET http://<path_to_REST_app>/application.wadl
.
You can also use the options method to return the WADL for particular resource, as shown in Example 9-7.
Example 9-7 WADL Describing a REST Web Service
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <application xmlns="http://research.sun.com/wadl/2006/10"> <doc xmlns:jersey="http://jersey.dev.java.net/" jersey:generatedBy="Jersey: 0.10-ea-SNAPSHOT 08/27/2008 08:24 PM"/> <resources base="http://localhost:9998/"> <resource path="/helloworld"> <method name="GET" id="sayHello"> <response> <representation mediaType="text/plain"/> </response> </method> </resource> </resources> </application>