blob: fb8ca949cb6b0cd2ca0c388513a5e73f8bd05085 [file] [log] [blame]
\chapter{Resources}
\label{resources}
Using \jaxrs\, a Web resource is implemented as a resource class and requests are handled by resource methods. This chapter describes resource classes and resource methods in detail.
\section{Resource Classes}
A resource class is a Java class that uses \jaxrs\ annotations to implement a corresponding Web resource. Resource classes are POJOs that have at least one method annotated with \Path\ or a request method designator.
\subsection{Lifecycle and Environment}
By default a new resource class instance is created for each request to that resource. First the constructor (see section \ref{resource_class_constructor}) is called, then any requested dependencies are injected (see chapter \ref{context}), then the appropriate method (see section \ref{resource_method}) is invoked and finally the object is made available for garbage collection.
An implementation MAY offer other resource class lifecycles, mechanisms for specifying these are outside the scope of this specification. E.g. an implementation based on an inversion-of-control framework may support all of the lifecycle options provided by that framework.
\subsection{Constructors}
\label{resource_class_constructor}
Root resource classes are instantiated by the \jaxrs\ runtime and MUST have a public constructor for which the \jaxrs\ runtime can provide all parameter values. Note that a zero argument constructor is permissible under this rule.
A public constructor MAY include parameters annotated with one of the following: \Context, \HeaderParam, \CookieParam, \MatrixParam, \QueryParam\ or \PathParam - section \ref{resource_method_params} defines the parameter types permitted for each annotation. However, depending on the resource class lifecycle and concurrency, per-request information may not make sense in a constructor. If more than one public constructor can be used then an implementation MUST use the one with the most parameters. Choosing amongst constructors with the same number of parameters is implementation specific.
Non-root resource classes are instantiated by an application and do not require the above-described public constructor.
\section{Resource Methods}
\label{resource_method}
Resource methods are methods of a resource class annotated with a request method designator. They are used to handle requests and MUST conform to certain restrictions described in this section.
A request method designator is a runtime annotation that is annotated with the \HttpMethod\ annotation. \jaxrs\ defines a set of request method designators for the common HTTP methods: \code{@GET}, \code{@POST}, \code{@PUT}, \code{@DELETE}, \code{@HEAD}. Users may define their own custom request method designators including alternate designators for the common HTTP methods.
\subsection{Visibility}
Only \code{public} methods may be exposed as resource methods. An implementation SHOULD warn users if a non-\code{public} method carries a method designator or \Path\ annotation.
\subsection{Parameters}
\label{resource_method_params}
When a resource method is invoked, parameters annotated with one of the following annotations are mapped from the request according to the semantics of the annotation:
\begin{description}
\item[\MatrixParam] Extracts the value of a URI matrix parameter.
\item[\QueryParam] Extracts the value of a URI query parameter.
\item[\PathParam] Extracts the value of a URI template parameter.
\item[\CookieParam] Extracts the value of a cookie.
\item[\HeaderParam] Extracts the value of a header.
\item[\Context] Injects an instance of a supported resource, see chapters \ref{context} and \ref{environment} for more details.
\end{description}
Valid parameter types for each of the above annotations are listed in the corresponding Javadoc. The \code{Default\-Value} annotation may be used to supply a default value for some of the above, see the Javadoc for \code{Default\-Value} for usage details and rules for generating a value in the absence of this annotation and the requested data. The \code{Encoded} annotation may be used to disable automatic URI decoding for \MatrixParam, \QueryParam\ and \PathParam\ annotated parameters.
The value of an non-annotated parameter is mapped from the request entity body. Resource methods MUST NOT have more than one parameter that is not annotated with one of the above-listed annotations. Conversion between an entity body and a Java type is the responsibility of an entity provider, see section \ref{entity_providers}.
\subsection{Return Type}
\label{resource_method_return}
Resource methods MAY return \code{void}, \Response\ or another Java type, these return types are mapped to a response entity body as follows:
\begin{description}
\item[\code{void}] Results in an empty entity body with a 204 status code.
\item[\Response] Results in an entity body mapped from the \code{Entity} property of the \Response\ with the status code specified by the status property of the \Response. A \code{null} return value results in a 204 status code.
\item[Other] Results in an entity body mapped from the return type. If the return value is not \code{null} a 200 status code is used, a \code{null} return value results in a 204 status code.
\end{description}
Conversion between a Java types and an entity body is the responsibility of an entity provider, see section \ref{entity_providers}.
Methods that need to provide additional metadata with a response should return an instance of \Response, the \Response\code{Builder} class provides a convenient way to create a \Response\ instance using a builder pattern.
\subsection{Exceptions}
An implementation MUST catch \WebAppExc\ and map it to a response. If the \code{response} property of the exception is not \code{null} then it MUST be used to create the response. If the \code{response} property of the exception is \code{null} an implementation MUST generate a server error response.
An implementation MUST allow other runtime exceptions to propagate to the underlying container. This allows existing container facilities (e.g. a Servlet filter) to be used to handle the error if desired.
\begin{ednote}What to do about checked exceptions ? If we allow them on resource methods then do we need some standard runtime exception that can be used to wrap the checked exception so it can be propagated to the container in a standard way ?\end{ednote}
\subsection{HEAD and OPTIONS}
\label{head_and_options}
\code{HEAD} and \code{OPTIONS} requests receive additional automated support. On receipt of a\code{HEAD} request an implementation MUST either:
\begin{enumerate}
\item Call a method annotated with a request method designator for \code{HEAD} or, if none present,
\item\label{get_not_head} Call a method annotated with a request method designator for \code{GET} and discard any returned entity.
\end{enumerate}
Note that option \ref{get_not_head} may result in reduced performance where entity creation is significant.
On receipt of an \code{OPTIONS} request an implementation MUST either:
\begin{enumerate}
\item Call a method annotated with a request method designator for \code{OPTIONS} or, if none present,
\item Generate an automatic response from the declared metadata of the matching class.
\end{enumerate}
\section{URI Templates}
A resource class is anchored in URI space using the \Path\ annotation. The value of the annotation is a relative URI path template whose base URI is provided by the deployment context. Root resource classes are anchored directly using a \Path\ annotation on the class.
\begin{ednote}Add reference to URI Templates ID when available.\end{ednote}
A URI path template is a string with zero or more embedded parameters that, when values are substituted for all the parameters, is a valid URI\cite{uri} path. A template parameter is represented as \lq\{\rq{\em name}\lq\}\rq\ where {\em name} is the name of the parameter. E.g.:
\begin{listing}{1}
@Path("widgets/{id}")
public class Widget {
...
}\end{listing}
In the above example the \code{Widget} resource class is identified by the relative URI path \code{widgets/{\em xxx}} where \code{\em xxx} is the value of the \code{id} parameter.
\begin{nnnote}Because \lq\{\rq and \lq\}\rq\ are not part of either the reserved or unreserved productions of URI\cite{uri} they will not appear in a valid URI.\end{nnnote}
The \code{encode} property of \Path\ controls whether the value of the annotation is automatically encoded (the default) or not. E.g. the following two lines are equivalent:
\begin{listing}{1}
@Path("widget list/{id}")
@Path(value="widget%20list/{id}" encode=false)
\end{listing}
When automatic encoding is disabled, care must be taken to ensure that the value of the URI template is valid.
The \code{limited} property of \Path\ controls whether a trailing template variable matches a single path segment or multiple. Setting the property to false allows a single template variable to match a path and can be used, e.g., when a template represents a path prefix followed by a path consisting of arbitrarily many path segments. E.g.:
\begin{listing}{1}
@Path(value="widgets/{path}", limited=false)
public class Widget {
...
}\end{listing}
In the above example the \code{Widget} resource class can be used for any request whose path starts with the \code{widgets}; the value of the \code{path} parameter will be the request path following \code{widgets}. E.g. given the request path \code{widgets/small/a} the value of \code{path} would be \code{small/a}.
\subsection{Sub Resources}
\label{sub_resources}
Methods of a resource class that are annotated with \Path\ are either sub-resource methods or sub-resource locators. The differentiator is the presence or absence of request method designator:
\begin{description}
\item[Present] Such methods, known as {\em sub-resource methods}, are treated like a normal resource method (see section \ref{resource_method}) except the method is only invoked for request URIs that match a URI template created by concatenating the URI template of the resource class with the URI template of the method\footnote{If the resource class URI template does not end with a \lq/\rq\ character then one is added during the concatenation.}.
\item[Absent] Such methods, known as {\em sub-resource locators}, are used to further resolve the object that will handle the request. Any returned object is treated as a resource class and used to either handle the request or to further resolve the object that will handle the request, see \ref{mapping_requests_to_java_methods} for further details.
\end{description}
The following example illustrates the difference:
\begin{listing}{1}
@Path("widgets")
public class WidgetsResource {
@GET
@Path("offers")
public WidgetList getDiscounted() {...}
@Path("{id}")
public WidgetResource findWidget(@UriParam("id") String id) {
return lookupWidget(id);
}
}\end{listing}
In the above a \code{GET} request for the \code{widgets/offers} resource is handled directly by the \code{getDiscounted} sub-resource method of the resource class \code{WidgetsResource} whereas a \code{GET} request for \code{widgets/{\em xxx}} is handled by whatever resource class instance is returned by the \code{findWidget} sub-resource locator (a \code{WidgetResource}).
\begin{nnnote}A set of sub-resource methods annotated with the same URI template value are functionally equivalent to a similarly annotated sub-resource locator that returns an instance of a resource class with the same set of resource methods.\end{nnnote}
\section{Declaring Media Type Capabilities}
\label{declaring_method_capabilities}
Application classes can declare the supported request and response media types using the \ProduceMime\ and \ConsumeMime\ annotations. These annotations MAY be applied to a resource method, a resource class, or to an entity provider (see section \ref{declaring_provider_capabilities}). Use of these annotations on a resource method overrides any on the resource class or on an entity provider for a method argument or return type. In the absence of either of these annotations, support for any media type (\lq\lq*/*\rq\rq) is assumed.
The following example illustrates the \ProduceMime\ annotation:
\begin{listing}{1}
@Path("widgets")
@ProduceMime("application/xml")
public class WidgetsResource {
@GET
public String getAll() {...}
@GET
@Path("{id}")
public Widget getWidget(@UriParam("id") String id) {...}
@GET
@Path("{id}/description")
@ProduceMime("text/html")
public String getDescription(@UriParam("id") String id) {...}
}
@Provider
@ProduceMime({"application/xml", "application/json"})
public class WidgetProvider implements MessageBodyWriter<Widget> {...}
\end{listing}
In the above:
\begin{itemize}
\item The \code{getAll} resource method returns a \code{String} in the \code{application/xml} format,
\item The \code{getDescription} sub-resource method returns a \code{String} as \code{text/html}, and
\item The \code{getWidget} sub-resource method returns a \code{Widget} entity instance that can be mapped to either \code{application/xml} or \code{application/json} using the \code{WidgetProvider} class (see section \ref{entity_providers} for more information on \MsgWrite).
\end{itemize}
An implementation MUST NOT invoke a method whose effective value of \ProduceMime\ does not match the request \code{Accept} header. An implementation MUST NOT invoke a method whose effective value of \ConsumeMime\ does not match the request \code{Content-Type} header.
\section{Annotation Inheritance}
\jaxrs\ annotations MAY be used on the methods of a super-class or an implemented interface. Such annotations are inherited by a corresponding sub-class or implementation class method provided that method does not have any of its own \jaxrs\ annotations. Annotations on a super-class take precedence over those on an implemented interface. If a subclass or implementation method has any \jaxrs\ annotations then {\em all} of the annotations on the super class or interface method are ignored. E.g.:
\begin{listing}{1}
public interface ReadOnlyAtomFeed {
@GET @ProduceMime("application/atom+xml")
Feed getFeed();
}
@Path("feed")
public class ActivityLog implements ReadOnlyAtomFeed {
public Feed getFeed() {...}
}
\end{listing}
In the above, \code{ActivityLog.getFeed} inherits the \code{@GET} and \ProduceMime\ annotations from the interface. Conversely:
\begin{listing}{1}
@Path("feed")
public class ActivityLog implements ReadOnlyAtomFeed {
@ProduceMime("application/atom+xml")
public Feed getFeed() {...}
}
\end{listing}
In the above, the \code{@GET} annotation on \code{ReadOnlyAtomFeed.getFeed} is not inherited by \code{Activity-Log\-.get\-Feed} and it would require its own request method designator since it redefines the \ProduceMime\ annotation.
\section{Matching Requests to Resource Methods}
\label{mapping_requests_to_java_methods}
This section describes how a request is matched to a resource class and method.
\subsection{Request Preprocessing}
For the purposes of matching, Request URIs are preprocessed to support URI-based content negotiation as follows:
\begin{enumerate}
\item Set
\begin{itemize}
\item $M = \{\mbox{\code{config.getMediaTypeMappings().keySet()}}\}$
\item $L = \{\mbox{\code{config.getLanguageMappings().keySet()}}\}$
\item Where \code{config} is an instance of the application-supplied subclass of \code{ApplicationConfig}.
\end{itemize}
\item For each extension (a \lq.\rq\ character followed by one or more alphanumeric characters) $e$ in the final path segment:
\begin{enumerate}
\item Remove the leading \lq.\rq\ character from $e$
\item\label{removematchingext} If $e$ is a member of $M$ or $L$ then remove the corresponding extension from the effective request URI.
\item If $e$ is a member of $M$ then set the effective value of the \code{Accept} header to \code{config\-.get\-Extension\-Mappings()\-.get($e$)}
\item Else if $e$ is a member of $L$ then set the effective value of the \code{Accept-Language} header to \code{config\-.get\-Language\-Mappings()\-.get($e$)}
\end{enumerate}
\end{enumerate}
The above preprocessing MUST NOT impact the URIs obtained from an injected \code{UriInfo}, in particular extensions removed in step \ref{removematchingext} MUST still be present in URIs returned from the methods of \UriInfo. Similarly the methods of \HttpHeaders\ MUST return the actual values of the \code{Accept} and \code{Accept-Language} headers rather than the effective values set during preprocessing.
\subsection{Request Matching}
A request is matched to the corresponding resource method or sub-resource method by comparing the preprocessed request URI, the media type of any request entity, and the requested response entity format to the metadata annotations on the resource classes and their methods. If no matching resource method or sub-resource method can be found then an appropriate error response is returned. Matching of requests to resource methods proceeds in three stages as follows:
\begin{enumerate}
\item Identify the root resource class:
\begin{enumerate}
\item Set $U=\mbox{request URI path}, C=\{\mbox{root resource classes}\}, E=\{\}$
\item For each class in $C$ add a regular expression (computed using the function $R(A)$ described in section \ref{template_to_regex}) to $E$ as follows:
\begin{itemize}
\item Add $R(T_{\mbox{class}})$ where $T_{\mbox{class}}$ is the URI path template specified for the class.
\end{itemize}
\item Filter $E$ by matching each member against $U$ as follows:
\begin{itemize}
\item Remove members that do not match $U$.
\item Remove members for which the final capturing group value is neither empty nor \lq/\rq\ and the class associated with $R(T_{\mbox{class}})$ had no sub-resource methods or locators.
\end{itemize}
\item If $E$ is empty then no matching resource can be found, the algorithm terminates and an implementation MUST generate a not found response (HTTP 404 status).
\item Sort $E$ using the number of literal characters\footnote{Here, literal characters means those not resulting from template variable substitution.} in each member as the primary key (descending order) and the number of capturing groups as a secondary key (descending order).
\item Set $R_{\mbox{match}}$ to be the first member of $E$, set $U$ to be the value of the final capturing group of $R(T_{\mbox{match}})$ when matched against $U$, and instantiate an object $O$ of the associated class.
\end{enumerate}
\item \label{find_object} Obtain the object that will handle the request:
\begin{enumerate}
\item \label{check_null} If $U$ is null or \lq/\rq\ go to step \ref{find_method}
\item Set $C=\mbox{class of} O, E=\{\}$
\item For class $C$ add regular expressions to $E$ for each sub-resource method and locator as follows:
\begin{enumerate}
\item \label{t_method_items} For each sub-resource method, add $R(T_{\mbox{method}})$ where $T_{\mbox{method}}$ is the URI path template of the sub-resource method.
\item For each sub-resource locator, add $R(T_{\mbox{locator}})$ where $T_{\mbox{locator}}$ is the URI path template of the sub-resource locator.
\end{enumerate}
\item Filter $E$ by matching each member against $U$ as follows:
\begin{itemize}
\item Remove members that do not match $U$.
\item Remove members derived from $T_{\mbox{method}}$ (those added in step \ref{t_method_items}) for which the final capturing group value is neither empty nor \lq/\rq.
\end{itemize}
\item If $E$ is empty then no matching resource can be found, the algorithm terminates and an implementation MUST generate a not found response (HTTP 404 status).
\item Sort $E$ using the number of literal characters in each member as the primary key (descending order), the number of capturing groups as a secondary key (descending order), and the source of each member as tertiary key sorting those derived from $T_{\mbox{method}}$ ahead of those derived from $T_{\mbox{locator}}$.
\item Set $R_{\mbox{match}}$ to be the first member of $E$
\item If $R_{\mbox{match}}$ was derived from $T_{\mbox{method}}$ then go to step \ref{find_method}.
\item Set $U$ to be the value of the final capturing group of $R(T_{\mbox{match}})$ when matched against $U$, invoke the sub-resource locator method of $O$ and set $O$ to the value returned from that method.
\item Go to step \ref{check_null}.
\end{enumerate}
\item \label{find_method} Identify the method that will handle the request:
\begin{enumerate}
\item Find the set of resource methods $M$ of $O$ that meet the following criteria:
\begin{itemize}
\item If $U$ is neither empty nor equal to \lq/\rq, the method must be annotated with a URI template that, when transformed into a regular expression using the process described in section \ref{template_to_regex}, matches $U$ with a final capturing group value that is either empty or equal to \lq/\rq.
\item The request method is supported. If no methods support the request method an implementation MUST generate a method not allowed response (HTTP 405 status). Note the additional support for \code{HEAD} and \code{OPTIONS} described in section \ref{head_and_options}.
\item The media type of the request entity body (if any) is a supported input data format (see section \ref{declaring_method_capabilities}). If no methods support the media type of the request entity body an implementation MUST generate an unsupported media type response (HTTP 415 status).
\item At least one of the acceptable response entity body media types is a supported output data format (see section \ref{declaring_method_capabilities}). If no methods support one of the acceptable response entity body media types an implementation MUST generate a not acceptable response (HTTP 406 status).
\end{itemize}
\item Sort $M$ a follows:
\begin{itemize}
\item The primary key is the media type of input data. Methods whose \ConsumeMime\ value most closely match the media type of the request are sorted first.
\item The secondary key is the \ProduceMime\ value. Methods whose value of \ProduceMime\ most closely match the value of the request accept header are sorted first.
\end{itemize}
Sorting of media types follows the general rule: x/y $<$ x/* $<$ */*, i.e. a method that explicitly lists one of the requested media types is sorted before a method that lists */*. Quality parameter values are also used such that x/y;q=1.0 $<$ x/y;q=0.7. See section 14.1 of \cite{http11} for more details.
\item \label{dispatch_method} If $M$ is not empty then the request is dispatched to the first Java method in the set; otherwise no matching resource method can be found and the algorithm terminates.
\end{enumerate}
\end{enumerate}
\subsection{Converting URI Templates to Regular Expressions}
\label{template_to_regex}
The function $R(A)$ converts a URI path template annotation $A$ into a regular expression as follows:
\begin{enumerate}
\item If $A.\mbox{encode}=\mbox{true}$, URI encode the template, ignoring URI template variable specifications.
\item Escape any regular expression characters in the URI template, again ignoring URI template variable specifications.
\item Replace the URI template variables\footnote{The regular expression to match a URI path template variable is $\backslash$\{([$\backslash$w-$\backslash.\sim$]+?)$\backslash$\}.} with the regular expression \lq(.*?)\rq.
\item If the resulting string ends with \lq/\rq\ then remove the final character.
\item If $A.\mbox{limited}=\mbox{true}$, append \lq(/.*)?\rq\ to the result, else append \lq(/)?\rq\ to the result.
\end{enumerate}
Note that the above renders the name of template variables irrelevant for template matching purposes. However, implementations will need to retain template variable names in order to facilitate the extraction of template variable values via \PathParam\ or \UriInfo\code{.getTemplateParameters}.
\section{Determining the MediaType of Responses}
In many cases it is not possible to statically determine the media type of a response. The following algorithm is used to determine the response media type, $M_{\mbox{selected}}$, at run time:
\begin{enumerate}
\item Gather the set of producible media types $P$:
\begin{itemize}
\item If the method is annotated with \ProduceMime, set $P = \{ V(\mbox{method}) \}$ where $V(t)$ represents the values of \ProduceMime\ on the specified target $t$.
\item Else if the class is annotated with \ProduceMime, set $P = \{ V(\mbox{class}) \}$.
\item Else set $P = \{ V(\mbox{writers}) \}$ where \lq writers\rq\ is the set of \MsgWrite\ that support the class of the returned entity object.
\end{itemize}
\item If $P = \{\}$, set $P = \{\mbox{\lq*/*\rq}\}$
\item Obtain the acceptable media types $A$. If $A = \{\}$, set $A = \{\mbox{\lq*/*\rq}\}$
\item Sort $A$ and $P$ in descending order, each with a primary key of q-value and secondary key of specificity ($\mbox{\lq n/m\rq} > \mbox{\lq n/*\rq} > \mbox{\lq*/*\rq}$).
\item Set $M=\{\}$. For each member of $A, a$:
\begin{itemize}
\item For each member of $P, p$:
\begin{itemize}
\item If $a$ is compatible with $p$, add $S(a,p)$ to $M$, where the function $S$ returns the most specific media type of the supplied list.
\end{itemize}
\end{itemize}
\item If $M = \{\}$ then return a not acceptable response (HTTP 406 status), finish.
\item For each member of $M, m$:
\begin{itemize}
\item If $m$ is a concrete type, set $M_{\mbox{selected}} = m$, finish.
\end{itemize}
\item If $M$ contains \lq*/*\rq\ or \lq application/*\rq, set $M_{\mbox{selected}} = \mbox{\lq application/octet-stream\rq}$, finish.
\item Return a not acceptable response (HTTP 406 status), finish.
\end{enumerate}
Note that the above renders a response with a default media type of \lq application/octet-stream\rq\ when a concrete type cannot be determined. It is RECOMMENDED that \MsgWrite\ implementations specify at least one concrete type via \ProduceMime.