├── spec.pdf ├── styles ├── lineno.sty ├── jsrfrontstyle.tex ├── jsrmainstyle.tex ├── jsr.sty └── macros.tex ├── README.md ├── chapters ├── jaxrs_pipeline.odg ├── license_final.tex ├── pipeline_client.pdf ├── pipeline_server.pdf ├── refs.tex ├── diagrams.tex ├── titlepage.tex ├── delegate.tex ├── headers.tex ├── annotations.tex ├── sse.tex ├── context.tex ├── applications.tex ├── license.tex ├── environment.tex ├── asynchronous.tex ├── intro.tex ├── validation.tex ├── clientapi.tex ├── providers.tex ├── changes.tex └── filters.tex ├── .gitignore ├── Makefile ├── spec.tex └── references.bib /spec.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/spec.pdf -------------------------------------------------------------------------------- /styles/lineno.sty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/styles/lineno.sty -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JAX-RS Specification 2 | 3 | This repository contains JAX-RS specification sources. 4 | -------------------------------------------------------------------------------- /chapters/jaxrs_pipeline.odg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/chapters/jaxrs_pipeline.odg -------------------------------------------------------------------------------- /chapters/license_final.tex: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/chapters/license_final.tex -------------------------------------------------------------------------------- /chapters/pipeline_client.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/chapters/pipeline_client.pdf -------------------------------------------------------------------------------- /chapters/pipeline_server.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/javaee/jax-rs-spec/HEAD/chapters/pipeline_server.pdf -------------------------------------------------------------------------------- /chapters/refs.tex: -------------------------------------------------------------------------------- 1 | \raggedright 2 | \bibliographystyle{unsrt} 3 | \addcontentsline{toc}{chapter}{Bibliography} 4 | \bibliography{references} 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # maven noise 2 | target 3 | 4 | # osx noise 5 | .DS_Store 6 | profile 7 | 8 | #IntelliJ Idea noise 9 | .idea 10 | *.iws 11 | *.ipr 12 | *.iml 13 | 14 | # TeX build noise 15 | *.aux 16 | *.bbl 17 | *.blg 18 | *.log 19 | *.out 20 | *.tex~ 21 | *.thm 22 | *.toc 23 | spec.synctex.gz 24 | -------------------------------------------------------------------------------- /chapters/diagrams.tex: -------------------------------------------------------------------------------- 1 | \chapter{Processing Pipeline} 2 | \label{processing_pipeline} 3 | 4 | \begin{figure}[H] 5 | \label{pipeline_server} 6 | \centering 7 | \includegraphics{chapters/pipeline_server.pdf} 8 | \caption{JAX-RS Server Processing Pipeline.} 9 | \end{figure} 10 | 11 | \begin{figure}[t] 12 | \label{pipeline_client} 13 | \centering 14 | \includegraphics{chapters/pipeline_client.pdf} 15 | \caption{JAX-RS Client Processing Pipeline.} 16 | \end{figure} 17 | 18 | -------------------------------------------------------------------------------- /styles/jsrfrontstyle.tex: -------------------------------------------------------------------------------- 1 | % set up page styles for frontmatter, no page headers, normal footer 2 | \fancyhf{} 3 | \fancyfoot[CO,CE]{JAX-RS} 4 | \fancyfoot[LE,RO]{\thepage} 5 | \fancyfoot[RE,LO]{\today} 6 | \fancypagestyle{plain}{ 7 | \fancyhf{} 8 | \fancyfoot[CO,CE]{JAX-RS} 9 | \fancyfoot[LE,RO]{\thepage} 10 | \fancyfoot[RE,LO]{\today} 11 | \renewcommand{\footrulewidth}{0pt} 12 | \renewcommand{\headrulewidth}{0pt} 13 | } 14 | \renewcommand{\headrulewidth}{0pt} 15 | -------------------------------------------------------------------------------- /chapters/titlepage.tex: -------------------------------------------------------------------------------- 1 | \begin{titlepage} 2 | \raggedleft 3 | 4 | \vspace*{60pt} 5 | 6 | {\Huge 7 | \textsf{JAX-RS: Java\texttrademark\ API for RESTful\\\vspace{10pt} 8 | Web Services}} 9 | 10 | \vspace{20pt} 11 | 12 | { 13 | \Large\textit{Version 2.1 Proposed Final Draft\\ 14 | \today} 15 | } 16 | 17 | \vspace{40pt} 18 | 19 | {\large Editors:\\ 20 | Pavel Bucek\\ 21 | Santiago\ Pericas-Geertsen\\ 22 | \vspace{10pt}Comments to: jaxrs-spec@javaee.groups.io 23 | } 24 | 25 | \vspace{80pt} 26 | 27 | {\small\textit{Oracle Corporation\\ 28 | 500 Oracle Parkway, Redwood Shores, CA 94065 USA.} 29 | } 30 | \end{titlepage} 31 | -------------------------------------------------------------------------------- /styles/jsrmainstyle.tex: -------------------------------------------------------------------------------- 1 | % set up page styles for mainmatter, page headers and normal footer 2 | \renewcommand{\chaptermark}[1]{ 3 | \markboth{\chaptername 4 | \ \thechapter.\ #1}{}} 5 | \renewcommand{\sectionmark}[1]{ 6 | \markright{\thesection.\ #1}{}} 7 | \fancyhf{} 8 | \fancyhead[RO]{\slshape \rightmark} 9 | \fancyhead[LE]{\slshape \leftmark} 10 | \fancyfoot[CO,CE]{JAX-RS} 11 | \fancyfoot[LE,RO]{\thepage} 12 | \fancyfoot[RE,LO]{\today} 13 | \fancypagestyle{plain}{ 14 | \fancyhf{} 15 | \fancyfoot[CO,CE]{JAX-RS} 16 | \fancyfoot[LE,RO]{\thepage} 17 | \fancyfoot[RE,LO]{\today} 18 | \renewcommand{\footrulewidth}{0pt} 19 | \renewcommand{\headrulewidth}{0pt} 20 | } 21 | \renewcommand{\headrulewidth}{0.4pt} 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | 3 | SOURCES=spec.tex \ 4 | styles/jsr.sty \ 5 | styles/jsrfrontstyle.tex \ 6 | styles/jsrmainstyle.tex \ 7 | styles/lineno.sty \ 8 | styles/macros.tex \ 9 | styles/ntheorem.sty \ 10 | chapters/titlepage.tex \ 11 | chapters/license.tex \ 12 | chapters/intro.tex \ 13 | chapters/applications.tex \ 14 | chapters/resources.tex \ 15 | chapters/providers.tex \ 16 | chapters/context.tex \ 17 | chapters/environment.tex \ 18 | chapters/delegate.tex \ 19 | chapters/annotations.tex \ 20 | chapters/headers.tex \ 21 | chapters/changes.tex \ 22 | chapters/refs.tex \ 23 | references.bib 24 | 25 | all: spec.pdf 26 | 27 | spec.pdf: ${SOURCES} 28 | pdflatex spec.tex 29 | bibtex spec.aux 30 | pdflatex spec.tex 31 | pdflatex spec.tex 32 | 33 | clean: 34 | rm -f spec.aux spec.bbl spec.blg spec.log spec.out spec.pdf spec.thm spec.toc 35 | rm -f chapters/*.aux styles/*.aux 36 | -------------------------------------------------------------------------------- /spec.tex: -------------------------------------------------------------------------------- 1 | \documentclass[11pt]{book} 2 | \usepackage[hyperref, thmmarks]{styles/ntheorem} 3 | \usepackage{framed} 4 | \usepackage{times} 5 | \usepackage{textcomp} 6 | \usepackage{tabularx} 7 | \usepackage{moreverb} 8 | \usepackage[pdftex]{graphicx} 9 | \usepackage{amssymb} 10 | \usepackage{float} 11 | \usepackage[pdftex, 12 | pdftitle={JAX-RS: Java API for RESTful Web Services}, 13 | pdfauthor={Santiago Pericas-Geertsen and Pavel Bucek, Oracle}, 14 | pdfsubject={JAX-RS: Java API for RESTful Web Services}, 15 | pdfkeywords={Java XML Web Services API REST RESTful}, 16 | pdftex, 17 | colorlinks=true, 18 | linkcolor=black, 19 | citecolor=black, 20 | pdfstartview=FitH, 21 | letterpaper=true, 22 | bookmarksnumbered=true 23 | ]{hyperref} 24 | 25 | % set up page dimensions 26 | \textwidth = 6.5 in 27 | \textheight = 9.33 in 28 | \oddsidemargin = 0.0 in 29 | \evensidemargin = 0.0 in 30 | \topmargin = -0.75 in 31 | \headheight = 15pt 32 | \headsep = 0.33 in 33 | \parskip = 6pt 34 | \parindent = 0.0in 35 | \footskip=0.5in 36 | 37 | \usepackage{fancyhdr} 38 | \pagestyle{fancy} 39 | \usepackage{styles/jsr} 40 | \theoremstyle{plain} 41 | %\setlength{\theorempostskipamount}{0pt} 42 | \newtheorem{ednote}{Editors Note}[chapter] 43 | 44 | \theoremstyle{nonumberplain} 45 | \theoremindent0cm 46 | \theoremseparator{:} 47 | \newtheorem{nnnote}{Note}[chapter] 48 | 49 | %\usepackage[pagewise, right]{styles/lineno} 50 | %\usepackage[dvips]{changebar} 51 | \usepackage{longtable} 52 | 53 | %\renewcommand{\today}{September 8, 2008} 54 | 55 | \begin{document} 56 | 57 | \frontmatter 58 | \include{styles/macros} 59 | \include{styles/jsrfrontstyle} 60 | 61 | \include{chapters/titlepage} 62 | 63 | \cleardoublepage 64 | { 65 | \small 66 | %\include{chapters/license} 67 | %\include{chapters/license_final} 68 | } 69 | 70 | \pdfbookmark[0]{Contents}{toc} 71 | \tableofcontents 72 | 73 | \mainmatter 74 | \include{styles/jsrmainstyle} 75 | 76 | %\linenumbers 77 | %\nochangebars 78 | 79 | \setcounter{secnumdepth}{4} 80 | 81 | \newcommand{\footnoteremember}[2]{\footnote{#2}\newcounter{#1}\setcounter{#1}{\value{footnote}}} 82 | \newcommand{\footnoterecall}[1]{\footnotemark[\value{#1}]} 83 | 84 | \include{chapters/intro} 85 | \include{chapters/applications} 86 | \include{chapters/resources} 87 | \include{chapters/providers} 88 | \include{chapters/clientapi} 89 | \include{chapters/filters} 90 | \include{chapters/validation} 91 | \include{chapters/asynchronous} 92 | \include{chapters/sse} 93 | \include{chapters/context} 94 | \include{chapters/environment} 95 | \include{chapters/delegate} 96 | 97 | \appendix 98 | \renewcommand{\chaptermark}[1]{ 99 | \markboth{\appendixname 100 | \ \thechapter.\ #1}{}} 101 | 102 | \include{chapters/annotations} 103 | \include{chapters/headers} 104 | \include{chapters/diagrams} 105 | \include{chapters/changes} 106 | 107 | \backmatter 108 | 109 | \include{chapters/refs} 110 | 111 | \end{document} 112 | -------------------------------------------------------------------------------- /styles/jsr.sty: -------------------------------------------------------------------------------- 1 | \NeedsTeXFormat{LaTeX2e}[1996/06/01] 2 | \ProvidesPackage{styles/jsr}[2003/04/29 v1.0 (MJH)] 3 | 4 | \def\@chapter[#1]#2{\ifnum \c@secnumdepth >\m@ne 5 | \if@mainmatter 6 | \refstepcounter{chapter}% 7 | \typeout{\@chapapp\space\thechapter.}% 8 | \addcontentsline{toc}{chapter}% 9 | {\protect\numberline{\thechapter}#1}% 10 | \else 11 | \addcontentsline{toc}{chapter}{#1}% 12 | \fi 13 | \else 14 | \addcontentsline{toc}{chapter}{#1}% 15 | \fi 16 | \chaptermark{#1}% 17 | \addtocontents{lof}{\protect\addvspace{10\p@}}% 18 | \addtocontents{lot}{\protect\addvspace{10\p@}}% 19 | \if@twocolumn 20 | \@topnewpage[\@makechapterhead{#2}]% 21 | \else 22 | \@makechapterhead{#2}% 23 | \@afterheading 24 | \fi} 25 | \def\@makechapterhead#1{% 26 | \vspace*{50\p@}% 27 | {\parindent \z@ \raggedleft \sffamily 28 | \ifnum \c@secnumdepth >\m@ne 29 | \if@mainmatter 30 | \huge\bfseries \@chapapp\space \thechapter 31 | \par\nobreak 32 | \vskip 20\p@ 33 | \fi 34 | \fi 35 | \interlinepenalty\@M 36 | \Huge \bfseries #1\par\nobreak 37 | \vskip 40\p@ 38 | }} 39 | \def\@schapter#1{\if@twocolumn 40 | \@topnewpage[\@makeschapterhead{#1}]% 41 | \else 42 | \@makeschapterhead{#1}% 43 | \@afterheading 44 | \fi} 45 | \def\@makeschapterhead#1{% 46 | \vspace*{50\p@}% 47 | {\parindent \z@ \raggedleft 48 | \sffamily 49 | \interlinepenalty\@M 50 | \Huge \bfseries #1\par\nobreak 51 | \vskip 40\p@ 52 | }} 53 | 54 | \def\verbatim@font{\small\ttfamily} 55 | 56 | \renewcommand{\chapter}{\if@openright\cleardoublepage\else\clearpage\fi 57 | \thispagestyle{plain}% 58 | \global\@topnum\z@ 59 | \@afterindentfalse 60 | \secdef\@chapter\@schapter} 61 | \renewcommand{\section}{\@startsection {section}{1}{0pt}% 62 | {-3.5ex \@plus -1ex \@minus -.2ex}% 63 | {2.3ex \@plus.2ex}% 64 | {\sffamily\Large\bfseries}} 65 | 66 | \renewcommand{\subsection}{\@startsection{subsection}{2}{0pt}% 67 | {-3.25ex\@plus -1ex \@minus -.2ex}% 68 | {1.5ex \@plus .2ex}% 69 | {\sffamily\large\bfseries}} 70 | 71 | \renewcommand{\subsubsection}{\@startsection{subsubsection}{3}{0pt}% 72 | {-3.25ex\@plus -1ex \@minus -.2ex}% 73 | {1.5ex \@plus .2ex}% 74 | {\sffamily\normalsize\bfseries}} 75 | -------------------------------------------------------------------------------- /chapters/delegate.tex: -------------------------------------------------------------------------------- 1 | \chapter{Runtime Delegate} 2 | \label{runtimedelegate} 3 | 4 | \rd\ is an abstract factory class that provides various methods for the creation of objects that implement \jaxrs\ APIs. These methods are designed for use by other \jaxrs\ API classes and are not intended to be called directly by applications. \rd\ allows the standard \jaxrs\ API classes to use different \jaxrs\ implementations without any code changes. 5 | 6 | An implementation of \jaxrs\ MUST provide a concrete subclass of \rd. Using the supplied \rd\ this can be provided to \jaxrs\ in one of two ways: 7 | 8 | \begin{enumerate} 9 | \item An instance of \rd\ can be instantiated and injected using its static method \code{set\-Instance}. In this case the implementation is responsible for creating the instance; this option is intended for use with implementations based on IoC frameworks. 10 | \item The class to be used can be configured, see Section \ref{rdconfig}. In this case \jaxrs\ is responsible for instantiating an instance of the class and the configured class MUST have a public constructor which takes no arguments. 11 | \end{enumerate} 12 | 13 | Note that an implementation MAY supply an alternate implementation of the \rd\ API class (provided it passes the TCK signature test and behaves according to the specification) that supports alternate means of locating a concrete subclass. 14 | 15 | A \jaxrs\ implementation may rely on a particular implementation of \rd\ being used -- applications SHOULD NOT override the supplied \rd\ instance with an application-supplied alternative and doing so may cause unexpected problems. 16 | 17 | \section{Configuration}\label{rdconfig} 18 | 19 | If not supplied by injection, the supplied \rd\ API class obtains the concrete implementation class using the following algorithm. The steps listed below are performed in sequence and, at each step, at most one candidate implementation class name will be produced. The implementation will then attempt to load the class with the given class name using the current context class loader or, missing one, the \code{java.lang.Class.forName(String)} method. As soon as a step results in an implementation class being successfully loaded, the algorithm terminates. 20 | \begin{enumerate} 21 | \item Use the Java SE class \code{java.util.ServiceLoader} to attempt to load an implementation from \code{META-INF\-/services/javax.ws.rs.ext.RuntimeDelegate}. Note that this may require more than one call to method \code{ServiceLoader.load(Class, ClassLoader)} in order to try both the context class loader and the current class loader as explained above 22 | \footnote{Earlier versions of \jaxrs\ did not mandate the use \code{ServiceLoader}. This backward-compatible change that started in \jaxrs\ 2.1 is to ensure forward compatibility with the Java SE 9 module system.}. 23 | \item If the \code{\$\{java.home\}/lib/jaxrs.properties} file exists and it is readable by the \code{java\-.util\-.Properties\-.load(\-InputStream)} method and it contains an entry whose key is \code{javax\-.ws\-.rs\-.ext\-.Runtime\-Delegate}, then the value of that entry is used as the name of the implementation class. 24 | \item If a system property with the name \code{javax\-.ws\-.rs\-.ext\-.Runtime\-Delegate} is defined, then its value is used as the name of the implementation class. 25 | \item Finally, a default implementation class name is used. 26 | \end{enumerate} 27 | -------------------------------------------------------------------------------- /styles/macros.tex: -------------------------------------------------------------------------------- 1 | \newtheorem{note}{Note}[chapter] 2 | \newcommand{\code}[1]{\texttt{\small #1}} 3 | \renewcommand\verbatimtabsize{4\relax} 4 | \newcommand{\jaxrs}{JAX-RS} 5 | 6 | \newcommand{\Consumes}{\code{@Consumes}} 7 | \newcommand{\Encoded}{\code{@Encoded}} 8 | \newcommand{\HeaderParam}{\code{@Header\-Param}} 9 | \newcommand{\Context}{\code{@Context}} 10 | \newcommand{\SecurityContext}{\code{Security\-Context}} 11 | \newcommand{\HttpHeaders}{\code{Http\-Headers}} 12 | \newcommand{\HttpMethod}{\code{@Http\-Method}} 13 | \newcommand{\MatrixParam}{\code{@Matrix\-Param}} 14 | \newcommand{\MsgRead}{\code{Message\-Body\-Reader}} 15 | \newcommand{\MsgWrite}{\code{Message\-Body\-Writer}} 16 | \newcommand{\Path}{\code{@Path}} 17 | \newcommand{\PathParam}{\code{@Path\-Param}} 18 | \newcommand{\Produces}{\code{@Produces}} 19 | \newcommand{\Provider}{\code{@Provider}} 20 | \newcommand{\QueryParam}{\code{@Query\-Param}} 21 | \newcommand{\FormParam}{\code{@Form\-Param}} 22 | \newcommand{\CookieParam}{\code{@Cookie\-Param}} 23 | \newcommand{\Request}{\code{Request}} 24 | \newcommand{\Response}{\code{Response}} 25 | \newcommand{\ResponseBuilder}{\code{Response\-Builder}} 26 | \newcommand{\rd}{\code{Runtime\-Delegate}} 27 | \newcommand{\UriInfo}{\code{Uri\-Info}} 28 | \newcommand{\WebAppExc}{\code{Web\-Application\-Exception}} 29 | \newcommand{\Resource}{\code{javax.\-annotation.\-Resource}} 30 | 31 | \newcommand{\Client}{\code{Client}} 32 | \newcommand{\ClientBuilder}{\code{ClientBuilder}} 33 | \newcommand{\ClientConfiguration}{\code{ClientConfiguration}} 34 | \newcommand{\Link}{\code{Link}} 35 | \newcommand{\Invocation}{\code{Invocation}} 36 | \newcommand{\Configurable}{\code{Configurable}} 37 | \newcommand{\InvocationBuilder}{\code{Invocation.Builder}} 38 | 39 | \newcommand{\ClientRequestFilter}{\code{ClientRequestFilter}} 40 | \newcommand{\ContainerRequestFilter}{\code{ContainerRequestFilter}} 41 | \newcommand{\ClientResponseFilter}{\code{ClientResponseFilter}} 42 | \newcommand{\ContainerResponseFilter}{\code{ContainerResponseFilter}} 43 | \newcommand{\PreMatching}{\code{@PreMatching}} 44 | \newcommand{\PostMatching}{\code{@PostMatching}} 45 | \newcommand{\ContainerRequestContext}{\code{ContainerRequestContext}} 46 | \newcommand{\ContainerResponseContext}{\code{ContainerResponseContext}} 47 | \newcommand{\ReaderInterceptor}{\code{ReaderInterceptor}} 48 | \newcommand{\WriterInterceptor}{\code{WriterInterceptor}} 49 | \newcommand{\ReaderInterceptorContext}{\code{ReaderInterceptorContext}} 50 | \newcommand{\WriterInterceptorContext}{\code{WriterInterceptorContext}} 51 | \newcommand{\MessageBodyReader}{\code{MessageBodyReader}} 52 | \newcommand{\MessageBodyWriter}{\code{MessageBodyWriter}} 53 | \newcommand{\DynamicBinder}{\code{DynamicBinder}} 54 | \newcommand{\DynamicFeature}{\code{DynamicFeature}} 55 | \newcommand{\ParamConverter}{\code{ParamConverter}} 56 | \newcommand{\ParamConverterProvider}{\code{ParamConverterProvider}} 57 | 58 | \newcommand{\NameBinding}{\code{@NameBinding}} 59 | \newcommand{\GlobalBinding}{\code{@GlobalBinding}} 60 | \newcommand{\Priority}{\code{@Priority}} 61 | 62 | \newcommand{\NotNull}{\code{@NotNull}} 63 | \newcommand{\ApplicationPath}{\code{@ApplicationPath}} 64 | \newcommand{\Email}{\code{@Email}} 65 | \newcommand{\Pattern}[1]{\code{@Pattern(#1)}} 66 | \newcommand{\Constraint}{\code{@Constraint}} 67 | \newcommand{\Valid}{\code{@Valid}} 68 | \newcommand{\Suspended}{\code{@Suspended}} 69 | \newcommand{\ExecutionContext}{\code{ExecutionContext}} 70 | \newcommand{\WebApplicationException}{\code{WebApplicationException}} 71 | \newcommand{\WebTarget}{\code{WebTarget}} 72 | 73 | \newcommand{\ClientRequest}{{\footnotesize {\sf ClientRequest}}} 74 | \newcommand{\ClientResponse}{{\footnotesize {\sf ClientResponse}}} 75 | \newcommand{\ContainerRequest}{{\footnotesize {\sf ContainerRequest}}} 76 | \newcommand{\PreMatchContainerRequest}{{\footnotesize {\sf PreMatchContainerRequest}}} 77 | \newcommand{\ContainerResponse}{{\footnotesize {\sf ContainerResponse}}} 78 | \newcommand{\ReadFrom}{{\footnotesize {\sf ReadFrom}}} 79 | \newcommand{\WriteTo}{{\footnotesize {\sf WriteTo}}} 80 | 81 | -------------------------------------------------------------------------------- /chapters/headers.tex: -------------------------------------------------------------------------------- 1 | \chapter{HTTP Header Support} 2 | \label{headersupport} 3 | 4 | The following table lists HTTP headers that are directly supported, either automatically by a \jaxrs\ implementation runtime or by an application using the \jaxrs\ API. Any request header may be obtained using \HttpHeaders, see Section \ref{httpheaders}; response headers not listed here may set using the \ResponseBuilder\-\code{.header} method. 5 | 6 | %\begin{center} 7 | \begin{longtable}{|l|p{4.5in}|} 8 | \hline 9 | \bfseries Header & \bfseries Description \tabularnewline 10 | \hline\hline\endhead 11 | \code{Accept} & \raggedright Used by runtime when selecting a resource method, compared to value of \Produces\ annotation, see Section \ref{declaring_method_capabilities}. \tabularnewline 12 | \hline 13 | \code{Accept-Charset} & \raggedright Processed by runtime if application uses \Request\code{.selectVariant} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 14 | \hline 15 | \code{Accept-Encoding} & \raggedright Processed by runtime if application uses \Request\code{.selectVariant} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 16 | \hline 17 | \code{Accept-Language} & \raggedright Processed by runtime if application uses \Request\code{.selectVariant} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 18 | \hline 19 | \code{Allow} & \raggedright Included in automatically generated 405 error responses (see Section \ref{request_matching}) and automatically generated responses to OPTIONS requests (see Section \ref{head_and_options}).\tabularnewline 20 | \hline 21 | \code{Authorization} & \raggedright Depends on container, information available via \SecurityContext, see Section \ref{security_context}. \tabularnewline 22 | \hline 23 | \code{Cache-Control} & \raggedright See \code{CacheControl} class and \ResponseBuilder\code{.cacheControl} method. \tabularnewline 24 | \hline 25 | \code{Content-Encoding} & \raggedright Response header set by application using \Response\code{.ok} or \ResponseBuilder\code{.variant}. \tabularnewline 26 | \hline 27 | \code{Content-Language} & \raggedright Response header set by application using \Response\code{.ok}, \ResponseBuilder\code{.language}, or \ResponseBuilder\code{.variant}. \tabularnewline 28 | \hline 29 | \code{Content-Length} & \raggedright Processed automatically for requests, set automatically in responses if value is provided by the \MsgWrite\ used to serialize the message entity. \tabularnewline 30 | \hline 31 | \code{Content-Type} & \raggedright Request header used by runtime when selecting a resource method, compared to value of \Consumes\ annotation, see Section \ref{declaring_method_capabilities}. Response header either set by application using \Response\code{.ok}, \ResponseBuilder\code{.type}, or \ResponseBuilder\code{.variant}, or set automatically by runtime (see Section \ref{determine_response_type}).\tabularnewline 32 | \hline 33 | \code{Cookie} & \raggedright See \code{Cookie} class and \HttpHeaders\code{.getCookies} method. \tabularnewline 34 | \hline 35 | \code{Date} & \raggedright Included in responses automatically as per HTTP/1.1. \tabularnewline 36 | \hline 37 | \code{ETag} & \raggedright See \code{EntityTag} class, \Response\code{.notModified} method and \ResponseBuilder\code{.tag} method. \tabularnewline 38 | \hline 39 | \code{Expect} & \raggedright Depends on underlying container. \tabularnewline 40 | \hline 41 | \code{Expires} & \raggedright Set by application using the \ResponseBuilder\code{.expires} method. \tabularnewline 42 | \hline 43 | \code{If-Match} & \raggedright Processed by runtime if application uses corresponding \Request\code{.evaluatePreconditions} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 44 | \hline 45 | \code{If-Modified-Since} & \raggedright Processed by runtime if application uses corresponding \Request\code{.evaluatePreconditions} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 46 | \hline 47 | \code{If-None-Match} & \raggedright Processed by runtime if application uses corresponding \Request\code{.evaluatePreconditions} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 48 | \hline 49 | \code{If-Unmodified-Since} & \raggedright Processed by runtime if application uses corresponding \Request\code{.evaluatePreconditions} method, see Section \ref{conneg_and_preconditions}. \tabularnewline 50 | \hline 51 | \code{Last-Modified} & \raggedright Set by application using the \ResponseBuilder\code{.lastModified} method. \tabularnewline 52 | \hline 53 | \code{Location} & \raggedright Set by application using the applicable \Response\ method or directly using the \ResponseBuilder\code{.location} method.\tabularnewline 54 | \hline 55 | \code{Set-Cookie} & \raggedright See \code{NewCookie} class and \ResponseBuilder\code{.cookie} method. \tabularnewline 56 | \hline 57 | \code{Transfer-Encoding} & \raggedright See Section \ref{transfer_encoding}. \tabularnewline 58 | \hline 59 | \code{Vary} & \raggedright Set by application using \Response\code{.notAcceptable} method or \ResponseBuilder\code{.variants} method. \tabularnewline 60 | \hline 61 | \code{WWW-Authenticate} & \raggedright Depends on container. \tabularnewline 62 | \hline 63 | \end{longtable} 64 | %\end{center} 65 | -------------------------------------------------------------------------------- /chapters/annotations.tex: -------------------------------------------------------------------------------- 1 | \chapter{Summary of Annotations} 2 | \label{annotation_table} 3 | %\begin{center} 4 | \begin{longtable}{|l|p{1.2in}|p{3.5in}|} 5 | \hline 6 | \bfseries Annotation & \bfseries Target & \bfseries Description \tabularnewline 7 | \hline\hline\endhead 8 | \code{Consumes} & \raggedright Type or method & \raggedright Specifies a list of media types that can be consumed. \tabularnewline 9 | \hline 10 | \code{Produces} & \raggedright Type or method & \raggedright Specifies a list of media types that can be produced. \tabularnewline 11 | \hline 12 | \code{GET} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP GET requests. \tabularnewline 13 | \hline 14 | \code{POST} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP POST requests. \tabularnewline 15 | \hline 16 | \code{PUT} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP PUT requests. \tabularnewline 17 | \hline 18 | \code{DELETE} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP DELETE requests. \tabularnewline 19 | \hline 20 | \code{PATCH} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP PATCH requests. \tabularnewline 21 | \hline 22 | \code{HEAD} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP HEAD requests. Note that HEAD may be automatically handled, see Section \ref{head_and_options}. \tabularnewline 23 | \hline 24 | \code{OPTIONS} & \raggedright Method & \raggedright Specifies that the annotated method handles HTTP OPTIONS requests. \tabularnewline 25 | \hline 26 | \code{ApplicationPath} & \raggedright Type & \raggedright Specifies the resource-wide application path that forms the base URI of all root resource classes. \tabularnewline 27 | \hline 28 | \code{Path} & \raggedright Type or method & \raggedright Specifies a relative path for a resource. When used on a class this annotation identifies that class as a root resource. When used on a method this annotation identifies a sub-resource method or locator. \tabularnewline 29 | \hline 30 | \code{PathParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter, class field, or bean property is to be extracted from the request URI path. The value of the annotation identifies the name of a URI template parameter.\tabularnewline 31 | \hline 32 | \code{QueryParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter, class field, or bean property is to be extracted from a URI query parameter. The value of the annotation identifies the name of a query parameter. \tabularnewline 33 | \hline 34 | \code{FormParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter is to be extracted from a form parameter in a request entity body. The value of the annotation identifies the name of a form parameter. Note that whilst the annotation target allows use on fields and methods, the specification only requires support for use on resource method parameters.\tabularnewline 35 | \hline 36 | \code{MatrixParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter, class field, or bean property is to be extracted from a URI matrix parameter. The value of the annotation identifies the name of a matrix parameter. \tabularnewline 37 | \hline 38 | \code{CookieParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter, class field, or bean property is to be extracted from a HTTP cookie. The value of the annotation identifies the name of a the cookie. \tabularnewline 39 | \hline 40 | \code{HeaderParam} & \raggedright Parameter, field or method & \raggedright Specifies that the value of a method parameter, class field, or bean property is to be extracted from a HTTP header. The value of the annotation identifies the name of a HTTP header. \tabularnewline 41 | \hline 42 | \code{Encoded} & \raggedright Type, constructor, method, field or parameter & \raggedright Disables automatic URI decoding for path, query, form and matrix parameters. \tabularnewline 43 | \hline 44 | \code{DefaultValue} & \raggedright Parameter, field or method & \raggedright Specifies a default value for a field, property or method parameter annotated with \QueryParam, \MatrixParam, \CookieParam, \FormParam\ or \HeaderParam. The specified value will be used if the corresponding query or matrix parameter is not present in the request URI, if the corresponding form parameter is not in the request entity body, or if the corresponding HTTP header is not included in the request.\tabularnewline 45 | \hline 46 | \code{Context} & \raggedright Field, method or parameter & \raggedright Identifies an injection target for one of the types listed in Section \ref{contexttypes} or the applicable section of Chapter \ref{environment}. \tabularnewline 47 | \hline 48 | \code{HttpMethod} & \raggedright Annotation & \raggedright Specifies the HTTP method for a request method designator annotation. \tabularnewline 49 | \hline 50 | \code{Provider} & \raggedright Type & \raggedright Specifies that the annotated class implements a \jaxrs\ extension interface. \tabularnewline 51 | \hline 52 | \hline 53 | \multicolumn{3}{|c|} 54 | {\bfseries Since JAX-RS 2.0} \\ 55 | \hline 56 | \hline 57 | \code{NameBinding} & \raggedright Annotation & \raggedright Meta-annotation to create annotations for binding filters or interceptors to resource methods and applications. Name binding is only supported as part of the Server API. \tabularnewline 58 | \hline 59 | \code{Suspended} & \raggedright Parameter & \raggedright Indicates that a resource method is asynchronous. I.e., that it does not produce a response upon returning. JAX-RS implementations will suspend the incoming connection until a response becomes available. \tabularnewline 60 | \hline 61 | \code{PreMatching} & \raggedright Type & \raggedright Global binding annotation that can be applied to a container filter to indicate that it should be applied globally and before the resource method is matched.\tabularnewline 62 | \hline 63 | \code{BeanParam} & \raggedright Parameter, field or method & \raggedright Can be used to inject a user-defined bean whose fields and properties may be annotated with JAX-RS param annotations.\tabularnewline 64 | \hline 65 | \code{ConstrainedTo} & \raggedright Type & \raggedright Can be used to restrict the applicability of a provider to just the Client API or just the Server API. If omitted, a provider can be used in either context. 66 | \tabularnewline\hline 67 | \code{ParamConverter.Lazy} & \raggedright Type & \raggedright Indicates that a conversion of a default value delegated to a \code{ParamConverter} SHOULD occur only when the value is actually requested. 68 | \tabularnewline\hline 69 | \end{longtable} 70 | %\end{center} 71 | -------------------------------------------------------------------------------- /chapters/sse.tex: -------------------------------------------------------------------------------- 1 | \chapter{Server-Sent Events} 2 | \label{sse} 3 | 4 | \section{Introduction} 5 | \label{sse_introduction} 6 | 7 | Server-sent events (SSE) is a specification originally introduced as part of HTML5 by the W3C, but is currently maintained by the WHATWG \cite{sse}. It provides a way to establish a one-way channel from a server to a client. The connection is long running: it is re-used for multiple events sent from the server, yet it is still based on the HTTP protocol. Clients request the opening of an SSE connection by using the special media type \code{text/event-stream} in the \code{Accept} header. 8 | 9 | Events are structured and contain several fields, namely, \code{event}, \code{data}, \code{id}, \code{retry} and \code{comment}. SSE is a messaging protocol where the \code{event} field corresponds to a topic, and where the \code{id} field can be used to validate event order and guarantee continuity. If a connection is interrupted for any reason, the \code{id} can be sent in a request header for a server to re-play past events ---although this is an optional behavior that may not be supported by all implementations. Event payloads are conveyed in the \code{data} field and must be in text format; \code{retry} is used to control re-connects and finally \code{comment} is a general purpose field that can also be used to keep connections alive. 10 | 11 | \section{Client API} 12 | \label{sse_client_api} 13 | 14 | The \jaxrs\ client API for SSE was inspired by the corresponding JavaScript API in HTML5, but with changes that originate from the use of a different language. The entry point to the client API is the type \code{SseEventSource}, which provides a fluent builder similarly to other classes in the JAX-RS API. An \code{SseEventSource} is constructed from a \code{WebTarget} that is already configured with a resource location; \code{SseEventSource} does not duplicate any functionality in \code{WebTarget} and only adds the necessary logic for SSE. 15 | 16 | The following example shows how to open an SSE connection and read some messages for a little 17 | while: 18 | 19 | \begin{listing}{1} 20 | WebTarget target = client.target("http://..."); 21 | try (SseEventSource source = SseEventSource.target(target).build()) { 22 | source.register(System.out::println); 23 | source.open();

 24 | Thread.sleep(500); // Consume events for just 500 ms
 25 | } catch (InterruptedException e) {
 26 | // falls through
 27 | } 28 | \end{listing} 29 | 30 | As seen in this example, an \code{SseEventSource} implements \code{AutoCloseable}. Before opening the source, the client registers an event consumer that simply prints each event. Additional handlers for other life-cycle events such as \code{onComplete} and \code{onError} are also supported, but for simplicity only \code{onEvent} is shown in the example above. 31 | 32 | \section{Server API} 33 | \label{sse_server_api} 34 | 35 | The \jaxrs\ SSE server API is used to accept connections and send events to one or more clients. A resource method that injects an \code{SseEventSink} and produces the media type \code{text/event-stream} is an SSE resource method. 36 | 37 | The following example accepts SSE connections and uses an executor thread to send 3 events before closing the connection: 38 | 39 | \begin{listing}{1} 40 | @GET
 41 | @Path("eventStream")
 42 | @Produces(MediaType.SERVER_SENT_EVENTS)
 43 | public void eventStream(@Context SseEventSink eventSink,
 44 | @Context Sse sse) { 45 | executor.execute(() -> { 46 | try (SseEventSink sink = eventSink) {

 47 | eventSink.send(sse.newEvent("event1")); 48 | eventSink.send(sse.newEvent("event2")); 49 | eventSink.send(sse.newEvent("event3")); 50 | } 51 | }); 52 | } 53 | \end{listing} 54 | 55 | SSE resource methods follow a similar pattern to those for asynchronous processing (see Section \ref{introduction_async}) in that the object representing the incoming connection, in this case \code{SseEventSink}, is injected into the resource method. 56 | 57 | The example above also injects the \code{Sse} type which provides factory methods for events and broadcasters. See section \ref{sse_broadcasting} for more information about broadcasting. Note that, just like \code{SseEventSource}, the interface \code{SseEventSink} is also auto-closeable, hence the use of the \emph{try-with-resources} statement above. 58 | 59 | Method \code{send} on \code{SseEventSink} returns a \code{CompletionStage} as a way to provide a \emph{handle} to the action of asynchronously sending a message to a client. 60 | 61 | \section{Broadcasting} 62 | \label{sse_broadcasting} 63 | 64 | Applications may need to send events to multiple clients simultaneously. This action is called \emph{broadcasting} in \jaxrs. Multiple \code{SseEventSink}'s can be registered on a single \code{SseBroadcaster}. 65 | 66 | A broadcaster can only be created by calling method \code{newBroadcaster} on the injected \code{Sse} instance. The life-cycle and scope of an \code{SseBroadcaster} is fully controlled by applications and not the \jaxrs\ runtime. The following example shows the use of broadcasters, note the \code{@Singleton} annotation on the resource class: 67 | 68 | \begin{listing}{1} 69 | @Path("/")
 70 | @Singleton 71 | public class SseResource { 72 | 73 | @Context 74 | private Sse sse; 75 | 76 | private volatile SseBroadcaster sseBroadcaster; 77 | 78 | @PostConstruct 79 | public init() { 80 | this.sseBroadcaster = sse.newBroadcaster(); 81 | }

 82 | 83 | @GET 84 | @Path("register") 85 | @Produces(MediaType.SERVER_SENT_EVENTS) 86 | public void register(@Context SseEventSink eventSink) { 87 | eventSink.send(sse.newEvent("welcome!")); 88 | sseBroadcaster.register(eventSink); 89 | }

 90 | 91 | @POST 92 | @Path("broadcast") 93 | @Consumes(MediaType.MULTIPART_FORM_DATA) 94 | public void broadcast(@FormParam("event") String event) {
 95 | sseBroadcaster.broadcast(sse.newEvent(event)); 96 | }
 97 | } 98 | \end{listing} 99 | 100 | The \code{register} method on a broadcaster is used to add a new \code{SseEventSink}; the 101 | \code{broadcast} method is used to send an SSE event to all registered consumers. 102 | 103 | \section{Processing Pipeline} 104 | \label{sse_pipeline} 105 | 106 | Connections from SSE clients are represented by injectable instances of \code{SseEventSink}. There are some similarities between SSE and asynchronous processing (see Chapter \ref{asynchronous_processing}). Asynchronous responses can be resumed at most once while an \code{SseEventSink} can be used multiple times to stream individual events. 107 | 108 | For compatibility purposes, implementations MUST initiate processing of an SSE response when either the first message is sent or when the resource method returns, whichever happens first. The initial SSE response, which may only include the HTTP headers, is processed using the standard \jaxrs\ pipeline as described in Appendix \ref{processing_pipeline}. Each subsequent SSE event may include a different payload and thus require the use of a specific message body writer. Note that since this use case differs slightly from the normal \jaxrs\ pipeline, implementations SHOULD NOT call entity interceptors on each individual event \footnote{As a matter of fact, there is no API to bind entity interceptors to individual SSE events.}. 109 | 110 | \section{Environment} 111 | \label{sse_environment} 112 | 113 | The \code{SseEventSource} class uses the existing \jaxrs\ mechanism based on \code{RuntimeDelegate} to find an implementation using the service name \code{javax.ws.rs.sse.SseEventSource.Builder}. The majority of types in the \code{javax.ws.rs.sse} are thread safe; the reader is referred to the Javadoc for more information on thread safety. 114 | 115 | 116 | -------------------------------------------------------------------------------- /chapters/context.tex: -------------------------------------------------------------------------------- 1 | \chapter{Context} 2 | \label{context} 3 | 4 | \jaxrs\ provides facilities for obtaining and processing information about the application deployment context and the context of individual requests. Such information is available to \code{Application} subclasses (see Section \ref{config}), root resource classes (see Chapter \ref{resources}), and providers (see Chapter \ref{providers}). This chapter describes these facilities. 5 | 6 | \section{Concurrency} 7 | 8 | Context is specific to a particular request but instances of certain \jaxrs\ components (providers and resource classes with a lifecycle other than per-request) may need to support multiple concurrent requests. When injecting an instance of one of the types listed in Section \ref{contexttypes}, the instance supplied MUST be capable of selecting the correct context for a particular request. Use of a thread-local proxy is a common way to achieve this. 9 | 10 | \section{Context Types} 11 | \label{contexttypes} 12 | 13 | This section describes the types of context available to providers (client and server) as well as resource classes and \code{Application} subclasses (server only). Except for \code{Configuration} and \code{Providers}, which are injectable in both client and server-side providers, all the other types are server-side only. 14 | 15 | \subsection{Application} 16 | 17 | The instance of the application-supplied \code{Application} subclass can be injected into a class field or method parameter using the \Context\ annotation. Access to the \code{Application} subclass instance allows configuration information to be centralized in that class. Note that this cannot be injected into the \code{Application} subclass itself since this would create a circular dependency. 18 | 19 | \subsection{URIs and URI Templates} 20 | 21 | An instance of \UriInfo\ can be injected into a class field or method parameter using the \Context\ annotation. \UriInfo\ provides both static and dynamic, per-request information, about the components of a request URI. E.g. the following would return the names of any query parameters in a request: 22 | 23 | \begin{listing}{1} 24 | @GET 25 | @Produces{"text/plain"} 26 | public String listQueryParamNames(@Context UriInfo info) { 27 | StringBuilder buf = new StringBuilder(); 28 | for (String param: info.getQueryParameters().keySet()) { 29 | buf.append(param); 30 | buf.append("\n"); 31 | } 32 | return buf.toString(); 33 | } 34 | \end{listing} 35 | 36 | Note that the methods of \UriInfo\ provide access to request URI information following the pre-processing described in Section \ref{reqpreproc}. 37 | 38 | \subsection{Headers} 39 | \label{httpheaders} 40 | 41 | An instance of \HttpHeaders\ can be injected into a class field or method parameter using the \Context\ annotation. \HttpHeaders\ provides access to request header information either in map form or via strongly typed convenience methods. E.g. the following would return the names of all the headers in a request: 42 | 43 | \begin{listing}{1} 44 | @GET 45 | @Produces{"text/plain"} 46 | public String listHeaderNames(@Context HttpHeaders headers) { 47 | StringBuilder buf = new StringBuilder(); 48 | for (String header: headers.getRequestHeaders().keySet()) { 49 | buf.append(header); 50 | buf.append("\n"); 51 | } 52 | return buf.toString(); 53 | } 54 | \end{listing} 55 | 56 | Note that the methods of \HttpHeaders\ provide access to request information following the pre-processing described in Section \ref{reqpreproc}. 57 | 58 | Response headers may be provided using the \Response\ class, see \ref{resource_method_return} for more details. 59 | 60 | \subsection{Content Negotiation and Preconditions} 61 | \label{conneg_and_preconditions} 62 | 63 | \jaxrs\ simplifies support for content negotiation and preconditions using the \Request\ interface. An instance of \Request\ can be injected into a class field or method parameter using the \Context\ annotation. The methods of \Request\ allow a caller to determine the best matching representation variant and to evaluate whether the current state of the resource matches any preconditions in the request. Precondition support methods return a \ResponseBuilder\ that can be returned to the client to inform it that the request preconditions were not met. E.g. the following checks if the current entity tag matches any preconditions in the request before updating the resource: 64 | 65 | \begin{listing}{1} 66 | @PUT 67 | public Response updateFoo(@Context Request request, Foo foo) { 68 | EntityTag tag = getCurrentTag(); 69 | ResponseBuilder responseBuilder = request.evaluatePreconditions(tag); 70 | if (responseBuilder != null) 71 | return responseBuilder.build(); 72 | else 73 | return doUpdate(foo); 74 | } 75 | \end{listing} 76 | 77 | 78 | The application could also set the content location, expiry date and cache control information into the returned \code{ResponseBuilder} before building the response. 79 | 80 | \subsection{Security Context} 81 | \label{security_context} 82 | 83 | The \SecurityContext\ interface provides access to information about the security context of the current request. An instance of \SecurityContext\ can be injected into a class field or method parameter using the \Context\ annotation. The methods of \SecurityContext\ provide access to the current user principal, information about roles assumed by the requester, whether the request arrived over a secure channel and the authentication scheme used. 84 | 85 | \subsection{Providers} 86 | \label{providercontext} 87 | 88 | The \code{Providers} interface allows for lookup of provider instances based on a set of search criteria. An instance of \code{Providers} can be injected into a class field or method parameter using the \Context\ annotation. 89 | 90 | This interface is expected to be primarily of interest to provider authors wishing to use other providers functionality. It is injectable in both client and server providers. 91 | 92 | \subsection{Resource Context} 93 | \label{resource_context} 94 | 95 | The \code{ResourceContext} interface provides access to instantiation and initialization of resource or sub-resource classes in the default per-request scope. It can be injected to help with creation and initialization, or just initialization, of instances created by an application. 96 | 97 | Let us revisit the example from Section \ref{sub_resources} with some simple modifications: 98 | 99 | \begin{listing}{1} 100 | @Path("widgets") 101 | public class WidgetsResource { 102 | @Context 103 | private ResourceContext rc; 104 | 105 | @Path("{id}") 106 | public WidgetResource findWidget(@PathParam("id") String id) { 107 | return rc.initResource(new WidgetResource(id)); 108 | } 109 | } 110 | 111 | public class WidgetResource { 112 | @Context 113 | private HttpHeaders headers; 114 | 115 | public WidgetResource(String id) {...} 116 | 117 | @GET 118 | public Widget getDetails() {...} 119 | } 120 | \end{listing} 121 | 122 | Note that the instance returned by the resource locator \code{findWidget} in \code{WidgetsResource} is initialized using the injected \code{ResourceContext} before it is returned. Without this step, the \code{headers} field in \code{WidgetResource} will not be properly initialized. 123 | 124 | \subsection{Configuration} 125 | \label{configuration_injection} 126 | 127 | Both the client and the server runtime configurations are available for injection via \Context. These configurations are available for injection in providers (client or server) and resource classes (server only). 128 | 129 | As an example, consider the case of a client logging filter that not only logs messages but also logs information about certain features enabled during the processing of a request: 130 | 131 | \begin{listing}{1} 132 | public class LoggingFilter implements ClientRequestFilter { 133 | 134 | @Context 135 | private Configuration config; 136 | 137 | @Override 138 | public void filter(ClientRequestContext ctx) throws IOException { 139 | if (config.isEnabled(MyFeature.class)) { 140 | logMyFeatureEnabled(ctx); 141 | } 142 | logMessage(ctx); 143 | } 144 | ... 145 | } 146 | \end{listing} 147 | 148 | A client runtime configuration is injected in the filter shown above and its \code{isEnabled} method called to check if \code{MyFeature} is enabled. 149 | -------------------------------------------------------------------------------- /chapters/applications.tex: -------------------------------------------------------------------------------- 1 | \chapter{Applications} 2 | \label{applications} 3 | 4 | A \jaxrs\ application consists of one or more resources (see Chapter \ref{resources}) and zero or more providers (see Chapter \ref{providers}). This chapter describes aspects of \jaxrs\ that apply to an application as a whole, subsequent chapters describe particular aspects of a \jaxrs\ application and requirements on \jaxrs\ implementations. 5 | 6 | \section{Configuration} 7 | \label{config} 8 | 9 | The resources and providers that make up a \jaxrs\ application are configured via an application-supplied subclass of \code{Application}. An implementation MAY provide alternate mechanisms for locating resource classes and providers (e.g. runtime class scanning) but use of \code{Application} is the only portable means of configuration. 10 | 11 | \section{Verification} 12 | \label{verification} 13 | 14 | Specific application requirements are detailed throughout this specification and the \jaxrs\ Javadocs. Implementations MAY perform verification steps that go beyond what it is stated in this document. 15 | 16 | A \jaxrs\ implementation MAY report an error condition if it detects that two or more resources could result in an ambiguity during the execution of the algorithm described Section \ref{request_matching}. For example, if two resource methods in the same resource class have identical (or even intersecting) values in all the annotations that are relevant to the algorithm described in that section. The exact set of verification steps as well as the error reporting mechanism is implementation dependent. 17 | 18 | \section{Publication} 19 | 20 | Applications are published in different ways depending on whether the application is run in a Java SE environment or within a container. This section describes the alternate means of publication. 21 | 22 | \subsection{Java SE} 23 | 24 | In a Java SE environment a configured instance of an endpoint class can be obtained using the \code{create\-Endpoint} method of \rd. The application supplies an instance of \code{Application} and the type of endpoint required. An implementation MAY support zero or more endpoint types of any desired type. 25 | 26 | How the resulting endpoint class instance is used to publish the application is outside the scope of this specification. 27 | 28 | \subsubsection{JAX-WS} 29 | 30 | An implementation that supports publication via JAX-WS MUST support \code{create\-Endpoint} with an endpoint type of \code{javax\-.xml\-.ws\-.Provider}. JAX-WS describes how a \code{Provider} based endpoint can be published in an SE environment. 31 | 32 | \subsection{Servlet} 33 | \label{servlet} 34 | 35 | A \jaxrs\ application is packaged as a Web application in a \code{.war} file. The application classes are packaged in \code{WEB-INF/classes} or \code{WEB-INF/lib} and required libraries are packaged in \code{WEB-INF/lib}. See the Servlet specification for full details on packaging of web applications. 36 | 37 | It is RECOMMENDED that implementations support the Servlet 3 framework pluggability mechanism to enable portability between containers and to avail themselves of container-supplied class scanning facilities. When using the pluggability mechanism the following conditions MUST be met: 38 | 39 | \begin{itemize} 40 | \item If {\em no} \code{Application} subclass is present, JAX-RS implementations are REQUIRED to dynamically add a servlet and set its name to 41 | \begin{quote}\code{javax.\-ws.\-rs.\-core.\-Application}\end{quote} and to automatically discover all root resource classes and providers which MUST be packaged with the application. Additionally, the application MUST be packaged with a \code{web.xml} that specifies a servlet mapping for the added servlet. An example of such a \code{web.xml} file is: 42 | 43 | \begin{listing}{1} 44 | 48 | 49 | javax.ws.rs.core.Application 50 | 51 | 52 | javax.ws.rs.core.Application 53 | /myresources/* 54 | 55 | 56 | \end{listing} 57 | 58 | \item If an \code{Application} subclass is present: 59 | 60 | \begin{itemize} 61 | \item If there is already a servlet that handles this application. That is, a servlet that has an initialization parameter named 62 | \begin{quote}\code{javax.ws.rs.Application}\end{quote} whose value is the fully qualified name of the \code{Application} subclass, then no additional configuration steps are required by the JAX-RS implementation. 63 | 64 | \item If {\em no} servlet handles this application, JAX-RS implementations are REQUIRED to dynamically add a servlet whose fully qualified name must be that of the \code{Application} subclass. If the \code{Application} subclass is annotated with \ApplicationPath, implementations are REQUIRED to use the value of this annotation appended with "/*" to define a mapping for the added server. Otherwise, the application MUST be packaged with a \code{web.xml} that specifies a servlet mapping. For example, if \code{org.example.MyApplication} is the name of the \code{Application} subclass, a sample \code{web.xml} would be: 65 | 66 | \begin{listing}{1} 67 | 71 | 72 | org.example.MyApplication 73 | 74 | 75 | org.example.MyApplication 76 | /myresources/* 77 | 78 | 79 | \end{listing} 80 | 81 | \end{itemize} 82 | 83 | When an \code{Application} subclass is present in the archive, if both \code{Application.getClasses} and \code{Application.getSingletons} return an empty collection then all root resource classes and providers packaged in the web application MUST be included and the JAX-RS implementation is REQUIRED to discover them automatically by scanning a \code{.war} file as described above. If either \code{getClasses} or \code{getSingletons} returns a non-empty collection then only those classes or singletons returned MUST be included in the published \jaxrs\ application. 84 | \end{itemize} 85 | 86 | The following table summarizes the Servlet 3 framework pluggability mechanism: 87 | 88 | {\small 89 | \begin{longtable}{|p{1.2in}|l|l|p{1.65in}|} 90 | \hline 91 | \bfseries Condition & {\bfseries Action} & {\bfseries Servlet Name} & \bfseries \code{web.xml} 92 | \tabularnewline 93 | \hline\hline\endhead 94 | No \code{Application} subclass & Add servlet & \code{javax.\-ws.\-rs.\-core.\-Application} & Required for servlet mapping \tabularnewline 95 | \hline 96 | \code{Application} subclass handled by existing servlet & (none) & (already defined) & Not required \tabularnewline 97 | \hline 98 | \code{Application} subclass {\em not} handled by existing servlet & Add servlet & Subclass name & If no \ApplicationPath\ then required for servlet mapping \tabularnewline 99 | \hline 100 | \caption{Summary of Servlet 3 framework pluggability cases} 101 | \end{longtable} 102 | } 103 | 104 | If not using the Servlet 3 framework pluggability mechanism (e.g.~in a pre-Servlet 3.0 container), the \code{servlet-class} or \code{filter-class} element of the \code{web.xml} descriptor SHOULD name the \jaxrs\ implementation-supplied servlet or filter class respectively. The \code{Application} subclass SHOULD be identified using an \code{init-param} with a \code{param-name} of \code{javax.\-ws.\-rs.\-Application}. 105 | 106 | Note that the Servlet 3 framework pluggability mechanism described above is based on servlets and not filters. Applications that prefer to use an implementation-supplied filter class must use the pre-Servlet 3.0 configuration mechanism. 107 | 108 | \subsection{Other Container} 109 | 110 | An implementation MAY provide facilities to host a \jaxrs\ application in other types of container, such facilities are outside the scope of this specification. 111 | -------------------------------------------------------------------------------- /chapters/license.tex: -------------------------------------------------------------------------------- 1 | \begin{flushleft} 2 | 3 | {\bfseries JSR-370 Java\texttrademark\ API for RESTful Web Services (\lq\lq Specification\rq\rq)\\ 4 | Version: 2.1 \\ 5 | Status: Early Draft \\ 6 | Release: \today\\ 7 | Copyright 2011-2017 Oracle America, Inc. (``Oracle'') \\ 8 | 500 Oracle Parkway, Redwood Shores, California 94065, U.S.A\\ 9 | All rights reserved. 10 | } 11 | 12 | \mbox{}\\ 13 | {\bfseries LIMITED LICENSE GRANTS} 14 | 15 | 1. License for Evaluation Purposes. Oracle hereby grants you a fully-paid, non-exclusive, non-transferable, worldwide, limited license (without the right to sublicense), under Oracle's applicable intellectual property rights to view, download, use and reproduce the Specification only for the purpose of internal evaluation. This includes (i) developing applications intended to run on an implementation of the Specification, provided that such applications do not themselves implement any portion(s) of the Specification, and (ii) discussing the Specification with any third party; and (iii) excerpting brief portions of the Specification in oral or written communications which discuss the Specification provided that such excerpts do not in the aggregate constitute a significant portion of the Specification. 16 | 17 | 2. License for the Distribution of Compliant Implementations. Oracle also grants you a perpetual, non-exclusive, non-transferable, worldwide, fully paid-up, royalty free, limited license (without the right to sublicense) under any applicable copyrights or, subject to the provisions of subsection 4 below, patent rights it may have covering the Specification to create and/or distribute an Independent Implementation of the Specification that: (a) fully implements the Specification including all its required interfaces and functionality; (b) does not modify, subset, superset or otherwise extend the Licensor Name Space, or include any public or protected packages, classes, Java interfaces, fields or methods within the Licensor Name Space other than those required/authorized by the Specification or Specifications being implemented; and (c) passes the Technology Compatibility Kit (including satisfying the requirements of the applicable TCK Users Guide) for such Specification ("Compliant Implementation"). In addition, the foregoing license is expressly conditioned on your not acting outside its scope. No license is granted hereunder for any other purpose (including, for example, modifying the Specification, other than to the extent of your fair use rights, or distributing the Specification to third parties). Also, no right, title, or interest in or to any trademarks, service marks, or trade names of Oracle or Oracle's licensors is granted hereunder. Java, and Java-related logos, marks and names are trademarks or registered trademarks of Oracle America, Inc. in the U.S. and other countries. 18 | 19 | 3. Pass-through Conditions. You need not include limitations (a)-(c) from the previous paragraph or any other particular "pass through" requirements in any license You grant concerning the use of your Independent Implementation or products derived from it. However, except with respect to Independent Implementations (and products derived from them) that satisfy limitations (a)-(c) from the previous paragraph, You may neither: (a) grant or otherwise pass through to your licensees any licenses under Oracle’s applicable intellectual property rights; nor (b) authorize your licensees to make any claims concerning their implementation's compliance with the Specification in question. 20 | 21 | 4. Reciprocity Concerning Patent Licenses. 22 | 23 | \hspace{1em} a. With respect to any patent claims covered by the license granted under subparagraph 2 above that would be infringed by all technically feasible implementations of the Specification, such license is conditioned upon your offering on fair, reasonable and non-discriminatory terms, to any party seeking it from You, a perpetual, non-exclusive, non-transferable, worldwide license under Your patent rights which are or would be infringed by all technically feasible implementations of the Specification to develop, distribute and use a Compliant Implementation. 24 | 25 | \hspace{1em} b. With respect to any patent claims owned by Oracle and covered by the license granted under subparagraph 2, whether or not their infringement can be avoided in a technically feasible manner when implementing the Specification, such license shall terminate with respect to such claims if You initiate a claim against Oracle that it has, in the course of performing its responsibilities as the Specification Lead, induced any other entity to infringe Your patent rights. 26 | 27 | \hspace{1em} c. Also with respect to any patent claims owned by Oracle and covered by the license granted under subparagraph 2 above, where the infringement of such claims can be avoided in a technically feasible manner when implementing the Specification such license, with respect to such claims, shall terminate if You initiate a claim against Oracle that its making, having made, using, offering to sell, selling or importing a Compliant Implementation infringes Your patent rights. 28 | 29 | 5. Definitions. For the purposes of this Agreement: "Independent Implementation" shall mean an implementation of the Specification that neither derives from any of Oracle's source code or binary code materials nor, except with an appropriate and separate license from Oracle, includes any of Oracle's source code or binary code materials; "Licensor Name Space" shall mean the public class or interface declarations whose names begin with "java", "javax", "com.sun", “com.oracle” or their equivalents in any subsequent naming convention adopted by Oracle through the Java Community Process, or any recognized successors or replacements thereof; and "Technology Compatibility Kit" or "TCK" shall mean the test suite and accompanying TCK User's Guide provided by Oracle which corresponds to the Specification and that was available either (i) from Oracle 120 days before the first release of Your Independent Implementation that allows its use for commercial purposes, or (ii) more recently than 120 days from such release but against which You elect to test Your implementation of the Specification. 30 | 31 | This Agreement will terminate immediately without notice from Oracle if you breach the Agreement or act outside the scope of the licenses granted above. 32 | 33 | {\bfseries DISCLAIMER OF WARRANTIES} 34 | 35 | THE SPECIFICATION IS PROVIDED "AS IS". ORACLE MAKES NO REPRESENTATIONS OR WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT (INCLUDING AS A CONSEQUENCE OF ANY PRACTICE OR IMPLEMENTATION OF THE SPECIFICATION), OR THAT THE CONTENTS OF THE SPECIFICATION ARE SUITABLE FOR ANY PURPOSE. This document does not represent any commitment to release or implement any portion of the Specification in any product. In addition, the Specification could include technical inaccuracies or typographical errors. 36 | 37 | {\bfseries LIMITATION OF LIABILITY} 38 | 39 | TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL ORACLE OR ITS LICENSORS BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION, LOST REVENUE, PROFITS OR DATA, OR FOR SPECIAL, INDIRECT, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF OR RELATED IN ANY WAY TO YOUR HAVING, IMPLEMENTING OR OTHERWISE USING THE SPECIFICATION, EVEN IF ORACLE AND/OR ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 40 | You will indemnify, hold harmless, and defend Oracle and its licensors from any claims arising or resulting from: (i) your use of the Specification; (ii) the use or distribution of your Java application, applet and/or implementation; and/or (iii) any claims that later versions or releases of any Specification furnished to you are incompatible with the Specification provided to you under this license. 41 | 42 | {\bfseries RESTRICTED RIGHTS LEGEND} 43 | 44 | U.S. Government: If this Specification is being acquired by or on behalf of the U.S. Government or by a U.S. Government prime contractor or subcontractor (at any tier), then the Government's rights in the Software and accompanying documentation shall be only as set forth in this license; this is in accordance with 48 C.F.R. 227.7201 through 227.7202-4 (for Department of Defense (DoD) acquisitions) and with 48 C.F.R. 2.101 and 12.212 (for non-DoD acquisitions). 45 | 46 | {\bfseries REPORT} 47 | 48 | If you provide Oracle with any comments or suggestions concerning the Specification ("Feedback"), you hereby: (i) agree that such Feedback is provided on a non-proprietary and non-confidential basis, and (ii) grant Oracle a perpetual, non-exclusive, worldwide, fully paid-up, irrevocable license, with the right to sublicense through multiple levels of sublicensees, to incorporate, disclose, and use without limitation the Feedback for any purpose. 49 | 50 | {\bfseries GENERAL TERMS} 51 | 52 | Any action related to this Agreement will be governed by California law and controlling U.S. federal law. The U.N. Convention for the International Sale of Goods and the choice of law rules of any jurisdiction will not apply. 53 | 54 | The Specification is subject to U.S. export control laws and may be subject to export or import regulations in other countries. Licensee agrees to comply strictly with all such laws and regulations and acknowledges that it has the responsibility to obtain such licenses to export, re-export or import as may be required after delivery to Licensee. 55 | 56 | This Agreement is the parties' entire agreement relating to its subject matter. It supersedes all prior or contemporaneous oral or written communications, proposals, conditions, representations and warranties and prevails over any conflicting or additional terms of any quote, order, acknowledgment, or other communication between the parties relating to its subject matter during the term of this Agreement. No modification to this Agreement will be binding, unless in writing and signed by an authorized representative of each party. 57 | 58 | Rev. December, 2010 59 | 60 | \end{flushleft} 61 | -------------------------------------------------------------------------------- /chapters/environment.tex: -------------------------------------------------------------------------------- 1 | \chapter{Environment} 2 | \label{environment} 3 | 4 | The container-managed resources available to a \jaxrs\ root resource class or provider depend on the environment in which it is deployed. Section \ref{contexttypes} describes the types of context available regardless of container. The following sections describe the additional container-managed resources available to a \jaxrs\ root resource class or provider deployed in a variety of environments. 5 | 6 | \section{Servlet Container} 7 | \label{servlet_container} 8 | 9 | The \Context\ annotation can be used to indicate a dependency on a Servlet-defined resource. A Servlet-based implementation MUST support injection of the following Servlet-defined types: \code{Servlet\-Config}, \code{Servlet\-Context}, \code{Http\-Servlet\-Request} and \code{Http\-Servlet\-Response}. 10 | 11 | An injected \code{Http\-Servlet\-Request} allows a resource method to stream the contents of a request entity. If the resource method has a parameter whose value is derived from the request entity then the stream will have already been consumed and an attempt to access it MAY result in an exception. 12 | 13 | An injected \code{Http\-Servlet\-Response} allows a resource method to commit the HTTP response prior to returning. An implementation MUST check the committed status and only process the return value if the response is not yet committed. 14 | 15 | Servlet filters may trigger consumption of a request body by accessing request parameters. In a servlet container the @FormParam annotation and the standard entity provider for \code{application\-/x-\-www-\-form-\-urlencoded} MUST obtain their values from the servlet request parameters if the request body has already been consumed. Servlet APIs do not differentiate between parameters in the URI and body of a request so URI-based query parameters may be included in the entity parameter. 16 | 17 | \section{Integration with Java EE Technologies} 18 | \label{javaee} 19 | 20 | This section describes the additional requirements that apply to a \jaxrs\ implementation when combined in a product that supports the following specifications. 21 | 22 | \subsection{Servlets} 23 | \label{servlets} 24 | 25 | In a product that also supports the Servlet specification, implementations MUST support \jaxrs\ applications that are packaged as a Web application. 26 | See Section \ref{servlet} for more information Web application packaging. 27 | 28 | It is RECOMMENDED for a \jaxrs\ implementation to provide asynchronous processing support, as defined in Chapter \ref{asynchronous_processing}, by enabling asynchronous processing (i.e., \code{asyncSupported=true}) in the underlying Servlet 3 container. It is OPTIONAL for a \jaxrs\ implementation to support asynchronous processing when running on a Servlet container whose version is prior to 3. 29 | 30 | As explained in Section \ref{servlet_container}, injection of Servlet-defined types is possible using the \Context\ annotation. Additionally, web application's \code{} and servlet's \code{} can be used to define application properties passed to server-side features or injected into server-side JAX-RS components. See Javadoc for \code{Application.getProperties} for more information. 31 | 32 | \subsection{Managed Beans} 33 | \label{managed_beans} 34 | 35 | In a product that supports Managed Beans, implementations MUST support the use of Managed Beans as root resource classes, providers and \code{Application} subclasses. 36 | 37 | For example, a bean that uses a managed-bean interceptor can be defined as a \jaxrs\ resource as follows: 38 | 39 | \begin{listing}{1} 40 | @ManagedBean 41 | @Path("/managedbean") 42 | public class ManagedBeanResource { 43 | 44 | public static class MyInterceptor { 45 | @AroundInvoke 46 | public String around(InvocationContext ctx) throws Exception { 47 | System.out.println("around() called"); 48 | return (String) ctx.proceed(); 49 | } 50 | } 51 | 52 | @GET 53 | @Produces("text/plain") 54 | @Interceptors(MyInterceptor.class) 55 | public String getIt() { 56 | return "Hi managedbean!"; 57 | } 58 | } 59 | \end{listing} 60 | 61 | The example above uses a managed-bean interceptor to intercept calls to the resource method \code{getIt}. See Section \ref{additional_reqs} for additional requirements on Managed Beans. 62 | 63 | \subsection{Context and Dependency Injection (CDI)} 64 | \label{cdi} 65 | In a product that supports CDI, implementations MUST support the use of CDI-style Beans as root resource classes, providers and \code{Application} subclasses. Providers and \code{Application} subclasses MUST be singletons or use application scope. 66 | 67 | For example, assuming CDI is enabled via the inclusion of a \code{beans.xml} file, a CDI-style bean that can be defined as a \jaxrs\ resource as follows: 68 | 69 | \begin{listing}{1} 70 | @Path("/cdibean") 71 | public class CdiBeanResource { 72 | 73 | @Inject MyOtherCdiBean bean; // CDI injected bean 74 | 75 | @GET 76 | @Produces("text/plain") 77 | public String getIt() { 78 | return bean.getIt(); 79 | } 80 | } 81 | \end{listing} 82 | 83 | The example above takes advantage of the type-safe dependency injection provided in CDI by using another bean, of type \code{MyOtherCdiBean}, in order to return a resource representation. See Section \ref{additional_reqs} for additional requirements on CDI-style Beans. 84 | 85 | \subsection{Enterprise Java Beans (EJBs)} 86 | \label{ejbs} 87 | 88 | In a product that supports EJBs, an implementation MUST support the use of stateless and singleton session beans as root resource classes, providers and \code{Application} subclasses. 89 | \jaxrs\ annotations can be applied to methods in an EJB's local interface or directly to methods in a no-interface EJB. Resource class annotations (like \Path) MUST be applied to an EJB's class directly following the annotation inheritance rules defined in Section \ref{annotationinheritance}. 90 | 91 | For example, a stateless EJB that implements a local interface can be defined as a \jaxrs\ resource class as follows: 92 | 93 | \begin{listing}{1} 94 | @Local 95 | public interface LocalEjb { 96 | 97 | @GET 98 | @Produces("text/plain") 99 | public String getIt(); 100 | } 101 | 102 | @Stateless 103 | @Path("/stateless") 104 | public class StatelessEjbResource implements LocalEjb { 105 | 106 | @Override 107 | public String getIt() { 108 | return "Hi stateless!"; 109 | } 110 | } 111 | \end{listing} 112 | 113 | \jaxrs\ implementations are REQUIRED to discover EJBs by inspecting annotations on classes and local interfaces; they are not REQUIRED to read EJB deployment descriptors (ejb-jar.xml). Therefore, any information in an EJB deployment descriptor for the purpose of overriding EJB annotations or providing additional meta-data will likely result in a non-portable \jaxrs\ application. 114 | 115 | If an \code{Exception\-Mapper} for a \code{EJBException} or subclass is not included with an application then exceptions thrown by an EJB resource class or provider method MUST be unwrapped and processed as described in Section \ref{method_exc}. 116 | 117 | See Section \ref{async_ejbs} for more information on asynchronous EJB methods and Section \ref{additional_reqs} for additional requirements on EJBs. 118 | 119 | \subsection{Bean Validation} 120 | \label{bv_support} 121 | 122 | In a product that supports the Bean Validation specification \cite{bv11}, implementations MUST support resource validation using constraint annotations as described in Chapter \ref{validation}. Otherwise, support for resource validation is OPTIONAL. 123 | 124 | \subsection{Java API for JSON Processing} 125 | \label{jsonp} 126 | 127 | In a product that supports the Java API for JSON Processing (JSON-P) \cite{jsonp}, implementations MUST support entity providers for \code{JsonValue} and all of its sub-types: \code{JsonStructure}, \code{JsonObject}, \code{JsonArray}, \code{JsonString} and \code{JsonNumber}. 128 | 129 | Note that other types from the JSON-P API such as \code{JsonParser}, \code{JsonGenerator}, \code{JsonReader} and \code{JsonWriter} can also be integrated into JAX-RS applications using the entity providers for \code{InputStream} and \code{StreamingOutput}. 130 | 131 | 132 | \subsection{Java API for JSON Binding} 133 | \label{jsonb} 134 | In a product that supports the Java API for JSON Binding (JSON-B) \cite{jsonb}, 135 | implementations MUST support entity providers for all Java types supported by JSON-B in combination with the following media types: \code{application/json}, \code{text/json} as well as any other media types matching \code{*/json} or \code{*/*+json}. 136 | 137 | Note that if JSON-B and JSON-P are both supported in the same environment, entity providers for JSON-B take precedence over those for JSON-P for all types except \code{JsonValue} and its sub-types. 138 | 139 | 140 | \subsection{Additional Requirements} 141 | \label{additional_reqs} 142 | 143 | The following additional requirements apply when using Managed Beans, CDI-style Beans or EJBs as resource classes, providers or \code{Application} subclasses: 144 | 145 | \begin{itemize} 146 | \item Field and property injection of \jaxrs\ resources MUST be performed prior to the container invoking any \code{@PostConstruct} annotated method. 147 | \item Support for constructor injection of \jaxrs\ resources is OPTIONAL. Portable applications MUST instead use fields or bean properties in conjunction with a \code{@PostConstruct} annotated method. Implementations SHOULD warn users about use of non-portable constructor injection. 148 | \item Implementations MUST NOT require use of \code{@Inject} or \code{@Resource} to trigger injection of \jaxrs\ annotated fields or properties. Implementations MAY support such usage but SHOULD warn users about non-portability. 149 | \end{itemize} 150 | 151 | \section{Other} 152 | 153 | Other container technologies MAY specify their own set of injectable resources but MUST, at a minimum, support access to the types of context listed in Section \ref{contexttypes}. 154 | -------------------------------------------------------------------------------- /chapters/asynchronous.tex: -------------------------------------------------------------------------------- 1 | \chapter{Asynchronous Processing} 2 | \label{asynchronous_processing} 3 | 4 | This chapter describes the asynchronous processing capabilities in JAX-RS. Asynchronous processing is supported both in the Client API and in the Server API. 5 | 6 | \section{Introduction} 7 | \label{introduction_async} 8 | 9 | Asynchronous processing is a technique that enables a better and more efficient use of processing threads. On the client side, a thread that issues a request may also be responsible for updating a UI component; if that thread is blocked waiting for a response, the user's perceived performance of the application will suffer. Similarly, on the server side, a thread that is processing a request should avoid blocking while waiting for an external event to complete so that other requests arriving to the server during that period of time can be attended\footnote{The maximum number of request threads is typically set by the administrator; if that upper bound is reached, subsequent requests will be rejected.}. 10 | 11 | \section{Server API} 12 | \label{server_api} 13 | 14 | \subsection{AsyncResponse} 15 | \label{async_response} 16 | 17 | Synchronous processing requires a resource method to produce a response upon returning control back to the JAX-RS implementation. Asynchronous processing enables a resource method to inform the JAX-RS implementation that a response is not readily available upon return but will be produced at a future time. This can be accomplished by first {\em suspending} and later {\em resuming} the client connection on which the request was received. 18 | 19 | Let us illustrate these concepts via an example: 20 | 21 | \begin{listing}{1} 22 | @Path("/async/longRunning") 23 | public class MyResource { 24 | 25 | @GET 26 | public void longRunningOp(@Suspended final AsyncResponse ar) { 27 | executor.submit( 28 | new Runnable() { 29 | public void run() { 30 | executeLongRunningOp(); 31 | ar.resume("Hello async world!"); 32 | } 33 | }); 34 | } 35 | ... 36 | } 37 | \end{listing} 38 | 39 | A resource method that elects to produce a response asynchronously must inject as a method parameter an instance of the class \code{AsyncResponse} using the special annotation \Suspended. In the example above, the method \code{longRunningOp} is called upon receiving a \code{GET} request. Rather than producing a response immediately, this method forks a (non-request) thread to execute a long running operation and returns immediately. Once the execution of the long running operation is complete, the connection is resumed and the response returned by calling \code{resume} on the injected instance of \code{AsyncResponse}. 40 | 41 | For more information on executors, concurrency and thread management in a Java EE environment, the reader is referred to JSR 236 \cite{concurrencyee}. For more information about executors in the \jaxrs\ Client API see Section \ref{executor_services}. 42 | 43 | \subsubsection{Timeouts and Callbacks} 44 | \label{timeouts_and_callbacks} 45 | 46 | A timeout value can be specified when suspending a connection to avoid waiting for a response indefinitely. The default unit is milliseconds, but any unit of type \code{java.util.concurrent.TimeUnit} can be used. The following example sets a timeout of 15 seconds and registers an instance of \code{TimeoutHandler} in case the timeout is reached before the connection is resumed. 47 | 48 | \begin{listing}{1} 49 | @GET 50 | public void longRunningOp(@Suspended final AsyncResponse ar) { 51 | // Register handler and set timeout 52 | ar.setTimeoutHandler(new TimeoutHandler() { 53 | public void handleTimeout(AsyncResponse ar) { 54 | ar.resume(Response.status(SERVICE_UNAVAILABLE).entity( 55 | "Operation timed out -- please try again").build()); 56 | } 57 | }); 58 | ar.setTimeout(15, SECONDS); 59 | 60 | // Execute long running operation in new thread 61 | executor.execute( 62 | new Runnable() { 63 | public void run() { 64 | executeLongRunningOp(); 65 | ar.resume("Hello async world!"); 66 | } 67 | }); 68 | } 69 | \end{listing} 70 | 71 | \jaxrs\ implementations are REQUIRED to generate a \code{ServiceUnavailableException}, a subclass of \WebApplicationException\ with its status set to 503, if the timeout value is reached and no timeout handler is registered. The exception MUST be processed as described in section~\ref{method_exc}. If a registered timeout handler resets the timeout value or resumes the connection and returns a response, \jaxrs\ implementations MUST NOT generate an exception. 72 | 73 | It is also possible to register callbacks on an instance of \code{AsyncResponse} in order to listen for processing completion (\code{CompletionCallback}) and connection termination (\code{ConnectionCallback}) events. See Javadoc for \code{AsyncResponse} for more information on how to register these callbacks. Note that support for \code{ConnectionCallback} is OPTIONAL. 74 | 75 | \subsection{CompletionStage} 76 | \label{completionstage} 77 | 78 | An alternative approach to the injection of \code{AsyncResponse} is for a resource method to return an instance of \code{CompletionStage} as an indication to the underlying \jaxrs\ implementation that asynchronous processing is enabled. The example from Section \ref{async_response} can be re-written using \code{CompletionStage} as follows: 79 | 80 | \begin{listing}{1} 81 | @Path("/async/longRunning") 82 | public class MyResource { 83 | 84 | @GET 85 | public CompletionStage longRunningOp() { 86 | CompletableFuture cs = new CompletableFuture<>(); 87 | executor.submit( 88 | new Runnable() { 89 | public void run() { 90 | executeLongRunningOp(); 91 | cs.complete("Hello async world!"); 92 | } 93 | }); 94 | return cs; 95 | } 96 | ... 97 | } 98 | \end{listing} 99 | 100 | In this example, a \code{CompletableFuture} instance is created and returned in the resource method; the call to method \code{complete} on that instance is executed only after the long running operation terminates. 101 | 102 | \section{EJB Resource Classes} 103 | \label{async_ejbs} 104 | 105 | As stated in Section~\ref{ejbs}, JAX-RS implementations in products that 106 | support EJB must also support the use of stateless and singleton session beans 107 | as root resource classes. When an EJB method is annotated with \code{@Asynchronous}, the 108 | EJB container automatically allocates the necessary resources for its execution. 109 | Thus, in this scenario, the use of an \code{Executor} is unnecessary to generate 110 | an asynchronous response. 111 | 112 | Consider the following example: 113 | 114 | \begin{listing}{1} 115 | @Stateless 116 | @Path("/") 117 | class EJBResource { 118 | 119 | @GET @Asynchronous 120 | public void longRunningOp(@Suspended AsyncResponse ar) { 121 | executeLongRunningOp(); 122 | ar.resume("Hello async world!"); 123 | } 124 | } 125 | \end{listing} 126 | 127 | There is no explicit thread management needed in this case since that is 128 | under the control of the EJB container. Just like the other examples in this chapter, 129 | the response is produced by calling \code{resume} on the injected \code{AsyncResponse}. Hence, the return type of \code{longRunningOp} is simply \code{void}. 130 | 131 | \section{Client API} 132 | \label{client_api_async} 133 | 134 | The fluent API supports asynchronous invocations as part of the invocation building process. By default, invocations are synchronous but can be set to run asynchronously by calling the \code{async} method and (optionally) registering an instance of \code{InvocationCallback} as shown next: 135 | 136 | \begin{listing}{1} 137 | Client client = ClientBuilder.newClient(); 138 | WebTarget target = client.target("http://example.org/customers/{id}"); 139 | target.resolveTemplate("id", 123).request().async().get( 140 | new InvocationCallback() { 141 | @Override 142 | public void completed(Customer customer) { 143 | // Do something 144 | } 145 | @Override 146 | public void failed(Throwable throwable) { 147 | // Process error 148 | } 149 | }); 150 | \end{listing} 151 | 152 | Note that in this example, the call to \code{get} after calling \code{async} returns immediately without blocking the caller's thread. 153 | The response type is specified as a type parameter to \code{InvocationCallback}. The method \code{completed} is called when the invocation completes successfully and a response is available; the method \code{failed} is called with an instance of \code{Throwable} when the invocation fails. 154 | 155 | All asynchronous invocations return an instance of \code{Future} here the type parameter \code{T} matches the type specified in \code{InvocationCallback}. This instance can be used to monitor or cancel the asynchronous invocation: 156 | 157 | \begin{listing}{1} 158 | Future ff = target.resolveTemplate("id", 123).request().async() 159 | .get(new InvocationCallback() { 160 | @Override 161 | public void completed(Customer customer) { 162 | // Do something 163 | } 164 | @Override 165 | public void failed(Throwable throwable) { 166 | // Process error 167 | } 168 | }); 169 | 170 | // After waiting for a while ... 171 | if (!ff.isDone()) { 172 | ff.cancel(true); 173 | } 174 | \end{listing} 175 | 176 | Even though it is recommended to pass an instance of \code{InvocationCallback} when executing an asynchronous call, it is not mandated. When omitted, the \code{Future} returned by the invocation can be used to gain access to the response by calling the method \code{Future.get}, which will return an instance of \code{T} if the invocation was successful or \code{null} if the invocation failed. 177 | 178 | 179 | 180 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /chapters/intro.tex: -------------------------------------------------------------------------------- 1 | \chapter{Introduction} 2 | 3 | This specification defines a set of Java APIs for the development of Web services built according to the Representational State Transfer\cite{rest} (REST) architectural style. Readers are assumed to be familiar with 4 | REST; for more information about the REST architectural style and RESTful Web services, see: 5 | 6 | \begin{itemize} 7 | \item Architectural Styles and the Design of Network-based Software Architectures\cite{rest} 8 | \item The REST Wiki\cite{restwiki} 9 | \item Representational State Transfer on Wikipedia\cite{restwikipedia} 10 | \end{itemize} 11 | 12 | \section{Status} 13 | \label{status} 14 | 15 | %This is an early draft; this specification is not yet complete. A list of open issues can %be found at: 16 | %This is a JCP public review draft; this specification is not yet final. A list of open issues can be found at: 17 | %This is a JCP final specification. A list of open issues can be found at: 18 | 19 | This is the final release of version 2.1. The issue tracking system for this release can be found at: 20 | 21 | \begin{quote} 22 | https://github.com/jax-rs/api/issues 23 | \end{quote} 24 | 25 | The corresponding Javadocs can be found online at: 26 | 27 | \begin{quote} 28 | https://jax-rs.github.io/apidocs/2.1 29 | \end{quote} 30 | 31 | The reference implementation can be obtained from: 32 | 33 | \begin{quote} 34 | https://jersey.github.io 35 | \end{quote} 36 | 37 | The expert group seeks feedback from the community on any aspect of this specification, please send comments to: 38 | 39 | \begin{quote} 40 | jaxrs-spec@javaee.groups.io 41 | \end{quote} 42 | 43 | \section{Goals} 44 | 45 | The following are the goals of the API: 46 | 47 | \begin{description} 48 | 49 | \item[POJO-based] The API will provide a set of annotations and associated classes/interfaces that may be used with POJOs in order to expose them as Web resources. The specification will define object lifecycle and scope. 50 | 51 | \item[HTTP-centric] The specification will assume HTTP\cite{http11} is the underlying network protocol and will provide a clear mapping between HTTP and URI\cite{uri} elements and the corresponding API classes and annotations. The API will provide high level support for common HTTP usage patterns and will be sufficiently flexible to support a variety of HTTP applications including WebDAV\cite{webdav} and the Atom Publishing Protocol\cite{atompub}. 52 | 53 | \item[Format independence] The API will be applicable to a wide variety of HTTP entity body content types. It will provide the necessary pluggability to allow additional types to be added by an application in a standard manner. 54 | 55 | \item[Container independence] Artifacts using the API will be deployable in a variety of Web-tier containers. The specification will define how artifacts are deployed in a Servlet\cite{servlet} container and as a JAX-WS\cite{jsr224} Provider. 56 | 57 | \item[Inclusion in Java EE] The specification will define the environment for a Web resource class hosted in a Java EE container and will specify how to use Java EE features and components within a Web resource class. 58 | 59 | \end{description} 60 | 61 | \section{Non-Goals} 62 | \label{non_goals} 63 | 64 | The following are non-goals: 65 | 66 | \begin{description} 67 | 68 | \item[Support for Java versions prior to Java SE 8] The API will make extensive use of annotations and lambda expressions that require Java SE 8 or later. 69 | 70 | \item[Description, registration and discovery] The specification will neither define nor require any service description, registration or discovery capability. 71 | 72 | \item[HTTP Stack] The specification will not define a new HTTP stack. HTTP protocol support is provided by a container that hosts artifacts developed using the API. 73 | 74 | \item[Data model/format classes] The API will not define classes that support manipulation of entity body content, rather it will provide pluggability to allow such classes to be used by artifacts developed using the API. 75 | 76 | \end{description} 77 | 78 | \section{Conventions} 79 | 80 | The keywords `MUST', `MUST NOT', `REQUIRED', `SHALL', `SHALL NOT', `SHOULD', `SHOULD NOT', `RECOMMENDED', `MAY', and `OPTIONAL' in this document are to be interpreted as described in RFC 2119\cite{rfc2119}. 81 | 82 | Java code and sample data fragments are formatted as shown in figure \ref{ex1}: 83 | 84 | \begin{figure}[hbtp] 85 | \caption{Example Java Code} 86 | \label{ex1} 87 | \begin{listing}{1} 88 | package com.example.hello; 89 | 90 | public class Hello { 91 | public static void main(String args[]) { 92 | System.out.println("Hello World"); 93 | } 94 | }\end{listing} 95 | \end{figure} 96 | 97 | URIs of the general form `http://example.org/...' and `http://example.com/...' represent application or context-dependent URIs. 98 | 99 | All parts of this specification are normative, with the exception of examples, notes and sections explicitly marked as `Non-Normative'. Non-normative notes are formatted as shown below. 100 | 101 | \begin{nnnote*} 102 | This is a note. 103 | \end{nnnote*} 104 | 105 | \section{Terminology} 106 | \label{terminology} 107 | 108 | \begin{description} 109 | \item[Resource class] A Java class that uses \jaxrs\ annotations to implement a corresponding Web resource, see Chapter \ref{resources}. 110 | \item[Root resource class] A {\em resource class} annotated with \Path. Root resource classes provide the roots of the resource class tree and provide access to sub-resources, see Chapter \ref{resources}. 111 | \item[Request method designator] A runtime annotation annotated with \HttpMethod. Used to identify the HTTP request method to be handled by a {\em resource method}. 112 | \item[Resource method] A method of a {\em resource class} annotated with a {\em request method designator} that is used to handle requests on the corresponding resource, see Section \ref{resource_method}. 113 | \item[Sub-resource locator] A method of a {\em resource class} that is used to locate sub-resources of the corresponding resource, see Section \ref{sub_resources}. 114 | \item[Sub-resource method] A method of a {\em resource class} that is used to handle requests on a sub-resource of the corresponding resource, see Section \ref{sub_resources}. 115 | \item[Provider] An implementation of a \jaxrs\ extension interface. Providers extend the capabilities of a \jaxrs\ runtime and are described in Chapter \ref{providers}. 116 | \item[Filter] A provider used for filtering requests and responses. 117 | \item[Entity Interceptor] A provider used for intercepting calls to message body readers and writers. 118 | \item[Invocation] A Client API object that can be configured to issue an HTTP request. 119 | \item[WebTarget] The recipient of an Invocation, identified by a URI. 120 | \item[Link] A URI with additional meta-data such as a media type, a relation, a title, etc. 121 | 122 | \end{description} 123 | 124 | \section{Expert Group Members} 125 | \label{expert_group} 126 | 127 | This specification is being developed as part of JSR 370 under the Java Community Process. It is the result of the collaborative work of the members of the JSR 370 Expert Group. The following are the present expert group members: 128 | 129 | \begin{list}{$-$}{\parsep 0em \labelwidth 0em} 130 | \item Sergey Beryozkin (Talend SA) 131 | \item Adam Bien (Individual Member) 132 | \item Sebastian Dashner (Individual Member) 133 | \item Markus Karg (Individual Member) 134 | \item Casey Lee (Vision Service Plan) 135 | \item Marcos Luna (Individual Member) 136 | \item Andy McCright (IBM) 137 | \item Julian Reschke (Individual Member) 138 | \item Alessio Soldano (Red Hat) 139 | \end{list} 140 | 141 | The following are former group members of the JSR 339 Expert Group: 142 | 143 | \begin{list}{$-$}{\parsep 0em \labelwidth 0em} 144 | \item Jan Algermussen (Individual Member) 145 | \item Florent Beniot (OW2) 146 | \item Sergey Beryozkin (Talend SA) 147 | \item Adam Bien (Individual Member) 148 | \item Bill Burke (Red Hat) 149 | \item Clinton L. Combs (Individual Member) 150 | \item Jian Wu Dai (IBM) 151 | \item Bill De Hora (Individual Member) 152 | \item Markus Karg (Individual Member) 153 | \item Sastry Malladi (eBay, Inc) 154 | \item Julian Reschke (Individual Member) 155 | \item Guilherme de Azevedo Silveira (Individual Member) 156 | \item Synodinos, Dionysios G. (Individual Member) 157 | \end{list} 158 | 159 | JAX-RS 1.X has been developed as part of JSR 311 under the Java Community Process. The following were group members of the JSR 311 Expert Group: 160 | 161 | \begin{list}{$-$}{\parsep 0em \labelwidth 0em} 162 | \item Heiko Braun (Red Hat Middleware LLC) 163 | \item Larry Cable (BEA Systems) 164 | \item Roy Fielding (Day Software, Inc.) 165 | \item Harpreet Geekee (Nortel) 166 | \item Nickolas Grabovas (Individual Member) 167 | \item Mark Hansen (Individual Member) 168 | \item John Harby (Individual Member) 169 | \item Hao He (Individual Member) 170 | \item Ryan Heaton (Individual Member) 171 | \item David Hensley (Individual Member) 172 | \item Stephan Koops (Individual Member) 173 | \item Changshin Lee (NCsoft Corporation) 174 | \item Francois Leygues (Alcatel-Lucent) 175 | \item Jerome Louvel (Individual Member) 176 | \item Hamid Ben Malek (Fujitsu Limited) 177 | \item Ryan J. McDonough (Individual Member) 178 | \item Felix Meschberger (Day Software, Inc.) 179 | \item David Orchard (BEA Systems) 180 | \item Dhanji R. Prasanna (Individual Member) 181 | \item Julian Reschke (Individual Member) 182 | \item Jan Schulz-Hofen (Individual Member) 183 | \item Joel Smith (IBM) 184 | \item Stefan Tilkov (innoQ Deutschland GmbH) 185 | \end{list} 186 | 187 | \section{Acknowledgements} 188 | \label{acks} 189 | 190 | During the course of this JSR we received great contributions and suggestions from many individuals. Special thanks to Marek Potociar and Michal Gajdos. Also Gunnar Morling, Ondrej Mihalyi, Arjan Tijms, Guillermo Gonzales de Aguero, Christian Kaltepoth and many, many others. Last but not least to the JSR 370 Expert Group for all their contributions. 191 | 192 | During the course of JSR 339 we received many excellent suggestions. Special thanks to Martin Matula, Gerard Davison, Jakub Podlesak and Pavel Bucek from Oracle as well as Pete Muir and Emmanuel Bernard from Red Hat. Also to Gunnar Morling and Ron Sigal (Red Hat) for their suggestions on how to improve resource validation, and to Mattias Arthursson for his insights on hypermedia. 193 | 194 | During the course of JSR 311 we received many excellent suggestions on the JSR and Jersey (RI) mailing lists, thanks in particular to James Manger (Telstra) and Reto Bachmann-Gm\"{u}r (Trialox) for their contributions. The following individuals (all Sun Microsystems at the time) have also made invaluable technical contributions: Roberto Chinnici, Dianne Jiao (TCK), Ron Monzillo, Rajiv Mordani, Eduardo Pelegri-Llopart, Jakub Podlesak (RI) and Bill Shannon. 195 | 196 | The \code{GenericEntity} class was inspired by the Google Guice \code{Type\-Literal} class. Our thanks to Bob Lee and Google for donating this class to \jaxrs. 197 | -------------------------------------------------------------------------------- /chapters/validation.tex: -------------------------------------------------------------------------------- 1 | \chapter{Validation} 2 | \label{validation} 3 | 4 | Validation is the process of verifying that some data obeys one or more pre-defined constraints. The Bean Validation specification \cite{bv11} defines an API to validate Java Beans. This chapter describes how JAX-RS provides native support for validating resource classes based on the concepts presented in \cite{bv11}. See Section \ref{bv_support} for more information on implementation requirements. 5 | 6 | \section{Constraint Annotations} 7 | \label{constraint_annotations} 8 | 9 | The Server API provides support for extracting request values and mapping them into Java fields, properties and parameters using annotations such as \code{@HeaderParam}, \code{@QueryParam}, etc. It also supports mapping of request entity bodies into Java objects via non-annotated parameters (i.e., parameters without any JAX-RS annotations). See Chapter \ref{resources} for additional information. 10 | 11 | In earlier versions of JAX-RS, any additional validation of these values needed to be performed programmatically. This version of JAX-RS introduces support for declarative validation based on the Bean Validation specification \cite{bv11}. 12 | 13 | The Bean Validation specification \cite{bv11} supports the use of \emph{constraint annotations} as a way of declaratively validating beans, method parameters and method returned values. For example, consider the following resource class augmented with constraint annotations: 14 | 15 | \begin{listing}{1} 16 | @Path("/") 17 | class MyResourceClass { 18 | 19 | @POST 20 | @Consumes("application/x-www-form-urlencoded") 21 | public void registerUser( 22 | @NotNull @FormParam("firstName") String firstName, 23 | @NotNull @FormParam("lastName") String lastName, 24 | @Email @FormParam("email") String email) { 25 | ... 26 | } 27 | } 28 | \end{listing} 29 | 30 | The annotations \NotNull\ and \Email\ impose additional constraints on the form parameters \code{firstName}, \code{lastName} and \code{email}. The \NotNull\ constraint is built-in to the Bean Validation API; the \Email\ constraint is assumed to be user defined in the example above. These constraint annotations are not restricted to method parameters, they can be used in any location in which the JAX-RS binding annotations are allowed with the exception of constructors and property setters. Rather than using method parameters, the \code{MyResourceClass} shown above could have been written as follows: 31 | 32 | \begin{listing}{1} 33 | @Path("/") 34 | class MyResourceClass { 35 | 36 | @NotNull @FormParam("firstName") 37 | private String firstName; 38 | 39 | @NotNull @FormParam("lastName") 40 | private String lastName; 41 | 42 | private String email; 43 | 44 | @FormParam("email") 45 | public void setEmail(String email) { 46 | this.email = email; 47 | } 48 | 49 | @Email 50 | public String getEmail() { 51 | return email; 52 | } 53 | ... 54 | } 55 | \end{listing} 56 | 57 | Note that in this version, \code{firstName} and \code{lastName} are fields initialized via injection and \code{email} is a resource class property. Constraint annotations on properties are specified in their corresponding getters. 58 | 59 | Constraint annotations are also allowed on resource classes. In addition to annotating fields and properties, an annotation can be defined for the entire class. Let us assume that \code{@NonEmptyNames} validates that one of the two \emph{name} fields in \code{MyResourceClass} is provided. Using such an annotation, the example above can be extended as follows: 60 | 61 | \begin{listing}{1} 62 | @Path("/") 63 | @NonEmptyNames 64 | class MyResourceClass { 65 | 66 | @NotNull @FormParam("firstName") 67 | private String firstName; 68 | 69 | @NotNull @FormParam("lastName") 70 | private String lastName; 71 | 72 | private String email; 73 | ... 74 | } 75 | \end{listing} 76 | 77 | Constraint annotations on resource classes are useful for defining cross-field and cross-property constraints. 78 | 79 | \section{Annotations and Validators} 80 | \label{annotations_and_validators} 81 | 82 | Annotation constraints and validators are defined in accordance with the Bean Validation specification \cite{bv11}. The \Email\ annotation shown above is defined using the Bean Validation \Constraint\ meta-annotation: 83 | 84 | \begin{listing}{1} 85 | @Target( { METHOD, FIELD, PARAMETER }) 86 | @Retention(RUNTIME) 87 | @Constraint(validatedBy = EmailValidator.class) 88 | public @interface Email { 89 | String message() default "{com.example.validation.constraints.email}"; 90 | Class[] groups() default {}; 91 | Class[] payload() default {}; 92 | } 93 | \end{listing} 94 | 95 | The \Constraint\ annotation must include a reference to the validator class that will be used to validate decorated values. The \code{EmailValidator} class must implement \code{ConstraintValidator} where \code{T} is the type of values being validated. For example, 96 | 97 | \begin{listing}{1} 98 | public class EmailValidator implements ConstraintValidator { 99 | public void initialize(Email email) { 100 | ... 101 | } 102 | 103 | public boolean isValid(String value, ConstraintValidatorContext context) { 104 | ... 105 | } 106 | } 107 | \end{listing} 108 | 109 | Thus, \code{EmailValidator} applies to values annotated with \Email\ that are of type \code{String}. Validators for different types can be defined for the same constraint annotation. 110 | 111 | Constraint annotations must also define a \code{groups} element to indicate which processing groups they are associated with. If no groups are specified (as in the example above) the \code{Default} group is assumed. For simplicity, \jaxrs\ implementations are NOT REQUIRED to support processing groups other than \code{Default}. In what follows, we assume that constraint validation is carried out in the \code{Default} processing group. 112 | 113 | \section{Entity Validation} 114 | \label{entity_validation} 115 | 116 | Request entity bodies can be mapped to resource method parameters. There are two ways in which these entities can be validated. If the request entity is mapped to a Java bean whose class is decorated with Bean Validation annotations, then validation can be enabled using \Valid: 117 | 118 | \begin{listing}{1} 119 | @StandardUser 120 | class User { 121 | 122 | @NotNull 123 | private String firstName; 124 | ... 125 | } 126 | 127 | @Path("/") 128 | class MyResourceClass { 129 | 130 | @POST 131 | @Consumes("application/xml") 132 | public void registerUser(@Valid User user) { 133 | ... 134 | } 135 | } 136 | \end{listing} 137 | 138 | In this case, the validator associated with \code{@StandardUser} (as well as those for non-class level constraints like \code{@NotNull}) will be called to verify the request entity mapped to \code{user}. Alternatively, a new annotation can be defined and used directly on the resource method parameter. 139 | 140 | \begin{listing}{1} 141 | @Path("/") 142 | class MyResourceClass { 143 | 144 | @POST 145 | @Consumes("application/xml") 146 | public void registerUser(@PremiumUser User user) { 147 | ... 148 | } 149 | } 150 | \end{listing} 151 | 152 | In the example above, \code{@PremiumUser} rather than \code{@StandardUser} will be used to validate the request entity. These two ways in which validation of entities can be triggered can also be combined by including \Valid\ in the list of constraints. The presence of \Valid\ will trigger validation of \emph{all} the constraint annotations decorating a Java bean class. This validation will take place in the \code{Default} processing group unless the \code{@ConvertGroup} annotation is present. See \cite{bv11} for more information on \code{@ConvertGroup}. 153 | 154 | Response entity bodies returned from resource methods can be validated in a similar manner by annotating the resource method itself. To exemplify, assuming both \code{@StandardUser} and \code{@PremiumUser} are required to be checked before returning a user, the \code{getUser} method can be annotated as shown next: 155 | 156 | \begin{listing}{1} 157 | @Path("/") 158 | class MyResourceClass { 159 | 160 | @GET 161 | @Path("{id}") 162 | @Produces("application/xml") 163 | @Valid @PremiumUser 164 | public User getUser(@PathParam("id") String id) { 165 | User u = findUser(id); 166 | return u; 167 | } 168 | ... 169 | } 170 | \end{listing} 171 | 172 | Note that \code{@PremiumUser} is explicitly listed and \code{@StandardUser} is triggered by the presence of the \Valid\ annotation ---see definition of \code{User} class earlier in this section. 173 | 174 | \section{Default Validation Mode} 175 | \label{default_validation_mode} 176 | 177 | According to \cite{bv11}, validation is enabled by default only for the so called {\em constrained} methods. Getter methods as defined by the Java Beans specification are not constrained methods, so they will not be validated by default. The special annotation \code{@ValidateOnExecution} defined in \cite{bv11} can be used to selectively enable and disable validation. For example, you can enable validation on method \code{getEmail} shown above as follows: 178 | 179 | \begin{listing}{1} 180 | @Path("/") 181 | class MyResourceClass { 182 | 183 | @Email 184 | @ValidateOnExecution 185 | public String getEmail() { 186 | return email; 187 | } 188 | ... 189 | } 190 | \end{listing} 191 | 192 | The default value for the \code{type} attribute of \code{@ValidateOnExecution} is \code{IMPLICIT} which, in the example above, results in method \code{getEmail} being validated. See \cite{bv11} for more information on other uses of this annotation. 193 | 194 | Note that if validation for getter methods is {\em enabled} and a resource method's signature obeys the rules for getters, the resource method may be (unintentionally) invoked during validation. Conversely, if validation for getter methods is {\em disabled} and the {\em matching} resource method's signature obeys the rules for getters, the JAX-RS runtime will still validate the method (i.e., the validation preference will be ignored) before invocation. 195 | 196 | \section{Annotation Inheritance} 197 | \label{annotation_inheritance} 198 | 199 | The rules for inheritance of constraint annotation are defined in \cite{bv11}. It is worth noting that these rules are incompatible with those defined in Section \ref{annotationinheritance}. Generally speaking, constraint annotations in \cite{bv11} are cumulative (can be strengthen) across a given type hierarchy while \jaxrs\ annotations are inherited or, overridden and ignored. 200 | 201 | The goal of this specification is to enable validation of \jaxrs\ resources by leveraging existing Bean Validation implementations. Therefore, \jaxrs\ implementations MUST follow the constraint annotation rules defined in \cite{bv11}. 202 | 203 | \section{Validation and Error Reporting} 204 | \label{validation_and_error_reporting} 205 | 206 | Constraint annotations are allowed in the same locations as the following annotations: \MatrixParam, \QueryParam, \PathParam, \CookieParam, \HeaderParam\ and \Context, {\em except} in class constructors and property setters. Specifically, they are allowed in resource method parameters, fields and property getters as well as resource classes, entity parameters and resource methods (return values). 207 | 208 | The default resource class instance lifecycle is per-request in JAX-RS. Implementations MAY support other lifecycles; the same caveats related to the use of other JAX-RS annotations in resource classes apply to constraint annotations. For example, a constraint validation annotating a constructor parameter in a resource class whose lifecycle is singleton will only be executed once. 209 | 210 | \jaxrs\ implementations SHOULD use the following process to validate resource class instances after they have been instantiated: 211 | 212 | \begin{description} 213 | \item[Phase 1] Inject field values and initialize bean properties as described in Section \ref{resource_field}. 214 | \item[Phase 2] Validate annotations on fields, property getters (if enabled) and the resource class. The order in which these validations are executed is implementation dependent. 215 | \item[Phase 3] Validate annotations on parameters passed to the resource method matched. 216 | \item[Phase 4] If no constraint violations found thus far, invoke resource method and validate returned value. 217 | \end{description} 218 | 219 | The exception model in \cite{bv11} defines a base class \code{javax.validation.ValidationException} and a few subclasses to report errors that are specific to constraint definitions, constraint declarations, group definitions and constraint violations. \jaxrs\ implementations MUST provide a default exception mapper (see Section~\ref{exceptionmapper}) for \code{javax.validation.ValidationException} according to the following rules: 220 | 221 | \begin{enumerate} 222 | \item If the exception is of type \code{javax.validation.ValidationException} or any of its subclasses {\em excluding} \code{javax.validation.ConstraintViolationException}, then it is mapped to a response with status code 500 (Internal Server Error). 223 | \item If the exception is an instance of \code{javax.validation.ConstraintViolationException}, then: 224 | \begin{enumerate} 225 | \item If the exception was thrown while validating a method return type, then it is mapped to a response with status code 500 (Internal Server Error) \footnote{The property path of a {\code ConstraintViolation} provides information about the location from which an exception originated. See Javadoc for more information.}. 226 | \item Otherwise, it is mapped to a response with status code 400 (Bad Request). 227 | \end{enumerate} 228 | \end{enumerate} 229 | 230 | In all cases, \jaxrs\ implementations SHOULD include a response entity describing the source of the error; however, the exact content and format of this entity is beyond the scope of this specification. As described in Section~\ref{exceptionmapper}, applications can provide their own exception mappers and, consequently, customize the default mapper described above. 231 | 232 | 233 | 234 | 235 | 236 | -------------------------------------------------------------------------------- /chapters/clientapi.tex: -------------------------------------------------------------------------------- 1 | \chapter{Client API} 2 | \label{client_api} 3 | 4 | The Client API is used to access Web resources. It provides a higher-level API than \code{HttpURLConnection} as well as integration with JAX-RS providers. Unless otherwise stated, types presented in this chapter live in the \code{javax.ws.rs.client} package. 5 | 6 | \section{Bootstrapping a Client Instance} 7 | 8 | An instance of \Client\ is required to access a Web resource using the Client API. The default instance of \Client\ can be obtained by calling \code{newClient} on \ClientBuilder. \Client\ instances can be configured using methods inherited from \code{Configurable} as follows: 9 | 10 | \begin{listing}{1} 11 | // Default instance of client 12 | Client client = ClientBuilder.newClient(); 13 | 14 | // Additional configuration of default client 15 | client.property("MyProperty", "MyValue") 16 | .register(MyProvider.class) 17 | .register(MyFeature.class); 18 | \end{listing} 19 | 20 | See Chapter \ref{providers} for more information on providers. Properties are simply name-value pairs where the value is an arbitrary object. Features are also providers and must implement the \code{Feature} interface; they are useful for grouping sets of properties and providers (including other features) that are logically related and must be enabled as a unit. 21 | 22 | \section{Resource Access} 23 | \label{resource_access} 24 | 25 | A Web resource can be accessed using a fluent API in which method invocations are chained to build and ultimately submit an HTTP request. The following example gets a \code{text/plain} representation of the resource identified by \code{http://example.org/hello}: 26 | 27 | \begin{listing}{1} 28 | Client client = ClientBuilder.newClient(); 29 | Response res = client.target("http://example.org/hello") 30 | .request("text/plain").get(); 31 | \end{listing} 32 | 33 | Conceptually, the steps required to submit a request are the following: (i) obtain an instance of \Client\ (ii) create a \WebTarget\ (iii) create a request from the \WebTarget\ and (iv) submit a request or get a prepared \Invocation\ for later submission. See Section \ref{invocations} for more information on using \Invocation. 34 | 35 | Method chaining is not limited to the example shown above. A request can be further specified by setting headers, cookies, query parameters, etc. For example: 36 | 37 | \begin{listing}{1} 38 | Response res = client.target("http://example.org/hello") 39 | .queryParam("MyParam","...") 40 | .request("text/plain") 41 | .header("MyHeader", "...") 42 | .get(); 43 | \end{listing} 44 | 45 | See the Javadoc for the classes in the \code{javax.ws.rs.client} package for more information. 46 | 47 | \section{Client Targets} 48 | 49 | The benefits of using a \WebTarget\ become apparent when building complex URIs, for example by extending base URIs with additional path segments or templates. The following example highlights these cases: 50 | 51 | \begin{listing}{1} 52 | WebTarget base = client.target("http://example.org/"); 53 | WebTarget hello = base.path("hello").path("{whom}"); 54 | Response res = hello.resolveTemplate("whom", "world").request("...").get(); 55 | \end{listing} 56 | 57 | Note the use of the URI template parameter~\code{\{whom\}}. The example above gets a representation for the resource identified by \code{http://example.org/hello/world}. 58 | 59 | \WebTarget\ instances are {\em immutable} with respect to their URI (or URI template): methods for specifying additional path segments and parameters return a new instance of \WebTarget. However, \WebTarget\ instances are {\em mutable} with respect to their configuration. Thus, configuring a \WebTarget\ does not create new instances. 60 | 61 | \begin{listing}{1} 62 | // Create WebTarget instance base 63 | WebTarget base = client.target("http://example.org/"); 64 | // Create new WebTarget instance hello and configure it 65 | WebTarget hello = base.path("hello"); 66 | hello.register(MyProvider.class); 67 | \end{listing} 68 | 69 | In this example, two instances of \WebTarget\ are created. The instance \code{hello} inherits the configuration from \code{base} and it is further configured by registering \code{MyProvider.class}. Note that changes to \code{hello}'s configuration do not affect \code{base}, i.e.~inheritance performs a {\em deep} copy of the configuration. See Section \ref{configurable_types} for additional information on configurable types. 70 | 71 | \section{Typed Entities} 72 | 73 | The response to a request is not limited to be of type \Response. The following example upgrades the status of customer number 123 to ``gold status'' by first obtaining an entity of type \code{Customer} and then posting that entity to a different URI: 74 | 75 | \begin{listing}{1} 76 | Customer c = client.target("http://examples.org/customers/123") 77 | .request("application/xml").get(Customer.class); 78 | String newId = client.target("http://examples.org/gold-customers/") 79 | .request().post(xml(c), String.class); 80 | \end{listing} 81 | 82 | Note the use of the {\em variant} \code{xml()} in the call to \code{post}. The class \code{javax.ws.rs.client.Entity} defines variants for the most popular media types used in JAX-RS applications. 83 | 84 | In the example above, just like in the Server API, \jaxrs\ implementations are REQUIRED to use entity providers to map a representation of type \code{application/xml} to an instance of \code{Customer} and vice versa. See Section \ref{standard_entity_providers} for a list of entity providers that MUST be supported by all \jaxrs\ implementations. 85 | 86 | \section{Invocations} 87 | \label{invocations} 88 | 89 | An invocation is a request that has been prepared and is ready for execution. Invocations provide a {\em generic interface} that enables a separation of concerns between the creator and the submitter. In particular, the submitter does not need to know how the invocation was prepared, but only how it should be executed: namely, synchronously or asynchronously. 90 | 91 | Let us consider the following example\footnote{The Collections class in this example is arbitrary and does not correspond to any specific implementation. There are a number of Java collection libraries available that provide this type of functionality.}: 92 | 93 | \begin{listing}{1} 94 | // Executed by the creator 95 | Invocation inv1 = client.target("http://examples.org/atm/balance") 96 | .queryParam("card", "111122223333").queryParam("pin", "9876") 97 | .request("text/plain").buildGet(); 98 | Invocation inv2 = client.target("http://examples.org/atm/withdrawal") 99 | .queryParam("card", "111122223333").queryParam("pin", "9876") 100 | .request().buildPost(text("50.0")); 101 | Collection invs = Arrays.asList(inv1, inv2); 102 | 103 | // Executed by the submitter 104 | Collection ress = 105 | Collections.transform(invs, 106 | new F() { 107 | @Override 108 | public Response apply(Invocation inv) { 109 | return inv.invoke(); } }); 110 | \end{listing} 111 | 112 | In this example, two invocations are prepared and stored in a collection by the creator. The submitter then traverses the collection applying a transformation that maps an \Invocation\ to a \Response. The mapping calls \code{Invocation.invoke} to execute the invocation synchronously; asynchronous execution is also supported by calling \code{Invocation.submit}. Refer to 113 | Chapter~\ref{asynchronous_processing} for more information on asynchronous invocations. 114 | 115 | \section{Configurable Types} 116 | \label{configurable_types} 117 | 118 | The following Client API types are configurable: \Client, \ClientBuilder, and \WebTarget. Configuration methods are inherited from the \code{Configurable} interface implemented by all these classes. This interface supports configuration of: 119 | 120 | \begin{description} 121 | \item [Properties] Name-value pairs for additional configuration of features or other components of a \jaxrs\ implementation. 122 | \item [Features] A special type of provider that implement the \code{Feature} interface and can be used to configure a \jaxrs\ implementation. 123 | \item [Providers] Classes or instances of classes that implement one or more of the provider interfaces from Chapter \ref{providers}. A provider can be a message body reader, a filter, a context resolver, etc. 124 | \end{description} 125 | 126 | The configuration defined on an instance of any of the aforementioned types is inherited by other instances created from it. For example, an instance of \WebTarget\ created from a \Client\ will inherit the \Client's configuration. However, any additional changes to the instance of \WebTarget\ will not impact the \Client's configuration and vice versa. Therefore, once a configuration is inherited it is also detached (deep copied) from its parent configuration and changes to the parent and child configurations are not be visible to each other. 127 | 128 | \subsection{Filters and Entity Interceptors} 129 | \label{filters_interceptors_client} 130 | 131 | As explained in Chapter \ref{filters_and_interceptors}, filters and interceptors are defined as JAX-RS providers. Therefore, they can be registered in any of the configurable types listed in the previous section. The following example shows how to register filters and interceptors on instances of \Client\ and \WebTarget: 132 | 133 | \begin{listing}{1} 134 | // Create client and register logging filter 135 | Client client = ClientBuilder.newClient().register(LoggingFilter.class); 136 | 137 | // Executes logging filter from client and caching filter from target 138 | WebTarget wt = client.target("http://examples.org/customers/123"); 139 | Customer c = wt.register(CachingFilter.class).request("application/xml") 140 | .get(Customer.class); 141 | \end{listing} 142 | 143 | In this example, \code{LoggingFilter} is inherited by each instance of \WebTarget\ created from \code{client}; an additional provider named \code{CachingFilter} is registered on the instance of \WebTarget. 144 | 145 | \section{Reactive Clients} 146 | \label{reactive_clients} 147 | 148 | Section \ref{client_api_async} introduces asynchronous programming in the Client API. Asynchronous programming in \jaxrs\ enables clients to unblock certain threads by pushing work to background threads which can be monitored and possibly waited on (joined) at a later time. This can be accomplished in \jaxrs\ by either providing an instance of \code{InvocationCallback} or operating on the result of type \code{Future} returned by an asynchronous invoker ---or some combination of both styles. 149 | 150 | Using \code{InvocationCallback} enables a more \emph{reactive} programming style in which user-provided code activates (or reacts) only when a certain event has occurred. Using callbacks works well for simple cases, but the source code becomes harder to understand when multiple events are in play. For example, when asynchronous invocations need to be composed, combined or in any way operated upon. These type of scenarios may result in callbacks that are nested inside other callbacks making the code far less readable ---often referred to as the \emph{pyramid of doom} because of the inherent nesting of calls. 151 | 152 | To address the requirement of greater readability and to enable programmers to better reason about asynchronous computations, Java 8 introduces the a new interface called \code{CompletionStage} that includes a large number of methods dedicated to managing asynchronous computations. 153 | 154 | \jaxrs\ 2.1 defines a new type of invoker called \code{RxInvoker}, as well a default implementation of this type called \code{CompletionStageRxInvoker} that is based on the Java 8 type \code{CompletionStage}. There is a new \code{rx} method which is used in a similar manner to \code{async} as described in \ref{client_api_async}. Let us consider the following example: 155 | 156 | \begin{listing}{1} 157 | CompletionStage csf = client.target("forecast/{destination}") 158 | .resolveTemplate("destination", "mars") 159 | .request() 160 | .rx() 161 | .get(String.class); 162 | 163 | csf.thenAccept(System.out::println); 164 | \end{listing} 165 | 166 | This example first creates an asynchronous computation of type \code{CompletionStage}, and then simply waits for it to complete and displays its result (technically, a second computation of type \code{CompletionStage} is created on the last line simply to consume the result of the first computation). 167 | 168 | The value of \code{CompletionStage} becomes apparent when multiple asynchronous computations are necessary to accomplish a task. The following example obtains, in parallel, a price and a forecast for a destination and makes a reservation only if the desired conditions are met. 169 | 170 | \begin{listing}{1} 171 | CompletionStage csp = client.target("price/{destination}") 172 | .resolveTemplate("destination", "mars") 173 | .request() 174 | .rx() 175 | .get(Number.class); 176 | 177 | CompletionStage csf = client.target("forecast/{destination}") 178 | .resolveTemplate("destination", "mars") 179 | .request() 180 | .rx() 181 | .get(String.class); 182 | 183 | csp.thenCombine(csf, (price, forecast) -> 184 | reserveIfAffordableAndWarm(price, forecast)); 185 | \end{listing} 186 | 187 | Note that the \code{Consumer} passed in the call to method \code{thenCombine} requires the values of each stage to be available and, therefore, can only be executed after the two parallel stages are completed. 188 | 189 | As we shall see in the next section, support for \code{CompletionStage} is the \emph{default} for all \jaxrs\ implementations, but other reactive APIs may also be supported as extensions. 190 | 191 | \subsection{Reactive API Extensions} 192 | \label{reactive_api_extensions} 193 | 194 | There have been several proposals for reactive APIs in Java. All \jaxrs\ implementations MUST support an invoker for \code{CompletionStage} as shown above. Additionally, \jaxrs\ implementations MAY support other reactive APIs using an extension built into the Client API. 195 | 196 | RxJava \cite{rxjava} is a popular reactive library available in Java. The type representing an asynchronous computation in this API is called an \code{Observable}. An implementation may support this type by providing a new invoker as shown in the following example: 197 | 198 | \begin{listing}{1} 199 | Client client = client.register(ObservableRxInvokerProvider.class); 200 | 201 | Observable of = client.target("forecast/{destination}") 202 | .resolveTemplate("destination", "mars") 203 | .request() 204 | .rx(ObservableRxInvoker.class) // overrides default invoker 205 | .get(String.class); 206 | 207 | of.subscribe(System.out::println); 208 | \end{listing} 209 | 210 | First, a provider for the new invoker must be registered on the \code{Client} object. Second, the type of the invoker must be specified as a parameter to the \code{rx} method. Note that because this is a \jaxrs\ extension, the actual names for the provider and the invoker in the example above are implementation dependent. The reader is referred to the documentation for the \jaxrs\ implementation of choice for more information. 211 | 212 | Version 2.0 of RxJava \cite{rxjava2} has been completely re-written on top of the Reactive-Streams specification. This new architecture prompted the introduction of a new type called \code{Flowable}. JAX-RS implementations could easily support this new version by implementing a new provider (such as \code{FlowableRxInvokerProvider}) and using the same pattern shown in the example above. 213 | 214 | \section{Executor Services} 215 | \label{executor_services} 216 | 217 | Executor services can be used to submit asynchronous tasks for execution. \jaxrs\ applications can specify executor services while building a \code{Client} instance. Two methods are provided in \code{ClientBuilder} for this purpose, namely, \code{executorService} and \code{scheduledExecutorService}. 218 | 219 | In an environment that supports the Concurrency Utilities for Java EE \cite{concurrencyee}, such as the Java EE Full Profile, implementations MUST use \code{ManagedExecutorService} and \code{ManagedScheduledExecutorService}, respectively. The reader is referred to the Javadoc of \code{ClientBuilder} for more information about executor services. 220 | 221 | -------------------------------------------------------------------------------- /references.bib: -------------------------------------------------------------------------------- 1 | %% This BibTeX bibliography file was created using BibDesk. 2 | %% http://bibdesk.sourceforge.net/ 3 | 4 | 5 | %% Created for Marc Hadley at 2008-12-08 16:37:14 -0500 6 | 7 | 8 | %% Saved with string encoding Unicode (UTF-8) 9 | 10 | 11 | 12 | @techreport{xml10, 13 | Author = {Tim Bray and Jean Paoli and C. M. Sperberg-McQueen and Eve Maler}, 14 | Institution = {W3C}, 15 | Month = {October}, 16 | Note = {See http://www.w3.org/TR/2000/REC-xml-20001006}, 17 | Title = {Extensible {Markup} {Language} ({XML}) 1.0 ({Second} {Edition})}, 18 | Type = {{Recommendation}}, 19 | Year = 2000} 20 | 21 | @techreport{soap11, 22 | Author = {Don Box and David Ehnebuske and Gopal Kakivaya and Andrew Layman and Noah Mendelsohn and Henrik Nielsen and Satish Thatte and Dave Winer}, 23 | Institution = {W3C}, 24 | Month = {May}, 25 | Note = {See http://www.w3.org/TR/SOAP/}, 26 | Title = {Simple {Object} {Access} {Protocol} ({SOAP}) 1.1}, 27 | Type = {{Note}}, 28 | Year = 2000} 29 | 30 | @techreport{soap12p1, 31 | Author = {Martin Gudgin and Marc Hadley and Noah Mendelsohn and Jean-Jacques Moreau and Henrik {Frystyk Nielsen}}, 32 | Institution = {W3C}, 33 | Month = {June}, 34 | Note = {See http://www.w3.org/TR/2003/REC-soap12-part1-20030624}, 35 | Title = {{SOAP} {Version} 1.2 {Part} 1: {Messaging} {Framework}}, 36 | Type = {{Recommendation}}, 37 | Year = 2003} 38 | 39 | @techreport{soap12p2, 40 | Author = {Martin Gudgin and Marc Hadley and Noah Mendelsohn and Jean-Jacques Moreau and Henrik {Frystyk Nielsen}}, 41 | Institution = {W3C}, 42 | Month = {June}, 43 | Note = {See http://www.w3.org/TR/2003/REC-soap12-part2-20030624}, 44 | Title = {{SOAP} {Version} 1.2 {Part} 2: {Adjuncts}}, 45 | Type = {{Recommendation}}, 46 | Year = 2003} 47 | 48 | @techreport{wsdl11, 49 | Author = {Erik Christensen and Francisco Curbera and Greg Meredith and Sanjiva Weerawarana}, 50 | Institution = {W3C}, 51 | Month = {March}, 52 | Note = {See http://www.w3.org/TR/2001/NOTE-wsdl-20010315}, 53 | Title = {Web {Services} {Description} {Language} ({WSDL}) 1.1}, 54 | Type = {{Note}}, 55 | Year = 2001} 56 | 57 | @techreport{jaxrpc10, 58 | Author = {Rahul Sharma}, 59 | Institution = {JCP}, 60 | Month = {June}, 61 | Note = {See http://jcp.org/en/jsr/detail?id=101}, 62 | Title = {The {Java} {API} for {XML} {Based} {RPC} ({JAX-RPC}) 1.0}, 63 | Type = {{JSR}}, 64 | Year = 2002} 65 | 66 | @techreport{jaxrpc11, 67 | Author = {Roberto Chinnici}, 68 | Institution = {JCP}, 69 | Month = {August}, 70 | Note = {See http://jcp.org/en/jsr/detail?id=101}, 71 | Title = {The {Java} {API} for {XML} {Based} {RPC} ({JAX-RPC}) 1.1}, 72 | Type = {{Maintenance JSR}}, 73 | Year = 2003} 74 | 75 | @techreport{jaxb10, 76 | Author = {Joseph Fialli and Sekhar Vajjhala}, 77 | Institution = {JCP}, 78 | Month = {January}, 79 | Note = {See http://jcp.org/en/jsr/detail?id=31}, 80 | Title = {The {Java} {Architecture} for {XML} {Binding} ({JAXB})}, 81 | Type = {{JSR}}, 82 | Year = 2003} 83 | 84 | @techreport{jaxb20, 85 | Author = {Joseph Fialli and Sekhar Vajjhala}, 86 | Institution = {JCP}, 87 | Month = {August}, 88 | Note = {See http://jcp.org/en/jsr/detail?id=222}, 89 | Title = {The {Java} {Architecture} for {XML} {Binding} ({JAXB}) 2.0}, 90 | Type = {{JSR}}, 91 | Year = 2003} 92 | 93 | @techreport{wsdl20p1, 94 | Author = {Roberto Chinnici and Martin Gudgin and Jean-Jacques Moreau and Jeffrey Schlimmer and Sanjiva Weerawarana}, 95 | Institution = {W3C}, 96 | Month = {August}, 97 | Note = {See http://www.w3.org/TR/2004/WD-wsdl20-20040803}, 98 | Title = {Web {Services} {Description} {Language} ({WSDL}) {Version} 2.0 {Part} 1: {Core} {Language} }, 99 | Type = {{Working Draft}}, 100 | Year = 2004} 101 | 102 | @techreport{wsdl20p2, 103 | Author = {Martin Gudgin and Amy Lewis and Jeffrey Schlimmer}, 104 | Institution = {W3C}, 105 | Month = {August}, 106 | Note = {See http://www.w3.org/TR/2004/WD-wsdl20-extensions-20040803}, 107 | Title = {Web {Services} {Description} {Language} ({WSDL}) {Version} 2.0 {Part} 2: {Predefined} {Extensions}}, 108 | Type = {{Working Draft}}, 109 | Year = 2004} 110 | 111 | @techreport{wsdl20p3, 112 | Author = {Hugo Haas and Philippe Le H\'egaret and Jean-Jacques Moreau and David Orchard and Jeffrey Schlimmer and Sanjiva Weerawarana}, 113 | Institution = {W3C}, 114 | Month = {August}, 115 | Note = {See http://www.w3.org/TR/2004/WD-wsdl20-bindings-20040803}, 116 | Title = {Web {Services} {Description} {Language} ({WSDL}) {Version} 2.0 {Part} 3: {Bindings} }, 117 | Type = {{Working Draft}}, 118 | Year = 2004} 119 | 120 | @techreport{stax, 121 | Author = {Christopher Fry}, 122 | Institution = {JCP}, 123 | Month = {March}, 124 | Note = {See http://jcp.org/en/jsr/detail?id=173}, 125 | Title = {Streaming {API} for {XML} (StAX)}, 126 | Type = {{JSR}}, 127 | Year = 2003} 128 | 129 | @techreport{wsibp10, 130 | Author = {Keith Ballinger and David Ehnebuske and Martin Gudgin and Mark Nottingham and Prasad Yendluri}, 131 | Institution = {WS-I}, 132 | Month = {April}, 133 | Note = {See http://www.ws-i.org/Profiles/BasicProfile-1.0-2004-04-16.html}, 134 | Title = {Basic {Profile} {Version} 1.0}, 135 | Type = {{Final Material}}, 136 | Year = 2004} 137 | 138 | @techreport{wsibp11, 139 | Author = {Keith Ballinger and David Ehnebuske and Chris Ferris and Martin Gudgin and Canyang Kevin Liu and Mark Nottingham and Jorgen Thelin and Prasad Yendluri}, 140 | Institution = {WS-I}, 141 | Month = {August}, 142 | Note = {See http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html}, 143 | Title = {Basic {Profile} {Version} 1.1}, 144 | Type = {{Final Material}}, 145 | Year = 2004} 146 | 147 | @techreport{wsiap10, 148 | Author = {Chris Ferris and Anish Karmarkar and Canyang Kevin Liu}, 149 | Institution = {WS-I}, 150 | Month = {August}, 151 | Note = {See http://www.ws-i.org/Profiles/AttachmentsProfile-1.0-2004-08-24.html}, 152 | Title = {Attachments {Profile} {Version} 1.0}, 153 | Type = {{Final Material}}, 154 | Year = 2004} 155 | 156 | @techreport{swa, 157 | Author = {John Barton and Satish Thatte and Henrik Frystyk Nielsen}, 158 | Institution = {W3C}, 159 | Month = {December}, 160 | Note = {http://www.w3.org/TR/SOAP-attachments}, 161 | Title = {{SOAP} {Messages} {With} {Attachments}}, 162 | Type = {Note}, 163 | Year = 2000} 164 | 165 | @techreport{mtom, 166 | Author = {Martin Gudgin and Noah Mendelsohn and Mark Nottingham and Herve Ruellan}, 167 | Institution = {W3C}, 168 | Month = {January}, 169 | Note = {http://www.w3.org/TR/soap12-mtom/}, 170 | Title = {{SOAP} {Message} {Transmission} {Optimization} {Mechanism}}, 171 | Type = {Recommendation}, 172 | Year = 2005} 173 | 174 | @techreport{xop, 175 | Author = {Martin Gudgin and Noah Mendelsohn and Mark Nottingham and Herve Ruellan}, 176 | Institution = {W3C}, 177 | Month = {January}, 178 | Note = {http://www.w3.org/TR/xop10/}, 179 | Title = {{XML-binary} {Optimized} {Packaging}}, 180 | Type = {Recommendation}, 181 | Year = 2005} 182 | 183 | @techreport{wsissbp10, 184 | Author = {Mark Nottingham}, 185 | Institution = {WS-I}, 186 | Month = {August}, 187 | Note = {See http://www.ws-i.org/Profiles/SimpleSoapBindingProfile-1.0-2004-08-24.html}, 188 | Title = {Simple {SOAP} {Binding} {Profile} {Version} 1.0}, 189 | Type = {{Working Group Draft}}, 190 | Year = 2004} 191 | 192 | @techreport{jaxr, 193 | Author = {Farrukh Najmi}, 194 | Institution = {JCP}, 195 | Month = {June}, 196 | Note = {See http://www.jcp.org/en/jsr/detail?id=93}, 197 | Title = {Java {API} for {XML} {Registries} 1.0 ({JAXR}) }, 198 | Type = {{JSR}}, 199 | Year = 2002} 200 | 201 | @techreport{xmlinfoset, 202 | Author = {John Cowan and Richard Tobin}, 203 | Institution = {W3C}, 204 | Month = {October}, 205 | Note = {See http://www.w3.org/TR/2001/REC-xml-infoset-20011024/}, 206 | Title = {{XML} {Information} {Set}}, 207 | Type = {{Recommendation}}, 208 | Year = 2001} 209 | 210 | @techreport{rfc2119, 211 | Author = {S. Bradner}, 212 | Institution = {IETF}, 213 | Month = {March}, 214 | Note = {See http://www.ietf.org/rfc/rfc2119.txt}, 215 | Title = {{RFC} 2119: {Keywords} for use in {RFCs} to {Indicate} {Requirement} {Levels}}, 216 | Type = {{RFC}}, 217 | Year = 1997} 218 | 219 | @techreport{xsdp1, 220 | Author = {Henry S. Thompson and David Beech and Murray Maloney and Noah Mendelsohn}, 221 | Institution = {W3C}, 222 | Month = {May}, 223 | Note = {See http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/}, 224 | Title = {{XML} {Schema} {Part} 1: {Structures}}, 225 | Type = {{Recommendation}}, 226 | Year = 2001} 227 | 228 | @techreport{xsdp2, 229 | Author = {Paul V. Biron and Ashok Malhotra}, 230 | Institution = {W3C}, 231 | Month = {May}, 232 | Note = {See http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/}, 233 | Title = {{XML} {Schema} {Part} 2: {Datatypes}}, 234 | Type = {{Recommendation}}, 235 | Year = 2001} 236 | 237 | @techreport{uri, 238 | Author = {T. Berners-Lee and R. Fielding and L. Masinter}, 239 | Institution = {IETF}, 240 | Month = {January}, 241 | Note = {See http://www.ietf.org/rfc/rfc3986.txt}, 242 | Title = {{RFC} 3986: {Uniform} {Resource} {Identifier} ({URI}): {Generic} {Syntax}}, 243 | Type = {{RFC}}, 244 | Year = 2005} 245 | 246 | @techreport{jsr109, 247 | Author = {Jim Knutson and Heather Kreger}, 248 | Institution = {JCP}, 249 | Month = {September}, 250 | Note = {See http://jcp.org/en/jsr/detail?id=109}, 251 | Title = {Web {Services} for {J2EE}}, 252 | Type = {{JSR}}, 253 | Year = 2002} 254 | 255 | @techreport{jaf, 256 | Author = {Bill Shannon}, 257 | Institution = {JCP}, 258 | Month = {May}, 259 | Note = {See http://jcp.org/en/jsr/detail?id=925}, 260 | Title = {{JavaBeans} {Activation} {Framework}}, 261 | Type = {{JSR}}, 262 | Year = 2006} 263 | 264 | @techreport{jsr175, 265 | Author = {Joshua Bloch}, 266 | Date-Modified = {2008-12-08 16:37:00 -0500}, 267 | Institution = {JCP}, 268 | Keywords = {java}, 269 | Month = {August}, 270 | Note = {See http://jcp.org/en/jsr/detail?id=175}, 271 | Title = {A {Metadata} {Facility} for the {Java} {Programming} {Language}}, 272 | Type = {{JSR}}, 273 | Year = 2003} 274 | 275 | @techreport{jsr181, 276 | Author = {Jim Trezzo}, 277 | Institution = {JCP}, 278 | Month = {August}, 279 | Note = {See http://jcp.org/en/jsr/detail?id=181}, 280 | Title = {Web {Services} {Metadata} for the {Java} {Platform}}, 281 | Type = {{JSR}}, 282 | Year = 2003} 283 | 284 | @techreport{jsr183, 285 | Author = {Nataraj Nagaratnam}, 286 | Institution = {JCP}, 287 | Month = {April}, 288 | Note = {See http://jcp.org/en/jsr/detail?id=183}, 289 | Title = {Web {Services} {Message} {Security} {APIs} }, 290 | Type = {{JSR}}, 291 | Year = 2002} 292 | 293 | @techreport{javalang, 294 | Author = {James Gosling and Bill Joy and Guy Steele and Gilad Bracha}, 295 | Institution = {Sun Microsystems, Inc}, 296 | Note = {http://java.sun.com/docs/books/jls/second\_edition/html/j.title.doc.html}, 297 | Title = {The {Java} {Language} {Specification} - Second Edition}, 298 | Type = {{Book}}, 299 | Year = 2000} 300 | 301 | @techreport{servlet, 302 | Author = {G. Murray}, 303 | Institution = {JCP}, 304 | Month = {October}, 305 | Note = {See http://java.sun.com/products/servlet}, 306 | Title = {Java {Servlet} {Specification} {Version} {2.5} }, 307 | Type = {{JSR}}, 308 | Year = 2006} 309 | 310 | @techreport{jsr244, 311 | Author = {Bill Shannon}, 312 | Institution = {JCP}, 313 | Month = {August}, 314 | Note = {See http://jcp.org/en/jsr/detail?id=244}, 315 | Title = {{Java} {Platform} {Enterprise} {Edition} 5 {Specification}}, 316 | Type = {{JSR}}, 317 | Year = 2005} 318 | 319 | @techreport{jsr224, 320 | Author = {R. Chinnici and M. Hadley and R. Mordani}, 321 | Institution = {JCP}, 322 | Month = {August}, 323 | Note = {See http://jcp.org/en/jsr/detail?id=224}, 324 | Title = {{Java} {API} {for} {XML} {Web} {Services}}, 325 | Type = {{JSR}}, 326 | Year = 2005} 327 | 328 | @techreport{jsr250, 329 | Author = {Rajiv Mordani}, 330 | Institution = {JCP}, 331 | Month = {July}, 332 | Note = {See http://jcp.org/en/jsr/detail?id=250}, 333 | Title = {{Common} {Annotations} for the {Java} {Platform}}, 334 | Type = {{JSR}}, 335 | Year = 2005} 336 | 337 | @techreport{jsr299, 338 | Author = {Gavin King}, 339 | Institution = {JCP}, 340 | Month = {December}, 341 | Note = {See http://jcp.org/en/jsr/detail?id=299}, 342 | Title = {{Context} and {Dependency} {Injection} for the {Java} {Platform}}, 343 | Type = {{JSR}}, 344 | Year = 2009} 345 | 346 | @techreport{xmlcatalogs, 347 | Author = {Norm Walsh}, 348 | Institution = {OASIS}, 349 | Month = {July}, 350 | Note = {See http://www.oasis-open.org/committees/download.php/14041/xml-catalogs.html}, 351 | Title = {{XML} {Catalogs} 1.1}, 352 | Type = {{OASIS Committee Specification}}, 353 | Year = 2005} 354 | 355 | @techreport{atompub, 356 | Author = {J.C. Gregorio and B. de hOra}, 357 | Institution = {IETF}, 358 | Month = {March}, 359 | Note = {See http://bitworking.org/projects/atom/draft-ietf-atompub-protocol-14.html}, 360 | Title = {{The} {Atom} {Publishing} {Protocol}}, 361 | Type = {{Internet Draft}}, 362 | Year = 2007} 363 | 364 | @techreport{http11, 365 | Author = {R. Fielding and J. Gettys and J. C. Mogul and H. Frystyk and T. Berners-Lee}, 366 | Institution = {IETF}, 367 | Month = {January}, 368 | Note = {See http://www.ietf.org/rfc/rfc2616.txt}, 369 | Title = {{RFC} 2616: {Hypertext} {Transfer} {Protocol} -- {HTTP/1.1}}, 370 | Type = {{RFC}}, 371 | Year = 1997} 372 | 373 | @techreport{rest, 374 | Author = {R. Fielding}, 375 | Institution = {University of California, Irvine}, 376 | Note = {See http://roy.gbiv.com/pubs/dissertation/top.htm}, 377 | Title = {{Architectural} {Styles} and the {Design} of {Network-based} {Software} {Architectures}}, 378 | Type = {Ph.D Dissertation}, 379 | Year = 2000} 380 | 381 | @techreport{webdav, 382 | Author = {L. Dusseault}, 383 | Institution = {IETF}, 384 | Month = {June}, 385 | Note = {See http://www.ietf.org/rfc/rfc4918.txt}, 386 | Title = {{RFC} 4918: {HTTP} {Extensions} for {Web} {Distributed} {Authoring} and {Versioning} ({WebDAV})}, 387 | Type = {{RFC}}, 388 | Year = 2007} 389 | 390 | @techreport{restwiki, 391 | Note = {See http://rest.blueoxen.net/cgi-bin/wiki.pl}, 392 | Title = {{REST} {Wiki}}, 393 | Type = {Web Site}} 394 | 395 | @techreport{restwikipedia, 396 | Institution = {Wikipedia}, 397 | Note = {See http://en.wikipedia.org/wiki/Representational\_State\_Transfer}, 398 | Title = {{Representational} {State} {Transfer}}, 399 | Type = {Web Site}} 400 | 401 | @techreport{jaxrs11, 402 | Author = {Marc Hadley and Paul Sandoz}, 403 | Institution = {JCP}, 404 | Month = {September}, 405 | Note = {See http://jcp.org/en/jsr/detail?id=311}, 406 | Title = {{JAXRS:} {Java} {API} for {RESTful} {Web} {Services}}, 407 | Type = {{JSR}}, 408 | Year = 2009} 409 | 410 | @techreport{javaee6, 411 | Author = {Roberto Chinnici and Bill Shannon}, 412 | Institution = {JCP}, 413 | Month = {November}, 414 | Note = {See http://jcp.org/en/jsr/detail?id=316}, 415 | Title = {{Java} {Platform}, {Enterprise} {Edition} {(JavaEE)} {Specification}, {v6}}, 416 | Type = {{JSR}}, 417 | Year = 2009} 418 | 419 | @book{burke:restfuljava, 420 | Author = {Bill Burke}, 421 | Title = {{RESTful} {Java} with {JAX-RS}}, 422 | Publisher = {O'Reilly}, 423 | Year = 2009} 424 | 425 | @techreport{bv11, 426 | Author = {Emmanuel Bernard}, 427 | Institution = {JCP}, 428 | Month = {March}, 429 | Note = {See http://jcp.org/en/jsr/detail?id=349}, 430 | Title = {{Bean} {Validation} {1.1}}, 431 | Type = {{JSR}}, 432 | Year = 2013} 433 | 434 | @techreport{jsonp, 435 | Author = {Dmitry Kornilov}, 436 | Institution = {JCP}, 437 | Month = {May}, 438 | Note = {See http://jcp.org/en/jsr/detail?id=374}, 439 | Title = {{Java} {API} {for} {JSON} {Processing} {1.1}}, 440 | Type = {{JSR}}, 441 | Year = 2017} 442 | 443 | @techreport{jsonb, 444 | Author = {Dmitry Kornilov}, 445 | Institution = {JCP}, 446 | Month = {July}, 447 | Note = {See http://jcp.org/en/jsr/detail?id=367}, 448 | Title = {{Java} {API} {for} {JSON} {Binding}}, 449 | Type = {{JSR}}, 450 | Year = 2017} 451 | 452 | @techreport{concurrencyee, 453 | Author = {Anthony Lai}, 454 | Institution = {JCP}, 455 | Month = {March}, 456 | Note = {See http://jcp.org/en/jsr/detail?id=236}, 457 | Title = {{Concurrency} {Utilities} {for} {Java} {EE}}, 458 | Type = {{JSR}}, 459 | Year = 2013} 460 | 461 | @online{rxjava, 462 | Note = {See https://github.com/ReactiveX/RxJava}, 463 | Title = {{RxJava}: a library for composing asynchronous and event-based programs using observable sequences for the Java {VM}.}} 464 | 465 | @online{rxjava2, 466 | Note = {See https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0}, 467 | Title = {{RxJava 2.0}: {What's} {different} {in} {2.0}}} 468 | 469 | @online{sse, 470 | Note = {See https://html.spec.whatwg.org/\#server-sent-events}, 471 | Title = {{Server-Sent} {Events}}} 472 | 473 | -------------------------------------------------------------------------------- /chapters/providers.tex: -------------------------------------------------------------------------------- 1 | \chapter{Providers} 2 | \label{providers} 3 | 4 | Providers in \jaxrs\ are responsible for various cross-cutting concerns such as filtering requests, converting representations into Java objects, mapping exceptions to responses, etc. A provider can be either \emph{pre-packaged} in the \jaxrs\ runtime or supplied by an application. All \emph{application-supplied} providers implement interfaces in the \jaxrs\ API and MAY be annotated with \Provider\ for automatic discovery purposes; the integration of pre-packaged providers into the \jaxrs\ runtime is implementation dependent. 5 | 6 | This chapter introduces some of the basic \jaxrs\ providers; other providers are introduced in Chapter \ref{client_api} and Chapter \ref{filters_and_interceptors}. 7 | 8 | \section{Lifecycle and Environment} 9 | \label{lifecycle_and_environment} 10 | 11 | By default a single instance of each provider class is instantiated for each \jaxrs\ application. First the constructor (see Section \ref{provider_class_constructor}) is called, then any requested dependencies are injected (see Chapter \ref{context}), then the appropriate provider methods may be called multiple times (simultaneously), and finally the object is made available for garbage collection. Section \ref{providercontext} describes how a provider obtains access to other providers via dependency injection. 12 | 13 | An implementation MAY offer other provider 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. 14 | 15 | \subsection{Automatic Discovery} 16 | \label{automatic_discovery} 17 | 18 | The annotation \Provider\ is used by a \jaxrs\ runtime to automatically discover provider classes via mechanisms such as class scanning. A \jaxrs\ implementation that supports automatic discovery of classes MUST process only those classes that are annotated with \Provider. 19 | 20 | \subsection{Constructors} 21 | \label{provider_class_constructor} 22 | 23 | Provider classes that 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. 24 | 25 | A public constructor MAY include parameters annotated with \Context ---Chapter \ref{context} defines the parameter types permitted for this annotation. Since providers may be created outside the scope of a particular request, only deployment-specific properties may be available from injected interfaces at construction time; request-specific properties are available when a provider method is called. 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, implementations SHOULD generate a warning about such ambiguity. 26 | 27 | \subsection{Priorities} 28 | \label{provider_priorities} 29 | 30 | Application-supplied providers enable developers to extend and customize the \jaxrs\ runtime. Therefore, an application-supplied provider MUST always be preferred over a pre-packaged one if a single one is required. 31 | 32 | Application-supplied providers may be annotated with \Priority. If two or more providers are candidates for a certain task, the one with the \emph{highest} priority is chosen: the highest priority is defined to be the one with the \emph{lowest} value in this case. That is, \code{@Priority(1)} is higher than \code{@Priority(10)}. If two or more providers are eligible and have identical priorities, one is chosen in an implementation dependent manner. The default priority for all application-supplied providers is \code{javax.ws.rs.Priorities.USER}. 33 | 34 | The general rule about priorities is different for filters and interceptors since these providers are collected into chains. For more information see Section \ref{priorities}. 35 | 36 | \section{Entity Providers} 37 | \label{entity_providers} 38 | 39 | Entity providers supply mapping services between representations and their associated Java types. Entity providers come in two flavors: \MsgRead\ and \MsgWrite\ described below. 40 | 41 | \subsection{Message Body Reader} 42 | \label{message_body_reader} 43 | 44 | The \MsgRead\ interface defines the contract between the \jaxrs\ runtime and components that provide mapping services from representations to a corresponding Java type. A class wishing to provide such a service implements the \MsgRead\ interface and may be annotated with \Provider\ for automatic discovery. 45 | 46 | The following describes the logical\footnote{Implementations are free to optimize their processing provided the results are equivalent to those that would be obtained if these steps are followed.} steps taken by a \jaxrs\ implementation when mapping a message entity body to a Java method parameter: 47 | 48 | \begin{enumerate} 49 | \item Obtain the media type of the request. If the request does not contain a \code{Content-Type} header then use \code{application/octet-stream}. 50 | \item Identify the Java type of the parameter whose value will be mapped from the entity body. Section \ref{mapping_requests_to_java_methods} describes how the Java method is chosen. 51 | \item Select the set of \MsgRead\ classes that support the media type of the request, see Section \ref{declaring_provider_capabilities}. 52 | \item\label{findreader} Iterate through the selected \MsgRead\ classes and, utilizing the \code{isReadable} method of each, choose a \MsgRead\ provider that supports the desired Java type. 53 | \item If step \ref{findreader} locates one or more suitable \MsgRead's\ then select the one with the highest priority as described in Section \ref{provider_priorities} and use its \code{readFrom} method to map the entity body to the desired Java type. 54 | \item Otherwise, the server runtime MUST generate a \code{NotSupportedException} (415 status) and no entity (to be processed as described in Section \ref{method_exc}) and the client runtime MUST generate an instance of \code{ProcessingException}. 55 | \end{enumerate} 56 | 57 | See Section \ref{exceptions_providers} for more information on handling exceptions thrown in \MsgRead\code{.readFrom}. 58 | 59 | \subsection{Message Body Writer} 60 | \label{message_body_writer} 61 | 62 | The \MsgWrite\ interface defines the contract between the \jaxrs\ runtime and components that provide mapping services from a Java type to a representation. A class wishing to provide such a service implements the \MsgWrite\ interface and may be annotated with \Provider\ for automatic discovery. 63 | 64 | The following describes the logical steps taken by a \jaxrs\ implementation when mapping a return value to a message entity body: 65 | 66 | \begin{enumerate} 67 | \item Obtain the object that will be mapped to the message entity body. For a return type of \Response\ or subclasses, the object is the value of the \code{entity} property, for other return types it is the returned object. 68 | \item Determine the media type of the response, see Section \ref{determine_response_type}. 69 | \item Select the set of \MsgWrite\ providers that support (see Section \ref{declaring_provider_capabilities}) the object and media type of the message entity body. 70 | \item\label{item_sort} Sort the selected \MsgWrite\ providers with a primary key of generic type where providers whose generic type is the nearest superclass of the object class are sorted first and a secondary key of media type (see Section \ref{declaring_provider_capabilities}). 71 | \item\label{findwriter} Iterate through the sorted \MsgWrite\ providers and, utilizing the \code{isWriteable} method of each, choose an \MsgWrite\ that supports the object that will be mapped to the entity body. 72 | \item If step \ref{findwriter} locates one or more suitable \MsgWrite's\ that are equal with respect to the sorting in step \ref{item_sort}, then select the one with the highest priority as described in Section \ref{provider_priorities} and use its \code{writeTo} method to map the entity body to the desired Java type. 73 | \item Otherwise, the server runtime MUST generate a generate an \code{InternalServerErrorException}, a subclass of \WebAppExc\ with its status set to 500, and no entity (to be processed as described in Section \ref{method_exc}) and the client runtime MUST generate a \code{ProcessingException}. 74 | 75 | \end{enumerate} 76 | 77 | Experience gained in the field has resulted in the reversal of the sorting keys in step 78 | \ref{item_sort} in this specification. This represents a backward incompatible change 79 | with respect to \jaxrs\ 1.X. Implementations of this specification are REQUIRED to 80 | provide a backward compatible flag for those applications that rely on the previous 81 | ordering. The mechanism defined to enable this flag is implementation dependent. 82 | 83 | See Section \ref{exceptions_providers} for more information on handling exceptions thrown in \MsgWrite\code{.write}. 84 | 85 | \subsection{Declaring Media Type Capabilities} 86 | \label{declaring_provider_capabilities} 87 | 88 | Message body readers and writers MAY restrict the media types they support using the \Consumes\ and \Produces\ annotations respectively. The absence of these annotations is equivalent to their inclusion with media type (\lq\lq*/*\rq\rq), i.e. absence implies that any media type is supported. An implementation MUST NOT use an entity provider for a media type that is not supported by that provider. 89 | 90 | When choosing an entity provider an implementation sorts the available providers according to the media types they declare support for. Sorting of media types follows the general rule: x/y $<$ x/* $<$ */*, i.e. a provider that explicitly lists a media types is sorted before a provider that lists */*. 91 | 92 | \subsection{Standard Entity Providers} 93 | \label{standard_entity_providers} 94 | 95 | An implementation MUST include pre-packaged \MsgRead\ and \MsgWrite\ implementations for the following Java and media type combinations: 96 | 97 | \begin{description} 98 | \item[\code{byte[]}] All media types (\code{*/*}). 99 | \item[\code{java.lang.String}] All media types (\code{*/*}). 100 | \item[\code{java.io.InputStream}] All media types (\code{*/*}). 101 | \item[\code{java.io.Reader}] All media types (\code{*/*}). 102 | \item[\code{java.io.File}] All media types (\code{*/*}). 103 | \item[\code{javax.activation.DataSource}] All media types (\code{*/*}). 104 | \item[\code{javax.xml.transform.Source}] XML types (\code{text/xml}, \code{application/xml} and media types of the form \code{application/*+xml}). 105 | \item[\code{javax.xml.bind.JAXBElement} and application-supplied JAXB classes] XML types (\code{text/xml} and \code{application/xml} and media 106 | types of the form \code{application/*+xml}). 107 | \item[\code{MultivaluedMap}] Form content (\code{application/x-www-form-urlencoded}). 108 | \item[\code{StreamingOutput}] All media types (\code{*/*}), \MsgWrite\ only. 109 | \item[\code{java.lang.Boolean}, \code{java.lang.Character}, \code{java.lang.Number} \label{primitive_types}] Only for \code{text/plain}. Corresponding primitive types supported via boxing/unboxing conversion. 110 | \end{description} 111 | 112 | Depending on the environment, the list of standard entity providers MUST also include those for JSON. For more information about these providers see Sections \ref{jsonp} and \ref{jsonb}. 113 | 114 | When reading zero-length message entities all pre-packaged \MsgRead\ implementations, except the JAXB one and those for the (boxed) primitive types above, MUST create a corresponding Java object that represents zero-length data. The pre-packaged JAXB and the pre-packaged primitive type \MsgRead\ implementations MUST throw a \code{NoContentException} for zero-length message entities. 115 | 116 | When a \code{NoContentException} is thrown while reading a server request entity from a \MsgRead\, it MUST be translated by the server runtime into a \code{BadRequestException} wrapping the original \code{NoContentException} and re-thrown to be processed by any registered exception mappers. 117 | 118 | The implementation-supplied entity provider(s) for \code{javax\-.xml\-.bind\-.JAXBElement} and application-supplied JAXB classes MUST use \code{JAXBContext} instances provided by application-supplied context resolvers, see Section \ref{contextprovider}. If an application does not supply a \code{JAXBContext} for a particular type, the implementation-supplied entity provider MUST use its own default context instead. 119 | 120 | When writing responses, implementations SHOULD respect application-supplied character set metadata and SHOULD use UTF-8 if a character set is not specified by the application or if the application specifies a character set that is unsupported. 121 | 122 | An implementation MUST support application-provided entity providers and MUST use those in preference to its own pre-packaged providers when either could handle the same request. More precisely, step \ref{findreader} in Section \ref{message_body_reader} and step \ref{findwriter} in Section \ref{message_body_writer} MUST prefer application-provided over pre-packaged entity providers. 123 | 124 | \subsection{Transfer Encoding} 125 | \label{transfer_encoding} 126 | 127 | Transfer encoding for inbound data is handled by a component of the container or the \jaxrs\ runtime. \MsgRead\ providers always operate on the decoded HTTP entity body rather than directly on the HTTP message body. 128 | 129 | A JAX-RS runtime or container MAY transfer encode outbound data or this MAY be done by application code. 130 | 131 | \subsection{Content Encoding} 132 | 133 | Content encoding is the responsibility of the application. Application-supplied entity providers MAY perform such encoding and manipulate the HTTP headers accordingly. 134 | 135 | \section{Context Providers} 136 | \label{contextprovider} 137 | 138 | Context providers supply context to resource classes and other providers. A context provider class implements the \code{ContextResolver} interface and may be annotated with \Provider\ for automatic discovery. E.g., an application wishing to provide a customized \code{JAXBContext} to the default JAXB entity providers would supply a class implementing \code{ContextResolver}. 139 | 140 | Context providers MAY return \code{null} from the \code{getContext} method if they do not wish to provide their context for a particular Java type. E.g. a JAXB context provider may wish to only provide the context for certain JAXB classes. Context providers MAY also manage multiple contexts of the same type keyed to different Java types. 141 | 142 | \subsection{Declaring Media Type Capabilities} 143 | \label{context_media_type} 144 | 145 | Context provider implementations MAY restrict the media types they support using the \Produces\ annotation. The absence of this annotation is equivalent to its inclusion with media type (\lq\lq*/*\rq\rq), i.e. absence implies that any media type is supported. 146 | 147 | When choosing a context provider an implementation sorts the available providers according to the media types they declare support for. Sorting of media types follows the general rule: x/y $<$ x/* $<$ */*, i.e. a provider that explicitly lists a media type is sorted before a provider that lists */*. 148 | 149 | \section{Exception Mapping Providers} 150 | \label{exceptionmapper} 151 | 152 | Exception mapping providers map a checked or runtime exception to an instance of \Response. An exception mapping provider implements the \code{ExceptionMapper} interface and may be annotated with \Provider\ for automatic discovery. 153 | 154 | When a resource class or provider method throws an exception for which there is an exception mapping provider, the matching provider is used to obtain a \Response\ instance. The resulting \Response\ is processed as if a web resource method had returned the \Response, see Section \ref{resource_method_return}. In particular, a mapped \Response\ MUST be processed using the ContainerResponse filter chain defined in Chapter~\ref{filters_and_interceptors}. 155 | 156 | When choosing an exception mapping provider to map an exception, an implementation MUST use the provider whose generic type is the nearest superclass of the exception. If two or more exception providers are applicable, the one with the highest priority MUST be chosen as described in Section \ref{provider_priorities}. 157 | 158 | To avoid a potentially infinite loop, a single exception mapper must be used during the processing of a request and its corresponding response. \jaxrs\ implementations MUST NOT attempt to map exceptions thrown while processing a response previously mapped from an exception. Instead, this exception MUST be processed as described in steps \ref{runtimeexc} and \ref{checkedexc} in Section \ref{method_exc}. 159 | 160 | Note that exception mapping providers are {\em not} supported as part of the Client API. 161 | 162 | \section{Exceptions} 163 | \label{exceptions_providers} 164 | 165 | Exception handling differs depending on whether a provider is part of the client runtime or server runtime. This is covered in the next two sections. 166 | 167 | \subsection{Server Runtime} 168 | \label{exceptions_providers_server} 169 | 170 | When a provider method throws an exception, the \jaxrs\ server runtime will attempt to map the exception to a suitable HTTP response in the same way as described for methods and locators in Section \ref{method_exc}. If the exception is thrown 171 | while generating a response, \jaxrs\ implementations are required to map the exception {\em only when} the response has not been committed yet. 172 | 173 | As explained in Section \ref{exceptionmapper}, an application can supply exception mapping providers to customize this mapping, but these exception mappers will be ignored during the processing of a {\em previously mapped} response to avoid entering a potentially infinite loop. For example, suppose a method in a message body reader throws an exception that is mapped to a response via an exception mapping provider; if the message body writer throws an exception while trying to write the mapped response, \jaxrs\ implementations will not attempt to map the exception again. 174 | 175 | \subsection{Client Runtime} 176 | \label{exceptions_providers_client} 177 | 178 | When a provider method throws an exception, the \jaxrs\ client runtime will map it to an instance of \code{ProcessingException} if thrown while processing a request, and to a \code{ResponseProcessingException} if thrown while processing a response. 179 | 180 | Note that the client runtime will only throw an instance of \WebApplicationException\ (or any of its subclasses) as a result of a response from the server with status codes 3xx, 4xx or 5xx. 181 | 182 | -------------------------------------------------------------------------------- /chapters/changes.tex: -------------------------------------------------------------------------------- 1 | \chapter{Change Log} 2 | 3 | \section{Changes Since 2.1 Public Review} 4 | 5 | \begin{itemize} 6 | \item Section \ref{sse_pipeline}: New section describing the SSE processing pipeline. 7 | \item Section \ref{sub_resources}: Allow sub-resource locators to return classes as well. 8 | \item Section \ref{executor_services}: Removed defaults for all environments not supporting the Java Concurrenty Utilities for Java EE API. 9 | \item Section \ref{jsonp}: Support for \code{JsonValue} and all its sub-types. 10 | \item Section \ref{jsonb}: New section for JSON-B support. 11 | \item Section \ref{completionstage}: New section for \code{CompletionStage} as return type in a resource method. 12 | \item Section \ref{provider_priorities}: New section introducing support for \code{@Priority} for all providers. 13 | \item Section \ref{entity_providers}: Modified algorithm steps to add support for \code{@Priority} in selection of message body readers and writers. 14 | \end{itemize} 15 | 16 | \section{Changes Since 2.1 Early Draft} 17 | 18 | \begin{itemize} 19 | \item Chapter \ref{sse}: API changes and removal of Flow API references. 20 | \item Section \ref{resource_method}: Added \code{@PATCH} to list of supported HTTP methods. 21 | \item Section \ref{executor_services}: New section about executor services. 22 | \item Section \ref{rdconfig}: Use of \code{ServiceLoader} in first step of algorithm. 23 | \end{itemize} 24 | 25 | \section{Changes Since 2.0 Final Release} 26 | 27 | \begin{itemize} 28 | \item Section \ref{resource_field}: Clarified exception handling for all 5 steps used to convert a string to a Param. Allowed the combination of \code{List<{\em T}>}, \code{Set<{\em T}>}, or \code{SortedSet<{\em T}>} and \ParamConverter. 29 | \item Section \ref{request_matching}: Defined client and server media types. 30 | \item Section \ref{reactive_clients}: New section introducing support for reactive clients. 31 | \item Chapter \ref{sse}: New chapter describing the Server-Sent Events API. 32 | \end{itemize} 33 | 34 | \section{Changes Since 2.0 Proposed Final Draft} 35 | 36 | \begin{itemize} 37 | \item Section \ref{message_body_reader} and \ref{message_body_writer}: Updated last logical step separating client and server runtimes. 38 | \item Section \ref{standard_entity_providers}: New exception \code{NoContentException} to handle zero-length entities. 39 | \item Section \ref{exceptions_providers} and \ref{exceptions_filters_and_interceptors}: New subsections to separate client and server processing of exceptions. 40 | \item Section \ref{configurable_types}: \Invocation\ and \InvocationBuilder\ are no longer configurable types. 41 | \item Section \ref{filters_interceptors_client}: Updated samples based on changes to Client API. 42 | \item Section \ref{default_validation_mode}: Updated section based on changes to Bean Validation API. 43 | \item Section \ref{validation_and_error_reporting}: Minor re-wording of Phase 2. 44 | \item Section \ref{timeouts_and_callbacks}: Improved example to return a response if a timeout expires. 45 | \item Section \ref{client_api_async}: Updated samples based on changes to Client API. 46 | \item Section \ref{contexttypes}: Clarified server vs.~client injectable types. 47 | \item Section \ref{configuration_injection}: New section about injection of \code{Configuration} instances. 48 | \item Section \ref{bv_support}: New section stating that support for resource validation is required only in a product that supports Bean Validation. 49 | \end{itemize} 50 | 51 | \section{Changes Since 2.0 Public Review Draft} 52 | 53 | \begin{itemize} 54 | \item In Javadocs: Method \code{getSize} in class \code{MessageBodyWriter} is deprecated. 55 | \item Chapter \ref{resources} and \ref{providers}: Replaced \WebAppExc\ by corresponding subclass depending on HTTP status code. 56 | \item Section \ref{resource_field}: New step for \code{ParamConverter}. 57 | \item Section \ref{standard_entity_providers}: Special case for zero-length entities and primitive types. 58 | \item Chapter \ref{client_api}: Updated samples and text related to the configuration of Client API types. Method \code{configuration} has been removed in favor of the \code{Configurable} interface. 59 | \item Chapter \ref{client_api}: \code{ClientFactory} renamed to \code{ClientBuilder}. 60 | \item Chapter \ref{client_api}: Dropped support for \code{@Uri} annotation. 61 | \item Section \ref{entity_interceptors}: New paragraph clarifying that entity interceptors are not called if a \code{readFrom} or \code{writeTo} method is called directly from application code. 62 | \item Section \ref{entity_interceptors}: Improved \code{GzipInterceptor} sample. 63 | \item Section \ref{Name_Binding}: Clarified name binding with multiple annotations. Made semantics compatible with CDI interceptor binding. Name binding with \code{Application} subclasses. 64 | \item Section \ref{priorities}: Annotation \code{@BindingPriority} replaced by common annotation \code{@Priority}. 65 | \item Section \ref{exceptions_filters_and_interceptors}: Clarified processing of a response mapped from an exception. 66 | \item Section \ref{server_api}: Updated samples in this section. New citation for JSR 236. 67 | \item Section \ref{timeouts_and_callbacks}: Improved example. 68 | \item Section \ref{client_api_async}: Fixed signature of method \code{failed} in samples. 69 | \item Section \ref{default_validation_mode}: New section about default validation and \code{@ValidateExecutable}. 70 | \item Section \ref{validation_and_error_reporting}: Restored validation phases. 71 | \item Section \ref{jsonp}: New section about integration with JSON-P. 72 | 73 | \end{itemize} 74 | 75 | \section{Changes Since 2.0 Early Draft (Third Edition)} 76 | 77 | \begin{itemize} 78 | \item Chapter ``Validation'': Removed from PR. JAX-RS 2.0 will defer to CDI for Bean Validation. Only those resource classes that are CDI beans would be validated. 79 | \item Section \ref{method_exc}: Clarified that the steps must be followed in order and that throwables are propagated to the underlying container only if they cannot be mapped. 80 | \item Section \ref{resource_method}: Added \code{@OPTIONS} to list. 81 | \item Section \ref{resource_method_return}: New note about anonymous inner classes. 82 | \item Section \ref{request_matching}: Allow multiple root resource classes to share same URI in algorithm. Note changes in output and input of steps 1 and 2, respectively. 83 | \item Section \ref{message_body_writer}: Throw new exception \code{InternalServerErrorException}. 84 | \item Section \ref{entity_providers}: Removed steps that required the use of the JavaBeans Activation Framework\cite{jaf} to map objects to representations and vice-versa. The EG deemed this feature to be confusing and not portable across implementations. 85 | \item Section \ref{standard_entity_providers}: Support for pre-packaged readers and writers for Java types \code{java.lang.Boolean}, \code{java.lang.Character}, \code{java.lang.Number} and media type \code{text/plain}. 86 | \item Section \ref{standard_entity_providers}: Detailed behavior for readers and zero-length request entities. 87 | \item Section \ref{dynamic_binding}: \code{DynamicBinder} replaced by \code{DynamicFeature}. 88 | \item Section \ref{exceptions_filters_and_interceptors}: Clarified processing of responses mapped using exception mappers. 89 | %\item Section \ref{annotations_and_validators}: Explained notion of processing groups and use of \code{Default} group. 90 | \item Chapter \ref{asynchronous_processing}: Updated sections related to the Server API. \code{@Suspended} annotation, timeouts and callbacks. 91 | \item Section \ref{timeouts_and_callbacks}: Throw new exception \code{ServiceUnavailableException}. 92 | \item Section \ref{resource_context}: New section for \code{ResourceContext}. 93 | \item Section \ref{ejbs}: Clarified location of annotations in accordance to the JAX-RS annotation inheritance rules. 94 | \item Chapter \ref{filters_and_interceptors}: Replaced \code{@PostMatching} by \code{@PreMatching}. Post-matching is now the default. 95 | \item Appendix \ref{annotation_table}: Edited section on JAX-RS 2.0 annotations. 96 | \end{itemize} 97 | 98 | \section{Changes Since 2.0 Early Draft (Second Edition)} 99 | 100 | \begin{itemize} 101 | \item Section \ref{uritemplates}: New example showing a scenario in which a \code{@PathParam} is not be available for injection. 102 | \item Section \ref{request_matching}: Formalization of certain parts of the matching algorithm that were vague. Defined formal ordering between media types and highlighted situations in which implementations should report a warning if the matching is ambiguous. 103 | \item Section \ref{request_matching}: New sample showing the resource matching algorithm in action. 104 | \item Section \ref{template_to_regex}: New footnote about syntax of regular expression. 105 | \item Chapter \ref{providers}: The annotation \Provider\ is now only required for automatic discovery of providers (typically via class scanning). It is no longer required for a provider that is manually registered in classes such as \code{Application} or \code{Configuration}. 106 | \item Section \ref{automatic_discovery}: New section about automatic discovery of provider classes. Only those annotated with \Provider\ must be discovered automatically. 107 | \item Chapter \ref{client_api}: Features are now providers and can be registered as such. A feature can no longer be disabled. 108 | \item Chapter \ref{client_api}: Class \code{Target} renamed to \WebTarget. Removed text describing how to use a builder factory class (no longer supported). A few other minor updates and typos fixed. 109 | \item Chapter \ref{filters_and_interceptors}: Extension points for filters revised. New filter interfaces \ClientRequestFilter\ and \ClientResponseFilter\ in Client API and new filter interfaces \ContainerRequestFilter\ and \ContainerResponseFilter\ in Server API. Corresponding context classes also updated in chapter. A \ContainerRequestFilter\ is executed before resource matching unless annotated with \PostMatching. It is no longer possible to share a filter implementation between the Client and Server APIs; entity interceptors are still shareable. 110 | \item Chapter \ref{filters_and_interceptors}: Section on the relationship between filters and entity interceptors (including diagram) dropped. 111 | \item Section \ref{global_binding}: Clarified global binding in relation to the new semantics of \Provider\ for automatic discovery. 112 | \item Section \ref{dynamic_binding}: The \code{DynamicBinding} interface, intended to be implemented by filters and entity interceptors, is replaced by \code{DynamicBinder}. A dynamic binder is a new type of provider that binds filters and entity interceptors with resource methods. 113 | \item Chapter ``Validation'': Use media type names instead of Java constants for clarity. More descriptive names for constraint annotations. Changed inheritance rules for constraint annotations to follow those defined in \cite{bv11}. New note about \code{@Valid} support for return values. Fixed phase number typo. 114 | \item Section \ref{timeouts_and_callbacks}: New sentence about calling \code{suspend} more than once or in a method annotated with \code{@Suspend}. 115 | \item Section \ref{async_ejbs}: New section about EJB resource classes with methods annotated with \code{@Asynchronous}. 116 | \item Chapter \ref{environment}: Re-structured chapter with sub-sections for each of the EE technologies with which \jaxrs\ integrates. New examples added. 117 | \end{itemize} 118 | 119 | \section{Changes Since 2.0 Early Draft} 120 | 121 | \begin{itemize} 122 | \item Section \ref{expert_group}: Updated 2.0 expert group member list. 123 | \item Section \ref{acks}: Updated acknowledgements for 2.0 version. 124 | \item Section \ref{exceptions_providers}: New section that describes exception handling for all providers. Related changes to reference this new section. 125 | \item Section \ref{exceptions_filters_and_interceptors}: New section for filter and interceptor exceptions. Related changes to reference this new section. 126 | \item Section \ref{request_matching}: Updated step 2a so that it only goes to step 3 when $M \neq \{\}$. 127 | \item Section \ref{request_matching}: New sentence about the use of a server quality parameter (qs-value) during request matching. 128 | \item Chapter \ref{filters_and_interceptors}: New extension point for pre-match filters that are executed before resource matching. 129 | \item Chapter \ref{filters_and_interceptors}: Filter methods no longer return a next action; the execution of a request filter chain is stopped by setting a response in the associated context. 130 | \item Chapter \ref{filters_and_interceptors}: Handlers renamed to entity interceptors for clarity (in this log included). 131 | \item Section \ref{global_binding}: Global binding is now the default for filters and entity interceptors. The annotation \code{@GlobalBinding} has been dropped. 132 | \item Section \ref{priorities}: Clarified reverse ordering of the response filter chain based on binding priorities. 133 | \item Appendix C: Removed from this version after changes to Chapter \ref{filters_and_interceptors}. 134 | \item Chapter ``Validation'': Moved to an instantiate-then-validate strategy in which validation of constructor parameters and setters is no longer supported. Simplified validation process to better align with Bean Validation 1.1 \cite{bv11}. In particular, validation of resource classes, fields and property getters are all carried out in a single step. 135 | 136 | \end{itemize} 137 | 138 | \section{Changes Since 1.1 Release} 139 | 140 | \begin{itemize} 141 | \item Section \ref{status}: Updated URLs to JSR pages, etc. 142 | \item Section \ref{non_goals}: Removed Client APIs as non-goal. 143 | \item Section \ref{terminology}: Added new terminology. 144 | \item Section \ref{expert_group}: List 2.0 expert group members. 145 | \item Section \ref{acks}: acknowledgements for 2.0 version. 146 | \item Chapter \ref{applications}: Somewhat generic section on validation removed to avoid confusion with the type of validation defined in Chapter ``Validation''. 147 | \item Section \ref{servlet}: Clarified used of Servlet 3 framework pluggability. Added sample web.xml files and a table summarizing all cases. 148 | \item Section \ref{entity_parameters}: Clarified notion of entity parameter as a parameter not annotated with any JAX-RS annotation. 149 | \item Section \ref{declaring_method_capabilities}: Explained use of quality factor q. Introduced server-side quality factor qs and included example. 150 | \item Section \ref{annotationinheritance}: Added sentence about conflicting annotations and recommendation to repeat annotations for consistency with other Java EE specifications. 151 | \item Section \ref{reqpreproc}: Highlighted input and output for each step in algorithm. Minor edits to simplify presentation. 152 | \item Section \ref{determine_response_type}: Updated algorithm to support server-side quality factor qs. 153 | \item Chapter \ref{client_api}: New chapter Client API. 154 | \item Chapter \ref{filters_and_interceptors}: New chapter Filters and Interceptors. 155 | \item Chapter ``Validation'': New chapter Validation. 156 | \item Chapter \ref{asynchronous_processing}: New chapter Asynchronous Processing. 157 | \item Appendix \ref{annotation_table}: New section for 2.0 annotations. 158 | \item Appendix C: New appendix describing filter and interceptor extension points. 159 | \end{itemize} 160 | 161 | \section{Changes Since 1.0 Release} 162 | 163 | \begin{itemize} 164 | \item Section \ref{servlet}: New requirements for Servlet 3 containers. 165 | \item Section \ref{javaee}: Requirements for Java EE 6 containers. 166 | \item Section \ref{standard_entity_providers}: Requirements on standard entity providers when presented with an empty message entity. 167 | \item Section \ref{message_body_writer}: Add closeness of generic type as secondary sort key. 168 | \item Section \ref{message_body_reader}: Default to application/octet-stream if a request does not contain a content-type header. 169 | \item Section \ref{resource_field}: Add support for static fromString method. 170 | \item Section \ref{annotationinheritance}: Clarify annotation inheritance. 171 | \item Section \ref{security_context}: Fix typo. 172 | \item Section \ref{servlet_container}: Additional considerations related to filters consuming request bodies. 173 | \end{itemize} 174 | 175 | \section{Changes Since Proposed Final Draft} 176 | 177 | \begin{itemize} 178 | \item Section \ref{request_matching}: Additional sort criteria so that templates with explicit regexs are sorted ahead of those with the default. 179 | \item Sections \ref{request_matching}, \ref{determine_response_type}, \ref{declaring_provider_capabilities} and \ref{context_media_type}: Q-values not used in \Consumes\ or \Produces. 180 | \item Section \ref{message_body_writer}: Fixed algorithm to refer to Section \ref{determine_response_type} instead of restating it. Fixed status code returned when the media type has been determined but an appropriate message body writer cannot be located. 181 | \item Chapter \ref{runtimedelegate}: Clarify that an implementation can supply an alternate \rd\ API class. 182 | \end{itemize} 183 | 184 | \section{Changes Since Public Review Draft} 185 | 186 | \begin{itemize} 187 | \item Chapter \ref{applications}: Renamed ApplicationConfig class to Application. 188 | \item Chapter \ref{resources}: UriBuilder reworked to always encode components. 189 | \item Sections \ref{resource_class_constructor} and \ref{provider_class_constructor}: Added requirement to warn when choice of constructor is ambiguous. 190 | \item Section \ref{resource_field}: \code{FormParam} no longer required to be supported on fields or properties. 191 | \item Section \ref{resource_method_return}: Added text describing how to determine raw and generic types from method return type and returned instance. 192 | \item Section \ref{uritemplates}: Template parameters can specify the regular expression that forms their capturing group. 193 | \item Section \ref{reqpreproc}: Make pre-processed URIs available rather than original request URI. Added URI normalization. 194 | \item Section \ref{reqpreproc}: Removed URI-based content negotiation. 195 | \item Section \ref{request_matching}: Reorganized the request matching algorithm to remove redundancy and improve readability, no functional change. 196 | \item Section \ref{template_to_regex}: Changes to regular expressions to eliminate edge cases. 197 | \item Section \ref{entity_providers}: Added requirement to use JavaBean Activation Framework when no entity provider can be found. 198 | \item Section \ref{standard_entity_providers}: Require standard JAXB entity providers to use application-supplied JAXB contexts in preference to their own. 199 | \item Section \ref{contextprovider}: Added support for specifying media type capabilities of context providers. 200 | \item Section \ref{contexttypes}: Removed \code{ContextResolver} from list of injectable resources. 201 | \item Section \ref{providercontext}: Changed name to Providers, removed entity provider-specific text to reflect more generic capabilities. 202 | \item Chapter \ref{headersupport}: New appendix describing where particular HTTP headers are supported. 203 | \end{itemize} 204 | -------------------------------------------------------------------------------- /chapters/filters.tex: -------------------------------------------------------------------------------- 1 | \chapter{Filters and Interceptors} 2 | \label{filters_and_interceptors} 3 | 4 | Filters and entity interceptors can be registered for execution at well-defined extension points in \jaxrs\ implementations. They are used to extend an implementation in order to provide capabilities such as logging, confidentiality, authentication, entity compression, etc. 5 | 6 | \section{Introduction} 7 | \label{introduction_filters} 8 | Entity interceptors wrap around a method invocation at a specific extension point. 9 | Filters execute code at an extension point but without wrapping a method invocation. There are four extension points for filters: \ClientRequest, \ClientResponse, \ContainerRequest\ and \ContainerResponse. There are two extension points for entity interceptors: \ReadFrom\ and \WriteTo. For each of these extension points, there is a corresponding interface: 10 | 11 | \begin{listing}{1} 12 | public interface ClientRequestFilter { 13 | void filter(ClientRequestContext requestContext) throws IOException; 14 | } 15 | public interface ClientResponseFilter { 16 | void filter(ClientRequestContext requestContext, 17 | ClientResponseContext responseContext) throws IOException; 18 | } 19 | public interface ContainerRequestFilter { 20 | void filter(ContainerRequestContext requestContext) throws IOException; 21 | } 22 | public interface ContainerResponseFilter { 23 | void filter(ContainerRequestContext requestContext, 24 | ContainerResponseContext responseContext) throws IOException; 25 | } 26 | \end{listing} 27 | 28 | \begin{listing}{1} 29 | public interface ReaderInterceptor { 30 | Object aroundReadFrom(ReaderInterceptorContext context) 31 | throws java.io.IOException, javax.ws.rs.WebApplicationException; 32 | } 33 | public interface WriterInterceptor { 34 | void aroundWriteTo(WriterInterceptorContext context) 35 | throws java.io.IOException, javax.ws.rs.WebApplicationException; 36 | } 37 | \end{listing} 38 | 39 | A {\em client} filter is a class that implements \ClientRequestFilter\ or \ClientResponseFilter\, or both. A {\em container} filter is a class that implements \ContainerRequestFilter\ or \ContainerResponseFilter, or both. An entity interceptor is a class that implements \ReaderInterceptor\ or \WriterInterceptor, or both. Filters and entity interceptors are providers and, as such, may be annotated with \Provider\ for automatic discovery. 40 | 41 | In the Client API, a \ClientRequestFilter\ is executed as part of the invocation pipeline, before the HTTP request is delivered to the network; a \ClientResponseFilter\ is executed upon receiving a server response, before control is returned to the application. 42 | In the Server API, a \ContainerRequestFilter\ is executed upon receiving a request from a client; a \ContainerResponseFilter\ is executed as part of the response pipeline, before the HTTP response is delivered to the network. 43 | 44 | A globally-bound (see Section \ref{global_binding}) \ContainerRequestFilter\ is a container filter executed after resource matching {\em unless} it is annotated with \PreMatching. The use of this annotation on this type of filters defines a new extension point for applications to use, namely \PreMatchContainerRequest. Certain \ContainerRequestContext\ methods may not be available at this extension point. 45 | 46 | An entity interceptor implementing \ReaderInterceptor\ wraps around calls to \code{MessageBodyReader}'s method \code{readFrom}. An entity interceptor implementing \WriterInterceptor\ wraps around calls to \code{MessageBodyWriter}'s method \code{writeTo}. \jaxrs\ implementations are REQUIRED to call registered interceptors when mapping representations to Java types and vice versa. See Section \ref{entity_providers} for more information on entity providers. 47 | 48 | Please refer to Appendix \ref{processing_pipeline} for some diagrams on the client and server processing pipelines that show the interaction between filters and entity interceptors. 49 | 50 | \section{Filters} 51 | \label{filters} 52 | 53 | Filters are grouped into \emph{filter chains}. There is a separate filter chain for each extension point introduced in the previous section, namely: \ClientRequest, \ClientResponse, \ContainerRequest, \ContainerResponse\ and \PreMatchContainerRequest. Filters in a chain are sorted based on their priorities (see Section \ref{priorities}) and are executed in order. 54 | 55 | The following example shows an implementation of a container logging filter: each method simply logs the message and returns. 56 | 57 | \begin{listing}{1} 58 | @Provider 59 | class LoggingFilter implements ContainerRequestFilter, 60 | ContainerResponseFilter { 61 | 62 | @Override 63 | public void filter(ContainerRequestContext requestContext) 64 | throws IOException { 65 | log(requestContext); 66 | } 67 | 68 | @Override 69 | public void filter(ContainerRequestContext requestContext, 70 | ContainerResponseContext responseContext) throws IOException { 71 | log(responseContext); 72 | } 73 | ... 74 | } 75 | \end{listing} 76 | 77 | \ContainerRequestContext\ is a mutable class that provides request-specific information for the filter, such as the request URI, message headers, message entity or request-scoped properties. The exposed setters allow (certain) modification of the request before it is processed by the resource method. Similarly, there is 78 | a corresponding \ContainerResponseContext\ that provides response-specific information. 79 | 80 | Request filters implementing \ClientRequestFilter\ or \ContainerRequestFilter\ can stop the execution of their corresponding chains by calling \code{abortWith(Response)} in their corresponding context object. If this method is invoked, \jaxrs\ implementations are REQUIRED to abort execution of the chain and treat the response object as if produced by calling the resource method (Server API) or executing the HTTP invocation (Client API). For example, upon a cache hit, a client {\em caching} filter may call \code{abortWith(Response)} to abort execution and optimize network access. 81 | 82 | As stated above, a \ContainerRequestFilter\ that is annotated with \PreMatching\ is executed upon receiving a client request but {\em before} a resource method is matched. Thus, this type of filter has the ability to modify the input to the matching algorithm (see Section~\ref{request_matching}) and, consequently, alter its outcome. 83 | The following example uses a \ContainerRequestFilter\ annotated with \PreMatching\ to tunnel requests via POST by using the X-HTTP-Method-Override header to overwrite the HTTP method prior to resource matching. 84 | 85 | \begin{listing}{1} 86 | @Provider 87 | @PreMatching 88 | public class HttpMethodOverrideFilter implements ContainerRequestFilter { 89 | 90 | @Override 91 | public void filter(ContainerRequestContext requestContext) 92 | throws IOException { 93 | if (requestContext.getMethod().equalsIgnoreCase("POST")) { 94 | String override = requestContext.getHeaders() 95 | .getFirst("X-HTTP-Method-Override"); 96 | if (override != null) { 97 | requestContext.setMethod(override); 98 | } 99 | } 100 | } 101 | } 102 | \end{listing} 103 | 104 | \section{Entity Interceptors} 105 | \label{entity_interceptors} 106 | 107 | An entity interceptor implements interface \ReaderInterceptor\ or \WriterInterceptor, or both. There is an \emph{interceptor chain} for each kind of entity interceptor. Entity interceptors in a chain are sorted based on their priorities (see Section \ref{priorities}) and are executed in order. 108 | 109 | As part of the JAX-RS processing pipeline (see Appendix \ref{processing_pipeline}), entity interceptors wrap calls to the methods \code{readFrom} in classes implementing \code{MessageBodyReader} and \code{writeTo} in classes implementing \code{MessageBodyWriter}. An interceptor SHOULD explicitly call the context method \code{proceed} to continue the execution of the chain. Because of their wrapping nature, failure to call this method will prevent execution of the wrapped method in the corresponding message body reader or message body writer. 110 | 111 | The following example shows an implementation of a GZIP entity interceptor that provides deflate and inflate capabilities~\footnote{This class is not intended to be a complete implementation of this interceptor.}. 112 | 113 | \begin{listing}{1} 114 | @Provider 115 | class GzipInterceptor implements ReaderInterceptor, WriterInterceptor { 116 | 117 | @Override 118 | Object aroundReadFrom(ReaderInterceptorContext ctx) ... { 119 | if (isGzipped(ctx)) { 120 | InputStream old = ctx.getInputStream(); 121 | ctx.setInputStream(new GZIPInputStream(old)); 122 | try { 123 | return ctx.proceed(); 124 | } finally { 125 | ctx.setInputStream(old); 126 | } 127 | } else { 128 | return ctx.proceed(); 129 | } 130 | } 131 | 132 | @Override 133 | void aroundWriteTo(WriterInterceptorContext ctx) ... { 134 | OutputStream old = ctx.getOutputStream(); 135 | GZIPOutputStream gzipOutputStream = new GZIPOutputStream(old); 136 | ctx.setOutputStream(gzipOutputStream); 137 | updateHeaders(ctx); 138 | try { 139 | ctx.proceed(); 140 | } finally { 141 | gzipOutputStream.finish(); 142 | ctx.setOutputStream(old); 143 | } 144 | } 145 | ... 146 | } 147 | \end{listing} 148 | 149 | The context types, \ReaderInterceptorContext\ and \WriterInterceptorContext, provide read and write access to the parameters of the corresponding wrapped methods. In the example shown above, the input and output streams are wrapped and updated in the context object before proceeding. \jaxrs\ implementations MUST use the last parameter values set in the context object when calling the wrapped methods \code{MessageBodyReader.readFrom} and \code{MessageBodyWriter.writeTo}. 150 | 151 | It is worth noting that a \code{readFrom} or a \code{writeTo} that is called directly from application code, e.g.~via the injection of a \code{Providers} instance, will \emph{not} trigger the execution of any entity interceptors since it is not part of the normal JAX-RS processing pipeline. 152 | 153 | \section{Lifecycle} 154 | 155 | By default, just like all the other providers, a single instance of each filter or entity interceptor is instantiated for each \jaxrs\ application. First the constructor is called, then any requested dependencies are injected, then the appropriate methods are called (simultaneously) as needed. Implementations MAY offer alternative lifecycle options beyond the default one. See Section \ref{lifecycle_and_environment} for additional information. 156 | 157 | \section{Binding} 158 | 159 | Binding is the process by which a filter or interceptor is associated with a resource class or method (Server API) or an invocation (Client API). The forms of binding presented in the next sections are only supported as part of the Server API. See Section \ref{binding_in_client_api} for binding in the Client API. 160 | 161 | \subsection{Global Binding} 162 | \label{global_binding} 163 | 164 | Global binding is the default type of binding. A filter or interceptor that has no annotations is assumed to be bound globally, i.e.~it applies to all the resource methods in an application. Like any other provider, a filter or interceptor can be registered manually (e.g., via \code{Application} or \code{Configuration}) or be discovered automatically. Note that for a filter or interceptor to be automatically discovered it MUST be annotated with \Provider\ (see Section \ref{automatic_discovery}). 165 | 166 | For example, the \code{LoggingFilter} defined in Section \ref{filters} is both automatically discovered (it is annotated with \Provider) and bound globally. If this filter is part of an application, requests and responses will be logged for all resource methods. 167 | 168 | As stated in Section \ref{introduction_filters}, a global \ContainerRequestFilter\ is executed after resource matching unless annotated with \PreMatching. A global filter that injects \code{ResourceInfo}, and generally depends on resource information for its execution, must not be annotated with \PreMatching. 169 | 170 | \subsection{Name Binding} 171 | \label{Name_Binding} 172 | 173 | A filter or interceptor can be associated with a resource class or method by declaring a new \emph{binding} annotation \`{a} la CDI~\cite{jsr299}. These annotations are declared using the \jaxrs\ meta-annotation \NameBinding\ and are used to decorate both the filter (or interceptor) and the resource method or resource class. For example, the \code{LoggingFilter} defined in Section \ref{filters} can be bound to the method \code{hello} in \code{MyResourceClass}, instead of globally, as follows: 174 | 175 | \begin{listing}{1} 176 | @Provider 177 | @Logged 178 | class LoggingFilter implements ContainerRequestFilter, 179 | ContainerResponseFilter { 180 | ... 181 | } 182 | \end{listing} 183 | 184 | \begin{listing}{1} 185 | @Path("/") 186 | public class MyResourceClass { 187 | @Logged 188 | @GET 189 | @Produces("text/plain") 190 | @Path("{name}") 191 | public String hello(@PathParam("name") String name) { 192 | return "Hello " + name; 193 | } 194 | } 195 | \end{listing} 196 | 197 | According to the semantics of \code{LoggingFilter}, the request will be logged before the \code{hello} method is called and the response will be logged after it returns. The declaration of the \code{@Logged} annotation is shown next. 198 | 199 | \begin{listing}{1} 200 | @NameBinding 201 | @Target({ ElementType.TYPE, ElementType.METHOD }) 202 | @Retention(value = RetentionPolicy.RUNTIME) 203 | public @interface Logged { } 204 | \end{listing} 205 | 206 | Multiple filters and interceptors can be bound to a single resource method using additional annotations. For example, given the following filter: 207 | 208 | \begin{listing}{1} 209 | @Provider 210 | @Authenticated 211 | class AuthenticationFilter implements ContainerRequestFilter { 212 | ... 213 | } 214 | \end{listing} 215 | 216 | method \code{hello} above could be decorated with \code{@Logged} and \code{@Authenticated} in order to provide both logging and authentication capabilities to the resource. 217 | 218 | A filter or interceptor class can be decorated with multiple binding annotations. In this case, in accordance with the semantics described in CDI~\cite{jsr299}, all those annotations must be present in the resource class or method for the binding to be established. For example, if \code{LoggingFilter} is defined as follows: 219 | 220 | \begin{listing}{1} 221 | @Provider 222 | @Logged @Verbose 223 | class LoggingFilter implements ContainerRequestFilter, 224 | ContainerResponseFilter { 225 | ... 226 | } 227 | \end{listing} 228 | 229 | then method \code{hello} above must be annotated with both \code{@Logged} and \code{@Verbose} for the binding to be in effect. 230 | 231 | Binding annotations can also be applied to resource classes and \code{Application} subclasses. Binding annotations that decorate resource classes apply to \emph{all} resource methods defined in them. 232 | Binding annotations that decorate \code{Application} subclasses can also be used to bind filters and interceptors globally, even if other annotations are present. For example, \code{LoggingFilter} as defined at the beginning of this section can be bound globally as follows: 233 | 234 | \begin{listing}{1} 235 | @Logged 236 | public class MyApplication extends Application { 237 | ... 238 | } 239 | \end{listing} 240 | 241 | Note that returning filters or interceptors from the methods \code{getClasses} or \code{getSingletons} in an application subclass will bind them globally only if they are \emph{not} decorated with a name binding annotation. If they are decorated with at least one name binding annotation, the application subclass must be annotated as shown above in order for those filters or interceptors to be bound globally. See Chapter \ref{applications} for more information on \jaxrs\ applications. 242 | 243 | \subsection{Dynamic Binding} 244 | \label{dynamic_binding} 245 | 246 | The annotation-based forms of binding presented thus far are {\em static}. Dynamic binding is also supported using dynamic features. A dynamic feature is a provider that implements the \DynamicFeature\ interface. These providers are used to augment the set of filters and entity interceptors bound to a resource method. 247 | 248 | The following example defines a dynamic feature that binds the filter \code{LoggingFilter} ---assumed not globally bound for the purpose of this example--- with all the resource methods in \code{MyResource} that are annotated with \code{@GET}. 249 | 250 | \begin{listing}{1} 251 | @Provider 252 | public final class DynamicLoggingFilterFeature implements DynamicFeature { 253 | 254 | @Override 255 | public void configure(ResourceInfo resourceInfo, 256 | FeatureContext context) { 257 | if (MyResource.class.isAssignableFrom(resourceInfo.getResourceClass()) 258 | && resourceInfo.getResourceMethod().isAnnotationPresent(GET.class)) { 259 | context.register(new LoggingFilter()); 260 | } 261 | } 262 | } 263 | \end{listing} 264 | 265 | The overridden method in this provider updates the \code{Configuration} object assigned to each resource method; the information about the resource method is provided in the form of a \code{ResourceInfo} instance. 266 | \jaxrs\ implementations SHOULD resolve dynamic features for filters and interceptors once for each resource method. It is RECOMMENDED to process dynamic features at application deployment time. 267 | 268 | \subsection{Binding in Client API} 269 | \label{binding_in_client_api} 270 | 271 | Binding in the Client API is accomplished via API calls instead of annotations. \Client, \Invocation, \InvocationBuilder\ and \WebTarget\ are all configurable types: their configuration can be accessed using the methods inherited from the \code{Configurable} interface. See Section \ref{configurable_types} for more information. 272 | 273 | \section{Priorities} 274 | \label{priorities} 275 | 276 | The order in which filters and interceptors are executed as part of their corresponding chains is controlled by the \Priority\ annotation defined in \cite{jsr250}. 277 | Priorities are represented by integer numbers. Execution chains for extension points \ContainerRequest, \PreMatchContainerRequest, \ClientRequest, \ReadFrom\ and \WriteTo\ are sorted in \emph{ascending order}; the lower the number the higher the priority. Execution chains for extension points \ContainerResponse\ and \ClientResponse\ are sorted in \emph{descending order}; the higher the number the higher the priority. These rules ensure that response filters are executed in reversed order of request filters. 278 | 279 | The \code{Priorities} class in JAX-RS defines a set of built-in priorities for security, header decorators, decoders and encoders. The default binding priority is \code{javax.ws.rs.Priorities.USER}. For example, the priority of an authentication filter can be set as follows: 280 | 281 | \begin{listing}{1} 282 | @Provider 283 | @Authenticated 284 | @Priority(Priorities.AUTHENTICATION) 285 | public class AuthenticationFilter implements ContainerRequestFilter { 286 | ... 287 | } 288 | \end{listing} 289 | 290 | Note that even though, as explained in Section \ref{binding_in_client_api}, annotations are not used for binding in the Client API, they are still used to define priorities. Therefore, if a priority other than the default is required, the \Priority\ annotation must be used for a filter or interceptor registered with the Client API. 291 | 292 | The order in which filters and interceptors that belong to the same priority class are executed is implementation dependent. 293 | 294 | \section{Exceptions} 295 | \label{exceptions_filters_and_interceptors} 296 | 297 | \subsection{Server Runtime} 298 | 299 | When a filter or interceptor method throws an exception, the server runtime will process the exception as described in Section \ref{exceptions_providers_server}. As explained in Section \ref{exceptionmapper}, an application can supply exception mapping providers. At most one exception mapper MUST be used in a single request processing cycle to avoid potentially infinite loops. 300 | 301 | A response mapped from an exception MUST be processed using the \ContainerResponse\ filter chain and the \WriteTo\ interceptor chain (if an entity is present in the mapped response). The number of entries in these chains depends on whether a resource method has been matched or not at the time the exception is thrown. There are two cases: 302 | 303 | \begin{enumerate} 304 | \item If a web resource has been matched before the exception was thrown, then the filters in \ContainerResponse\ and the interceptors in \WriteTo\ will include everything that has been bound to the method as well as globally; 305 | \item\label{no_matching} Otherwise, only global filters and interceptors will be included. 306 | \end{enumerate} 307 | 308 | Note that a filter or interceptor invoked in case \ref{no_matching} will not have access to resource-dependent information, such as that returned by an injectable instance of \code{ResourceInfo}. 309 | 310 | \subsection{Client Runtime} 311 | 312 | When a filter or interceptor method throws an exception, the client runtime will process the exception as described in Section \ref{exceptions_providers_client}. 313 | --------------------------------------------------------------------------------