This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathresources.tex
More file actions
618 lines (451 loc) · 42.9 KB
/
resources.tex
File metadata and controls
618 lines (451 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
\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 Section \ref{resource_field}), 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. 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 is suitable then an implementation MUST use the one with the most parameters. Choosing amongst suitable constructors with the same number of parameters is implementation specific, implementations SHOULD generate a warning about such ambiguity.
Non-root resource classes are instantiated by an application and do not require the above-described public constructor.
\section{Fields and Bean Properties}
\label{resource_field}
When a resource class is instantiated, the values of fields and bean properties annotated with one the following annotations are set 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}
Because injection occurs at object creation time, use of these annotations (with the exception of \Context) on resource class fields and bean properties is only supported for the default per-request resource class lifecycle. An implementation SHOULD warn if resource classes with other lifecycles use these annotations on resource class fields or bean properties.
A \jaxrs\ implementation is only required to set the annotated field and bean property values of instances created by its runtime. Objects returned by sub-resource locators (see Section \ref{sub_resources}) are expected to be initialized by their creator.
Valid parameter types for each of the above annotations are listed in the corresponding Javadoc, however in general (excluding \Context) the following types are supported:
\begin{enumerate}
\item\label{paramconverter} Types for which a \ParamConverter\ is available via a registered \ParamConverterProvider. See Javadoc for these classes for more information.
\item Primitive types.
\item\label{stringctor} Types that have a constructor that accepts a single \code{String} argument.
\item\label{valueofmethod} Types that have a static method named \code{valueOf} or \code{fromString} with a single \code{String} argument that return an instance of the type. If both methods are present then \code{valueOf} MUST be used unless the type is an enum in which case \code{fromString} MUST be used\footnote{Due to limitations of the built-in \code{valueOf} method that is part of all Java enumerations, a \code{fromString} method is often defined by the enum writers. Consequently, the \code{fromString} method is preferred when available.}.
\item \code{List<{\em T}>}, \code{Set<{\em T}>}, or \code{SortedSet<{\em T}>}, where \code{{\em T}} satisfies \ref{paramconverter}, \ref{stringctor} or \ref{valueofmethod} above.
\end{enumerate}
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 fields and properties.
A \WebAppExc\ thrown during construction of field or property values using any of the 5 steps listed above is processed directly as described in Section \ref{method_exc}. Other exceptions thrown during construction of field or property values using any of the 5 steps listed above are treated as client errors: if the field or property is annotated with \MatrixParam, \QueryParam\ or \PathParam\ then an implementation MUST generate an instance of \code{NotFoundException} (404 status) that wraps the thrown exception and no entity; if the field or property is annotated with \HeaderParam\ or \CookieParam\ then an implementation MUST generate an instance of \code{BadRequestException} (400 status) that wraps the thrown exception and no entity. Exceptions MUST be processed as described in Section \ref{method_exc}.
\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{@PATCH}, \code{@HEAD} and \code{@OPTIONS}. Users may define their own custom request method designators including alternate designators for the common HTTP methods.
\subsection{Visibility}
\label{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 \FormParam\ or one of the annotations listed in Section \ref{resource_field} are mapped from the request according to the semantics of the annotation. Similar to fields and bean properties:
\begin{itemize}
\item The \code{Default\-Value} annotation may be used to supply a default value for parameters
\item The \code{Encoded} annotation may be used to disable automatic URI decoding of parameter values
\item Exceptions thrown during construction of parameter values are treated the same as exceptions thrown during construction of field or bean property values, see Section \ref{resource_field}. Exceptions thrown during construction of \FormParam\ annotated parameter values are treated the same as if the parameter were annotated with \HeaderParam.
\end{itemize}
\subsubsection{Entity Parameters}
\label{entity_parameters}
The value of a parameter not annotated with \FormParam\ or any of the annotations listed in in Section \ref{resource_field}, called the entity parameter, is mapped from the request entity body. Conversion between an entity body and a Java type is the responsibility of an entity provider, see Section \ref{entity_providers}. Resource methods MUST have at most one entity parameter.
\subsection{Return Type}
\label{resource_method_return}
Resource methods MAY return \code{void}, \Response, \code{Generic\-Entity}, 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 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. If the status property of the \Response\ is not set: a 200 status code is used for a non-\code{null} entity property and a 204 status code is used if the entity property is \code{null}.
\item[\code{Generic\-Entity}] Results in an entity body mapped from the \code{Entity} property of the \code{Generic\-Entity}. 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.
\item[Other] Results in an entity body mapped from the class of the returned instance or of its type parameter \code{T} if the return type is \code{CompletionStage<T>} (see Section \ref{completionstage}); if the class is an anonymous inner class, its superclass is used instead. 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}
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.
Conversion between a Java object and an entity body is the responsibility of an entity provider, see Section \ref{entity_providers}. The return type of a resource method and the type of the returned instance are used to determine the raw type and generic type supplied to the \code{isWritable} method of \MsgWrite\ as follows:
\begin{longtable}{|l|l|l|l|}
\hline
\bfseries Return Type & \bfseries Returned Instance\footnotemark & \bfseries Raw Type & \bfseries Generic Type
\tabularnewline
\hline\hline\endhead
\code{GenericEntity} & \code{GenericEntity} or subclass & \code{RawType} property & \code{Type} property \tabularnewline
\hline
\code{Response} & \code{GenericEntity} or subclass & \code{RawType} property & \code{Type} property \tabularnewline
\hline
\code{Response} & \code{Object} or subclass & Class of instance & Class of instance \tabularnewline
\hline
\code{Other} & Return type or subclass & Class of instance & Generic type of return type \tabularnewline
\hline
\caption{Determining raw and generic types of return values}
\end{longtable}
\footnotetext{Or \code{Entity} property of returned instance if return type is \Response\ or a subclass thereof.}
To illustrate the above consider a method that always returns an instance of \code{ArrayList<String>} either directly or wrapped in some combination of \Response\ and \code{GenericEntity}. The resulting raw and generic types are shown below.
\begin{longtable}{|l|l|l|l|}
\hline
\bfseries Return Type & \bfseries Returned Instance & \bfseries Raw Type & \bfseries Generic Type
\tabularnewline
\hline\hline\endhead
\code{GenericEntity} & \code{GenericEntity<List<String>>} & \code{ArrayList<?>} & \code{List<String>} \tabularnewline
\hline
\code{Response} & \code{GenericEntity<List<String>>} & \code{ArrayList<?>} & \code{List<String>} \tabularnewline
\hline
\code{Response} & \code{ArrayList<String>} & \code{ArrayList<?>} & \code{ArrayList<?>} \tabularnewline
\hline
\code{List<String>} & \code{ArrayList<String>} & \code{ArrayList<?>} & \code{List<String>} \tabularnewline
\hline
\caption{Example raw and generic types of return values}
\end{longtable}
\subsection{Exceptions}
\label{method_exc}
A resource method, sub-resource method or sub-resource locator may throw any checked or unchecked exception. An implementation MUST catch all exceptions and process them in the following order:
\begin{enumerate}
\item Instances of \WebAppExc\ and its subclasses MUST be mapped to a response as follows. If the \code{response} property of the exception does not contain an entity and an exception mapping provider (see Section \ref{exceptionmapper}) is available for \WebAppExc\ or the corresponding subclass, an implementation MUST use the provider to create a new \Response\ instance, otherwise the \code{response} property is used directly. The resulting \Response\ instance is then processed according to Section \ref{resource_method_return}.
\item If an exception mapping provider (see Section \ref{exceptionmapper}) is available for the exception or one of its superclasses, an implementation MUST use the provider whose generic type is the nearest superclass of the exception to create a \Response\ instance that is then processed according to Section \ref{resource_method_return}. If the exception mapping provider throws an exception while creating a \Response\ then return a server error (status code 500) response to the client.
\item\label{runtimeexc} Unchecked exceptions and errors that have not been mapped MUST be re-thrown and allowed to propagate to the underlying container.
\item\label{checkedexc} Checked exceptions and throwables that have not been mapped and cannot be thrown directly MUST be wrapped in a container-specific exception that is then thrown and allowed to propagate to the underlying container. Servlet-based implementations MUST use \code{Servlet\-Exception} as the wrapper. JAX-WS \code{Provider}-based implementations MUST use \code{Web\-Service\-Exception} as the wrapper.
\end{enumerate}
\begin{nnnote}Items \ref{runtimeexc} and \ref{checkedexc} allow existing container facilities (e.g. a Servlet filter or error pages) to be used to handle the error if desired.\end{nnnote}
\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 using the metadata provided by the \jaxrs\ annotations on the matching class and its methods.
\end{enumerate}
\section{URI Templates}
\label{uritemplates}
A root 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 combination of the deployment context and the application path (see the \code{@Application\-Path} annotation).
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. The Javadoc for the \Path\ annotation describes their syntax. 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 value of the annotation is automatically encoded, e.g. the following two lines are equivalent:
\begin{listing}{1}
@Path("widget list/{id}")
@Path("widget%20list/{id}")
\end{listing}
Template parameters can optionally specify the regular expression used to match their values. The default value matches any text and terminates at the end of a path segment but other values can be used to alter this behavior, e.g.:
\begin{listing}{1}
@Path("widgets/{path:.+}")
public class Widget {
...
}\end{listing}
In the above example the \code{Widget} resource class will be matched for any request whose path starts with \code{widgets} and contains at least one more path segment; 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}.
The value of a URI path parameter is available for injection via \PathParam\ on a field, property or method parameter. Note that if a URI template is used on a method, a path parameter injected in a field or property may not be available (set to \code{null}). The following example illustrates this scenario:
\begin{listing}{1}
@Path("widgets")
public class WidgetsResource {
@PathParam("id") String id;
@GET
public WidgetList getWidgets() {
... // id is null here
}
@GET
@Path("{id}")
public Widget findWidget() {
return new WidgetResource(id);
}
}\end{listing}
\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. Sub-resource methods handle a HTTP request directly whilst sub-resource locators return an object or class that will handle a HTTP request. The presence or absence of a request method designator (e.g. @GET) differentiates between the two:
\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 dynamically resolve the object that will handle the request. Sub-resource locators can return objects or classes; if a class is returned then an object is obtained by the implementation using a {\em suitable} constructor as described in Section \ref{resource_class_constructor}. In either case, the resulting object is used to handle the request or to further resolve the object that will handle the request, see \ref{mapping_requests_to_java_methods} for further details.
When an object is returned, implementations MUST dynamically determine its class rather than relying on the static sub-resource locator return type, since the returned instance may be a subclass of the declared type with potentially different annotations, see Section \ref{annotationinheritance} for rules on annotation inheritance. Sub-resource locators may have all the same parameters as a normal resource method (see Section \ref{resource_method}) except that they MUST NOT have an entity parameter.
\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(@PathParam("id") String id) {
return new WidgetResource(id);
}
}
public class WidgetResource {
public WidgetResource(String id) {...}
@GET
public Widget getDetails() {...}
}\end{listing}
In the above a \code{GET} request for the \code{widgets/offers} resource is handled directly by the \code{get\-Discounted} sub-resource method of the resource class \code{Widgets\-Resource} whereas a \code{GET} request for \code{widgets/{\em xxx}} is handled by the \code{get\-Details} method of the \code{Widget\-Resource} resource class.
\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 \Consumes\ and \Produces\ annotations respectively. 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 use of these annotations:
\begin{listing}{1}
@Path("widgets")
@Produces("application/widgets+xml")
public class WidgetsResource {
@GET
public Widgets getAsXML() {...}
@GET
@Produces("text/html")
public String getAsHtml() {...}
@POST
@Consumes("application/widgets+xml")
public void addWidget(Widget widget) {...}
}
@Provider
@Produces("application/widgets+xml")
public class WidgetsProvider implements MessageBodyWriter<Widgets> {...}
@Provider
@Consumes("application/widgets+xml")
public class WidgetProvider implements MessageBodyReader<Widget> {...}
\end{listing}
In the above:
\begin{itemize}
\item The \code{getAsXML} resource method will be called for \code{GET} requests that specify a response media type of \code{application/widgets+xml}. It returns a \code{Widgets} instance that will be mapped to that format using the \code{WidgetsProvider} class (see Section \ref{entity_providers} for more information on \MsgWrite).
\item The \code{getAsHtml} resource method will be called for \code{GET} requests that specify a response media type of \code{text/html}. It returns a \code{String} containing \code{text/html} that will be written using the default implementation of \code{MessageBodyWriter<String>}.
\item The \code{addWidget} resource method will be called for \code{POST} requests that contain an entity of the media type \code{application/widgets+xml}. The value of the \code{widget} parameter will be mapped from the request entity using the \code{WidgetProvider} class (see Section \ref{entity_providers} for more information on \MsgRead).
\end{itemize}
An implementation MUST NOT invoke a method whose effective value of \Produces\ does not match the request \code{Accept} header. An implementation MUST NOT invoke a method whose effective value of \Consumes\ does not match the request \code{Content-Type} header.
When accepting multiple media types, clients may indicate preferences by using a relative quality factor known as the q parameter. The value of the q parameter, or q-value, is used to sort the set of accepted types. For example, a client may indicate preference for \code{application/widgets+xml} with a relative quality factor of 1 and for \code{application/xml} with a relative quality factor of 0.8. Q-values range from 0 (undesirable) to 1 (highly desirable), with 1 used as default when omitted. A \code{GET} request matched to the \code{WidgetsResource} class with an accept header of \code{text/html; q=1, application/widgets+xml; q=0.8} will result in a call to method \code{getAsHtml} instead of \code{getAsXML} based on the value of q.
A server can also indicate media type quality using the qs parameter. Consider the following example:
\begin{listing}{1}
@Path("widgets2")
public class WidgetsResource2 {
@GET
@Produces("application/xml", "application/json")
public Widgets getWidget() {...}
}
\end{listing}
Suppose a client issues a \code{GET} request with an accept header of \code{application/*; q=0.5, text/html}. Based on this request, the server determines that both \code{application/xml} and \code{application/json} are equally preferred by the client with a q-value of 0.5. By specifying a server quality factor as part of the \Produces\ annotation, it is possible to control which response media type to select:
\begin{listing}{1}
@Path("widgets2")
public class WidgetsResource2 {
@GET
@Produces("application/xml; qs=1", "application/json; qs=0.75")
public Widgets getWidget() {...}
}
\end{listing}
With the updated value for \Produces\ in this example, and in response to a \code{GET} request with an accept header that includes \code{application/*; q=0.5}, JAX-RS implementations are REQUIRED to select the media type \code{application/xml} given its higher qs-value. Note that qs-values are multiplied with the q-value to determine if this media type is the most preferred. This allows for the behaviour as shown in the first example of \href{https://tools.ietf.org/html/rfc7231#section-5.3.2}{RFC 7231, Section 5.3.2}. For more information on media type selection see Section~\ref{determine_response_type}.
\section{Annotation Inheritance}
\label{annotationinheritance}
\jaxrs\ annotations may be used on the methods and method parameters of a super-class or an implemented interface. Such annotations are inherited by a corresponding sub-class or implementation class method provided that the method and its parameters do not have any \jaxrs\ annotations of their own. Annotations on a super-class take precedence over those on an implemented interface. The precedence over conflicting annotations defined in multiple implemented interfaces is implementation specific. Note that inheritance of class or interface annotations is not supported.
If a subclass or implementation method has any \jaxrs\ annotations then {\em all} of the annotations on the superclass or interface method are ignored. E.g.:
\begin{listing}{1}
public interface ReadOnlyAtomFeed {
@GET @Produces("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 \Produces\ annotations from the interface. Conversely:
\begin{listing}{1}
@Path("feed")
public class ActivityLog implements ReadOnlyAtomFeed {
@Produces("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 \Produces\ annotation.
For consistency with other Java EE specifications, it is recommended to always repeat annotations instead of relying on annotation inheritance.
\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. Implementations are not required to use the algorithm as written but MUST produce results equivalent to those produced by the algorithm.
\subsection{Request Preprocessing}
\label{reqpreproc}
Prior to matching, request URIs are normalized\footnote{Note: some containers might perform this functionality prior to passing the request to an implementation.} by following the rules for case, path segment, and percent encoding normalization described in section 6.2.2 of RFC 3986\cite{uri}. The normalized request URI MUST be reflected in the URIs obtained from an injected \code{UriInfo}.
\subsection{Request Matching}
\label{request_matching}
A request is matched to the corresponding resource method or sub-resource method by comparing the normalized request URI (see Section \ref{reqpreproc}), 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. All exceptions reported by this algorithm MUST be processed as described in Section \ref{method_exc}.
Matching of requests to resource methods proceeds in three stages as follows:
\begin{enumerate}
\item Identify a set of candidate root resource classes matching the request:
\begin{description}
\item[Input] $U=\mbox{request URI path},C=\{\mbox{root resource classes}\}$
\item[Output] $U=\mbox{final capturing group not yet matched}, C'=\{\mbox{root resouce classes matched so far}\}$
\end{description}
\begin{enumerate}
\item Set $E=\{\}$.
\item For each class $Z$ 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\label{build_E} Add $R(T_Z)$ where $T_Z$ is the URI path template specified for the class $Z$.
\end{itemize}
Note that two or more classes in $C$ may add the same regular expression to $E$ if they are
annotated with the same URI path template (modulo variable names).
\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 regular expression capturing group (henceforth simply referred to as a capturing group) value is neither empty nor \lq/\rq\ and the class $Z$ has 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 \code{NotFoundException} (404 status) and no entity.
\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), the number of capturing groups as a secondary key (descending order) and the number of capturing groups with non-default regular expressions (i.e. not \lq([\^{ }/]+?)\rq) as the tertiary key (descending order).
\item Set $R_{\mbox{match}}$ to be the first member of $E$ and set $U$ to be the value of the
final capturing group of $R_{\mbox{match}}$ when matched against $U$. Let $C'$ be the set
of classes $Z$ such that $R(T_Z)=R_{\mbox{match}}$. By definition, all root resource
classes in $C'$ must be annotated with the same URI path template modulo variable names.
\end{enumerate}
\item \label{find_object} Obtain a set of candidate resource methods for the request:
\begin{description}
\item[Input] $U=\mbox{final capturing group not yet matched}, C'=\{\mbox{root resouce classes matched so far}\}$
\item[Output] $M=\{\mbox{candidate resource methods}$\}
\end{description}
\begin{enumerate}
\item \label{check_null} If $U$ is null or \lq/\rq, set
$$M = \{\mbox{resource methods of all classes in $C'$ (excluding sub-resource methods)}\}$$
and go to step \ref{find_method} if $M \neq \{\}$
\item Set $E=\{\}$.
\item For each class $Z'$ in $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 $D$, add $R(T_D)$ where $T_D$ is the URI path template of the sub-resource method.
\item For each sub-resource locator $L$, add $R(T_L)$ where $T_L$ 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_D$ (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 and the algorithm terminates by generating a \code{NotFoundException} (404 status) and no entity.
\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), the number of capturing groups with non-default regular expressions (i.e. not \lq([\^{ }/]+?)\rq) as the tertiary key (descending order), and the source of each member as quaternary key sorting those derived from sub-resource methods ahead of those derived from sub-resource locators.
\item Set $R_{\mbox{match}}$ to be the first member of $E$
\item Set $M$ as follows,
$$M = \{\mbox{subresource methods of all classes in $C'$ (excluding sub-resource locators)}\}$$
and go to step \ref{find_method} if $M \neq \{\}$.
\item Let $L$ be a sub-resource locator such that $R_{\mbox{match}} = R(T_L)$. Implementations SHOULD report an error if there is more than one sub-resource locator that satisfies this condition. Set $U$ to be the value of the final capturing group of $R(T_L)$ when matched against $U$, and set $C'$ to be the singleton set containing only the class that defines $L$.
\item Go to step \ref{check_null}.
\end{enumerate}
\item \label{find_method} Identify the method that will handle the request:
\begin{description}
\item[Input] $M=\mbox{candidate resource methods}$
\item[Output] $O=\mbox{instance of resource class matched}, D=\mbox{resource method matched from $M$}$
\end{description}
\begin{enumerate}
\item \label{filter_methods} Filter $M$ by removing members that do not meet the following criteria:
\begin{itemize}
\item The request method is supported. If no methods support the request method an implementation MUST generate a \code{NotAllowedException} (405 status) and no entity. 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 a \code{NotSupportedException} (415 status) and no entity.
\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 \code{NotAcceptableException} (406 status) and no entity.
\end{itemize}
\newcommand{\bottom}{\perp}
\item If after filtering the set $M$ has more than one element, sort it in descending order as follows. First, let us
define the {\em client} media type and the {\em server} media type as those denoted by the \code{Accept} header in
a request and the \code{@Produces} annotation on a resource method, respectively.
Let a client media type be of the form $\mbox{$n$/$m$;q=$v_1$}$, a server media type be of the form $\mbox{$n$/$m$;qs=$v_2$}$ and a {\em combined} media type of the form $\mbox{$n$/$m$;q=$v_1$;qs=$v_2$;d=$v_3$}$, where the distance factor $d$ is defined below. For any of these types, $m$ could be $*$, or $m$ and $n$ could be $*$ and the values of q and qs are assumed to be $1.0$ if absent.
Let $S(p_1, p_2)$ be defined over a client media type $p_1$ and a server media type $p_2$ as the function that returns the {\em most} specific combined type with a distance factor if $p_1$ and $p_2$ are compatible and $\bottom$ otherwise. For example:
\begin{itemize}
\item $S(\mbox{text/html;q=1}, \mbox{text/html;qs=1}) = \mbox{text/html;q=1;qs=1;d=0}$,
\item $S(\mbox{text/*;q=0.5}, \mbox{text/html;qs=0.8}) = \mbox{text/html;q=0.5;qs=0.8;d=1}$,
\item $S(\mbox{*/*;q=0.2}, \mbox{text/*;qs=0.9}) = \mbox{text/*;q=0.2;qs=0.9;d=1}$,
\item $S(\mbox{text/*;q=0.4}, \mbox{application/*;qs=0.3}) = \bottom$.
\end{itemize}
where the $d$ factor corresponds to the number of wildcards matched with a concrete type or subtype.
Note that q and qs are not matched, but simply combined in the resulting media type. A total ordering can be defined over combined media types as follows.
We write $\mbox{$n_1$/$m_1$;q=$v_1$;qs=$v_1'$;d=$v_1''$} \ge \mbox{$n_2$/$m_2$;q=$v_2$;qs=$v_2'$;d=$v_2''$}$ if one of these ordered conditions holds:
\begin{enumerate}
\item $\mbox{$n_1$/$m_1$} \succ \mbox{$n_2$/$m_2$}$ where the partial order $\succ$ is defined as $\mbox{$n$/$m$} \succ \mbox{$n$/*} \succ \mbox{*/*}$,
\item $\mbox{$n_2$/$m_2$} \nsucc \mbox{$n_1$/$m_1$}$ and $v_1 \cdot v_1' > v_2 \cdot v_2'$,
\item $\mbox{$n_2$/$m_2$} \nsucc \mbox{$n_1$/$m_1$}$ and $v_1 \cdot v_1' = v_2 \cdot v_2'$ and $v_1 > v_2$.
\item $\mbox{$n_2$/$m_2$} \nsucc \mbox{$n_1$/$m_1$}$ and $v_1 \cdot v_1' = v_2 \cdot v_2'$ and $v_1 = v_2$ and $v_1'' \le v_2''$.
\end{enumerate}
Note that $\ge$ is a total order even though $\succ$ is a partial order. For example, the following holds $\mbox{text/html;q=1.0;qs=0.7;d=0} \ge \mbox{application/xml;q=1.0;qs=0.2;d=0}$ even though $\mbox{text/html}$ is incomparable to $\mbox{application/xml}$ according to $\succ$. Additionally, it is possible under $\ge$ for two types to be equal even though they are not identical~\footnoteremember{equality}{E.g., $\mbox{text/html;q=1.0;qs=0.7;d=0} \ge \mbox{application/xml;q=1.0;qs=0.7;d=0}$ and $\mbox{application/xml;q=1.0;qs=0.7;d=0} \ge \mbox{text/html;q=1.0;qs=0.7;d=0}$.}. For convenience, we defined $p \ge \bottom$ for every media type $p$.
Given these definitions, we can now sort $M$ in descending order based on $\ge$ as follows\footnote{If any of these types or sets of types are unspecified, $\mbox{*/*}$ and $\mbox{\{*/*\}}$ are assumed.}:
\begin{itemize}
\item Let $t$ be the request content type and $C_M$ a resource method's \Consumes\ set of server media types, we use the media type $\max_\ge \{ S(t,c) \, | \, (t, c) \in \{t\} \times C_M\}$ as primary key.
\item Let $A$ be the request accept header set of client media types and $P_M$ a resource method's \Produces\ set of server media types, we use the media type $\max_\ge \{ S(a,p) \, | \, (a,p) \in A \times P_M\}$ as secondary key. If there is more than one maximum element \footnoterecall{equality}, implementations SHOULD report a warning and select one of these types in an implementation dependent manner.
\end{itemize}
\item \label{dispatch_method} Let $D$ be the first resource method in the set $M$\footnote{Step \ref{filter_methods} ensures the set contains at least one member.} and $O$ an instance of the class that defines $D$. If after sorting, there is more than one maximum element in $M$, implementations SHOULD report a warning and select one of these methods in an implementation dependent manner.
\end{enumerate}
Consider the following example and assume the request to be \code{GET} \code{widgets/1}:
\begin{listing}{1}
@Path("widget")
public class WidgetResource {
private String id;
public WidgetResource() {
this("0");
}
public WidgetResource(String id) {
this.id = id;
}
@GET
public Widget findWidget() {
return Widget.findWidgetById(id);
}
}
@Path("widgets")
public class WidgetsResource {
@Path("{id}")
public WidgetResource getWidget(@PathParam("id") String id) {
return new WidgetResource(id);
}
}
\end{listing}
The input and output values for each of the 3 steps in the matching algorithm are as follows:
\begin{description}
\item[Step 1] Identify a set of candidate root resource classes matching the request. Let $R(\mbox{widgets}) = \mbox{widgets(/.*)?}$ and $R(\mbox{widget}) = \mbox{widget(/.*)?}$,
\begin{description}
\item[Input] $U = \mbox{widgets/1}$ and $C = \{\mbox{WidgetResource}, \mbox{WidgetsResource}\}$
\item[Output] $U = \mbox{/1}$ and $C' = \{\mbox{WidgetsResource}\}$
\end{description}
\item[Step 2] Obtain a set of candidate resource methods for the request. Let $R(\{\mbox{id}\}) = \mbox{([\^{ }/]+?)(/.*)?}$,
\begin{description}
\item[Input] $U = \mbox{/1}$ and $C' = \{\mbox{WidgetsResource}\}$
\item[Output] $M = \{\mbox{findWidget}\}$
\end{description}
\item[Step 3] Identify the method that will handle the request,
\begin{description}
\item[Input] $M = \{\mbox{findWidget}\}$
\item[Output] $O = \mbox{WidgetResource instance}$ and $D = \mbox{findWidget}$
\end{description}
\end{description}
Note that the algorithm matches a single root resource class (WidgetsResource) and, consequently, the \code{@Path} annotation on WidgetResource is ignored for the request \code{GET} \code{widgets/1}.
\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 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 each URI template variable with a capturing group containing the specified regular expression or \lq([\^{ }/]+?)\rq\ if no regular expression is specified\footnote{Note that the syntax +? denotes a reluctant quantifier as defined in the java.util.regex.Pattern class.}.
\item If the resulting string ends with \lq/\rq\ then remove the final character.
\item 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{.getPathParameters}.
\section{Determining the MediaType of Responses}
\label{determine_response_type}
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 If the method returns an instance of \Response\ whose metadata includes the response media type ($M_{\mbox{specified}}$) then set $M_{\mbox{selected}} = M_{\mbox{specified}}$, finish.
\item Gather the set of producible media types $P$:
\begin{itemize}
\item If the method is annotated with \Produces, set $P = \{ V(\mbox{method}) \}$ where $V(t)$ represents the values of \Produces\ on the specified target $t$.
\item Else if the class is annotated with \Produces, 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 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 pair with the q-value of $a$ and server-side qs-value of $p$.
\end{itemize}
\end{itemize}
\item If $M = \{\}$ then generate a \code{NotAcceptableException} (406 status) and no entity. The exception MUST be processed as described in Section \ref{method_exc}. Finish.
\item Sort $M$ in descending order, with a primary key of specificity ($\mbox{n/m} > \mbox{n/*} > \mbox{*/*}$), a secondary key of the product of q and qs ($\mbox{q-value} \cdot \mbox{qs-value}$), and a tertiary key of q-value.
\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 Generate a \code{NotAcceptableException} (406 status) and no entity. The exception MUST be processed as described in Section \ref{method_exc}. 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 \Produces.