PK
G\Eoa, mimetypeapplication/epub+zipPK G\E iTunesMetadata.plistx
This chapter describes how to monitor WebLogic Web services that conform to the Representational State Transfer (REST) architectural style using Java API for RESTful Web Services (JAX-RS).
This chapter includes the following sections:
To monitor your RESTful Web services, you can use one of the methods defined in Table 6-1.
Table 6-1 Methods for Monitoring RESTful Web Services
Method | More Information |
---|---|
Use the WebLogic Scripting Tool (WLST) command-line scripting environment to access run-time information and monitor run-time statistics. |
Monitoring RESTful Web Services Using WLST |
Enable the logging filter to monitor how a request is processed and dispatched to Jersey JAX-RS RI components. |
|
WebLogic Server provides several run-time MBeans, including those defined in Table 6-2, that capture run-time information and let you monitor run-time statistics for your RESTful Web service applications.
Table 6-2 Run-time MBeans for Monitoring RESTful Web Services
Run-time MBean | Description |
---|---|
|
Displays monitoring information for the RESTful Web service application. For more information, see "JaxRsApplicationRuntimeBean" in the WebLogic Server MBean Reference. |
|
Displays monitoring information about the RESTful Web service application resource configuration. For more information, see "JaxRsResourceConfigTypeRuntimeBean" in the WebLogic Server MBean Reference. |
|
Displays monitoring information about the RESTful Web service resource. Any object that is managed by a container (such as EJB) will have application scope. All other resources by default will have request scope. For more information, see "JaxRsResourceRuntimeBean" in the WebLogic Server MBean Reference. |
|
Displays monitoring information for the servlet that hosts the RESTful Web service application. For more information, see "ServletRuntimeMBean" in the WebLogic Server MBean Reference. |
To monitor RESTful Web services using WLST, perform the steps provided in the following procedure.
In this procedure, the example steps provided demonstrate how to monitor the RESTful Web Services sample delivered with the WebLogic Server Samples Server, described at "Sample Application and Code Examples" in Understanding Oracle WebLogic Server
Invoke WLST, as described in "Invoking WLST" in Oracle WebLogic Scripting Tool.
For example:
c:\> java weblogic.WLST
Connect to the Administration Server instance, as described in "connect" in WebLogic Scripting Tool Command Reference.
For example:
wls:/offline> connect('weblogic','welcome1','t3://localhost:8001')
Navigate to the server run-time MBean, as described in "serverRuntime" in WebLogic Scripting Tool Command Reference.
For example:
wls:/wl_server/serverConfig> serverRuntimes()
Location changed to serverRuntime tree. This is a read-only tree
with ServerRuntimeMBean as the root.
For more help, use help('serverRuntime')
wls:/wl_server/serverRuntime>
Navigate to the Web application component run-time MBean.
For example:
wls:/wl_server/serverRuntime> cd('ApplicationRuntimes/jaxrs') wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs> cd('ComponentRuntimes') wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs/ComponentRuntimes> cd('examplesServer_/jaxrs')
Navigate to the application run-time MBean for the RESTful Web service servlet.
For example:
wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs/ComponentRuntimes/examplesServer_/jaxrs> cd('JaxRsApplications/RestServlet')
Review the monitoring information displayed for the RESTful Web service application. For more information, see "JaxRsApplicationRuntimeBean" in the WebLogic Server MBean Reference.
For example:
wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs/ComponentRuntimes/example
sServer_/jaxrs/JaxRsApplications/RestServlet> ls()
dr-- ResourceConfig
dr-- RootResources
dr-- Servlet
-r-- ErrorCount 0
-r-- ExecutionTimeAverage 0
-r-- ExecutionTimeHigh 0
-r-- ExecutionTimeLow 0
-r-- ExecutionTimeTotal 0
-r-- HttpMethodCounts {}
-r-- InvocationCount 0
-r-- LastErrorDetails null
-r-- LastErrorMapper null
-r-- LastErrorTime 0
-r-- LastHttpMethod null
-r-- LastInvocationTime 0
-r-- LastResponseCode -1
-r-- Name RestServlet
-r-- ResponseCodeCounts {}
-r-- StartTime 1321907929703
-r-- Type JaxRsApplicationRuntime
-r-x preDeregister Void :
wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs/ComponentRuntimes/example
sServer_/jaxrs/JaxRsApplications/RestServlet>
Navigate to any of the following run-time MBeans to view additional monitoring information. For more information about the MBeans, see Table 6-2 or the WebLogic Server MBean Reference.
ResourceConfig
RootResources
Servlet
Exit WLST, as described in "Exiting WLST" in Oracle WebLogic Scripting Tool.
For example:
wls:/wl_server/serverRuntime/ApplicationRuntimes/jaxrs/ComponentRuntimes/example
sServer_/jaxrs/JaxRsApplications/RestServlet> exit()
Exiting WebLogic Scripting Tool ...
c:\>
The Jersey tracing feature provides useful information that describes how a request is processed and dispatched to Jersey JAX-RS RI components. Trace messages are output in the same order as they occur, so the numbering is useful to reconstruct the tracing order.
The following provides an example of a trace message. The message shows the request path and the initial set of regular expressions that will be matched, in order from left to right.
Example 6-1 Example of a Trace Message
Trace 001: X-Jersey-Trace-001 match path "/items/3/tracks/2/" -> "/application\\.wadl(/.\*)?", "/happy(/.\*)?", "(/.\*)?"
You can enable this feature server-wide or on a per-request basis, as described in the following sections:
To enable server-wide tracing:
Update the web.xml
deployment descriptor that is packaged with your application to add the following <init-param>
element:
<init-param> <param-name>com.sun.jersey.config.feature.Trace</param-name> <param-value>true</param-value> </init-param>
For more information about the <init-param>
element, see "servlet" in Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.
Enable the com.sun.jersey.api.core.ResourceConfig.FEATURE_TRACE
property. For more information, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/core/ResourceConfig.html#FEATURE_TRACE
.
With per-request tracing, trace messages are output if a request header is present with the header name of X-Jersey-Trace-Accept
.
Trace messages are output primarily as response headers with a header name of the form X-Jersey-Trace-
XXX
, where XXX
is a decimal value corresponding to the trace message number, and a header value that is the trace message. In certain cases, trace messages will be logged to the server if they cannot be included in the response headers, for example if the messages are too long.
To enable tracing on a per-request basis:
Update the web.xml
deployment descriptor that is packaged with your application to add the following <init-param>
element:
<init-param> <param-name>com.sun.jersey.config.feature.TracePerRequest</param-name> <param-value>true</param-value> </init-param>
For more information about the <init-param>
element, see "servlet" in Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.
Enable the com.sun.jersey.api.core.ResourceConfig.FEATURE_TRACE_PER_REQUEST
property. For more information, see http://jersey.java.net/nonav/apidocs/1.9/jersey/com/sun/jersey/api/core/ResourceConfig.html#FEATURE_TRACE_PER_REQUEST
.
This chapter describes how to develop WebLogic Web services that conform to the Representational State Transfer (REST) architectural style using Java API for RESTful Web Services (JAX-RS).
This chapter includes the following sections:
JAX-RS is a Java programming language API that uses annotations to simplify the development of RESTful Web services. JAX-RS annotations are runtime annotations. When you deploy the Java EE application archive containing JAX-RS resource classes to WebLogic Server, as described in Chapter 3, "Packaging and Deploying RESTful Web Services," the runtime configures the resources, generates the helper classes and artifacts, and exposes the resource to clients.
The following sections provide more information about RESTful Web service development:
Table 2-1 summarizes a subset of the tasks that are required to develop RESTful Web service using JAX-RS annotations. For more information about advanced tasks, see More Advanced RESTful Web Service Tasks.
In addition to the development tasks described below, you may wish to create a class that extends javax.ws.rs.core.Application
to define the components of a RESTful Web service application deployment and provides additional metadata. For more information, see Packaging With an Application Subclass.
Table 2-1 Summary of Tasks to Develop RESTful Web Services
Task | More Information |
---|---|
Define the root resource class. |
Defining the Root Resource Class |
Define the relative URI of the root resource class and its methods using the If you define the |
Defining the Relative URI of the Root Resource and Subresources |
Map incoming HTTP requests to your Java methods using |
Mapping Incoming HTTP Requests to Java Methods |
Customize the request and response messages, as required, to specify the MIME media types of representations a resource can produce and consume. |
Customizing Message Types for the Request and Response |
Extract information from the request. |
Extracting Information From the Request |
Build custom response messages to customize response codes or include additional metadata. |
Building Custom Response Messages |
Access information about the application deployment context or the context of individual requests. |
Accessing the Application Context |
Build new or extend existing resource URIs. |
|
Evaluate one or more preconditions before processing a GET request, potentially reducing bandwidth and improving server performance. |
|
Access the WADL. |
|
Secure your RESTful Web services. |
Chapter 5, "Securing RESTful Web Services" |
Example 2-1 provides a simple example of a RESTful Web service. In this example:
The helloWorld
class is a resource with a relative URI path defined as /helloworld
. At runtime, if the context root for the WAR file is defined as http://examples.com
, the full URI to access the resource is http://examples.com/helloworld
. For more information, see Defining the Relative URI of the Root Resource and Subresources.
The sayHello
method supports the HTTP GET method. For more information, see Mapping Incoming HTTP Requests to Java Methods.
The sayHello
method produces content of the MIME media type text/plain
. For more information, see Customizing Message Types for the Request and Response.
Additional examples are listed in Learn More About RESTful Web Services.
Example 2-1 Simple RESTful Web Service
package samples.helloworld; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; // Specifies the path to the RESTful service @Path("/helloworld") public class helloWorld { // Specifies that the method processes HTTP GET requests @GET @Produces("text/plain") public String sayHello() { return "Hello World!"; } }
A root resource class is a Plain Old Java Object (POJO) for which one or both of the following statements are true:
Is annotated with @Path
. For more information, see Defining the Relative URI of the Root Resource and Subresources.
Has at least one method annotated with @Path
or with a request method designator, such as @GET
, @POST
, @PUT
, or @DELETE
. A resource method is a method in the resource class that is annotated using a request method designator. For more information, see Mapping Incoming HTTP Requests to Java Methods.
Add the javax.ws.rs.Path
annotation at the class level of the resource to define the relative URI of the RESTful Web service. Such classes are referred to a root resource classes. You can add @Path
on methods of the root resource class as well, to define subresources to group specific functionality.
The following sections describe how to define the relative URI of the root resource and subresources:
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 define the URI as a constant value, pass a constant value to the @Path
annotation. Preceding and ending slashes (/) are optional.
In Example 2-2, the relative URI for the resource class is defined as the constant value, /helloworld
.
Example 2-2 Defining the Relative URI as a Constant Value
package samples.helloworld; import javax.ws.rs.Path; ... // Specifies the path to the RESTful service @Path("/helloworld") public class helloWorld {. . .}
To define the URI as a URI path template, pass one or more variable values enclosed in braces in the @Path
annotation. Then, you can use the javax.ws.rs.PathParam
annotation to extract variable information from the request URI, defined by the @Path
annotation, and initialize the value of the method parameter, as described in How to Extract Variable Information from the Request URI (@PathParam).
In Example 2-3, the relative URI for the resource class is defined using a variable, enclosed in braces, for example, /users/{username}
.
Example 2-3 Defining the Relative URI as a Variable Value
package samples.helloworld; import javax.ws.rs.Path; ... // Specifies the path to the RESTful service @Path("/users/{username}") public class helloWorld {. . .} }
To further customize the variable, you can override the default regular expression of "[^/]+?" by specifying the expected regular expression as part of the variable definition. For example:
@Path("users/{username: [a-zA-Z][a-zA-Z_0-9]}")
In this example, the username
variable will match only user names that begin with one uppercase or lowercase letter followed by zero or more alphanumeric characters or the underscore character. If the username does not match the requirements, a 404 (Not Found)
response will be sent to the client.
For more information about the @Path
annotation, see http://docs.oracle.com/javaee/6/api/index.html?javax/ws/rs/Path.html
.
Add the javax.ws.rs.Path
annotation to the method parameter of a resource to define a subresource. Subresources enable users to group specific functionality for a resource.
In Example 2-3, if the request path of the URI is users/list
, then the getUserList
subresource method is matched and a list of users is returned.
The base URI is constructed as follows:
http://myHostName/contextPath/servletURI
/resourceURI
myHostName
—DNS name mapped to the Web Server. You can replace this with host:port
which specifies the name of the machine running WebLogic Server and the port used to listen for requests.
contextPath
—Name of the standalone Web application. The Web application name is specified in the META-INF/application.xml
deployment descriptor in an EAR file or the weblogic.xml
deployment descriptor in a WAR file. If not specified, it defaults to the name of the WAR file minus the .war
extension. For more information, see "context-root" in Developing Web Applications, Servlets, and JSPs for Oracle WebLogic Server.
servletURI
—Base URI for the servlet context path. This path is configured as part of the packaging options defined in Table 3-1. Specifically, you can define the servlet context path by:
Updating the web.xml
deployment descriptor to define the servlet mapping.
Adding a javax.ws.rs.ApplicationPath
annotation to the class that extends javax.ws.rs.core.Application
, if defined.
If the servlet context path is configured using both options above, then the servlet mapping takes precedence. If you do not configure the servlet context path in your configuration using either of the options specified above, the WebLogic Server provides a default RESTful Web service application context path, resources
. For more information, see About RESTful Web Service Packaging and Deployment.
resourceURI
—@Path
value specified for the resource or subresource.
In Example 2-2, at runtime, if the context path for the WAR file is defined as rest
and the default URI for the servlet (resources
) is in effect, the base URI to access the resource is http://myServer:7001/rest/resources/helloworld
.
In Example 2-3, at runtime, the base URI will be constructed based on the value specified for the variable. For example, if the user entered johnsmith
as the username, the base URI to access the resource is http://myServer:7001/rest/resources/users/johnsmith
.
JAX-RS uses Java annotations to map an incoming HTTP request to a Java method. Table 2-2 lists the annotations available, which map to the similarly named HTTP methods.
Table 2-2 javax.ws.rs Annotations for Mapping HTTP Requests to Java Methods
Annotation | Description | Idempotent |
---|---|---|
|
Transmits a representation of the resource identified by the URI to the client. The format might be HTML, plain text, JPEG, and so on. See How to Transmit a Representation of the Resource (@GET). |
Yes |
|
Creates or updates the representation of the specified resource identified by the URI. See How to Create or Update the Representation of the Resource (@PUT). |
Yes |
|
Deletes the representation of the resource identified by the URI. See How to Delete a Representation of the Resource (@DELETE). |
Yes |
|
Creates, updates, or performs an action on the representation of the specified resource identified by the URI. See How to Create, Update, or Perform an Action On a Representation of the Resource (@POST). |
No |
|
Returns the response headers only, and not the actual resource (that is, no message body). This is useful to save bandwidth to check characteristics of a resource without actually downloading it. For more information, see The |
Yes |
|
Returns the communication options that are available on the request/response chain for the specified resource identified by the URI. The The |
Yes |
|
Indicates that the annotated method should be used to handle HTTP requests. For more information, see |
N/A |
The following sections provide more information about the JAX-RS annotations used for mapping HTTP requests to Java methods.
How to Create or Update the Representation of the Resource (@PUT)
How to Create, Update, or Perform an Action On a Representation of the Resource (@POST)
The examples referenced in the following sections are excerpted from the bookmark sample that is delivered with Jersey 1.9 JAX-RS RI. The bookmark sample provides a Web application that maintains users and the browser bookmarks that they set.
The following table summarizes the resource classes in the sample, their associated URI path, and the HTTP methods demonstrated by each class.
Table 2-3 About the Jersey Bookmark Sample
Resource Class | URI Path | HTTP Methods Demonstrated |
---|---|---|
|
|
GET |
|
|
GET, PUT, DELETE |
|
|
GET, POST |
|
|
GET. PUT, DELETE |
The bookmark sample, and other Jersey samples, can be accessed in one of the following ways:
Downloading the Jersey 1.9 software at http://jersey.java.net
Browsing the Maven repositories at: https://maven.java.net/content/repositories/releases/com/sun/jersey/samples
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 might be HTML, plain text, JPEG, and so on. For more information about the @GET
annotation, see http://docs.oracle.com/javaee/6/api/index.html?javax/ws/rs/GET.html
.
In Example 2-5, the annotated Java method, getBookmarkAsJsonArray
, from the BookmarksResource
class in the Jersey bookmark sample, will process HTTP GET requests. For more information about the Jersey bookmark sample, see About the Jersey Bookmark Sample.
Example 2-5 Mapping the HTTP GET Request to a Java Method (BookmarksResource Class)
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; } ... }
In Example 2-6, the annotated Java method, getBookmark
, from the BookmarkResource
class in the Jersey bookmark sample, will process HTTP GET requests. This example shows how to process the JSON object that is returned. For more information about the Jersey bookmark sample, see About the Jersey Bookmark Sample.