Class RestContext
- All Implemented Interfaces:
AnnotationProvider
An extension of the ServletConfig
object used during servlet initialization.
Methods are provided for overriding or augmenting the information provided by the
To interact with this object, simply pass it in as a constructor argument or in an INIT hook.
Notes:
- This class is thread safe and reusable.
See Also:
-
Nested Class Summary
-
Field Summary
Fields inherited from class org.apache.juneau.Context
CONTEXT_APPLY_FILTER
Fields inherited from interface org.apache.juneau.AnnotationProvider
DEFAULT, DISABLE_ANNOTATION_CACHING
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionprotected Throwable
Method that can be subclassed to allow uncaught throwables to be treated as other types of throwables.static RestContext.Builder
create
(Class<?> resourceClass, RestContext parentContext, jakarta.servlet.ServletConfig servletConfig) Creates a new builder for this object.Create a session builder based on the properties defined on this context.void
destroy()
Called during servlet destruction to invoke allRestDestroy
methods.protected void
endCall
(RestSession session) Called at the end of a request to invoke allRestEndCall
methods.void
execute
(Object resource, jakarta.servlet.http.HttpServletRequest r1, jakarta.servlet.http.HttpServletResponse r2) The main service method.protected RestOpArg[]
findRestOperationArgs
(Method m, BeanStore beanStore) Finds theRestOpArg
instances to handle resolving objects on the calls to the specified Java method.Allowed header URL parameters.Allowed method headers.Allowed method URL parameters.Returns the annotations applied to this context.Returns the bean context associated with this context.Returns the bean store associated with this context.jakarta.servlet.ServletConfig
Returns the builder that created this context.Returns the call logger to use for this resource.Returns the name of the client version header name used by this resource.Returns the config file associated with this servlet.Returns the explicit list of supported content types for this resource.Returns the debug enablement bean for this context.Returns the default request attributes for this resource.Returns the default request headers for this resource.Returns the default response headers for this resource.Returns the encoders associated with this context.Returns the path for this resource as defined by the@Rest(path)
annotation orRestContext.Builder.path(String)
method concatenated with those on all parent classes.static final Map<Class<?>,
RestContext> Returns a registry of all createdRestContext
objects.Returns the JSON-Schema generator associated with this resource.Returns the HTTP call for the current request.Returns the logger associated with this context.Returns the resource bundle used by this resource.protected MethodExecStats
Returns the time statistics gatherer for the specified method.Returns the timing statistics on all method executions on this class.Returns the parsers associated with this context.Returns the HTTP-part parser associated with this resource.Returns the HTTP-part serializer associated with this resource.getPath()
Returns the path for this resource as defined by the@Rest(path)
annotation orRestContext.Builder.path(String)
method.Returns the path matcher for this context.protected MethodList
Returns the list of methods to invoke after the actual REST method is called.protected MethodList
Returns the list of methods to invoke before the actual REST method is called.Returns the explicit list of supported accept types for this resource.Returns the resource object.Class<?>
Returns the resource class type.Returns the child resources associated with this servlet.Returns the REST Java methods defined in this resource.Returns the root bean store for this context.Returns the serializers associated with this context.Returns the servlet init parameter returned byServletConfig.getInitParameter(String)
.Returns the static files associated with this context.getStats()
Gives access to the internal statistics on this context.getSwagger
(Locale locale) Returns the swagger for the REST resource.Returns the Swagger provider used by this resource.Returns the stack trace database associated with this context.Returns the authority path of the resource.Returns the context path of the resource.Returns the setting on how relative URIs should be interpreted as relative to.Returns the setting on how relative URIs should be resolved.Returns the variable resolver for this servlet.protected void
handleError
(RestSession session, Throwable e) Method for handling response errors.protected void
handleNotFound
(RestSession session) Handle the case where a matching method was not found.boolean
Returns whether it's safe to pass the HTTP content as a"content" GET parameter.boolean
Returns whether it's safe to render stack traces in HTTP responses.protected void
postCall
(RestOpSession session) Called during a request to invoke allRestPostCall
methods.postInit()
Called during servlet initialization to invoke allRestPostInit
child-last methods.Called during servlet initialization to invoke allRestPostInit
child-first methods.protected void
preCall
(RestOpSession session) Called during a request to invoke allRestPreCall
methods.protected void
processResponse
(RestOpSession opSession) The main method for serializing POJOs passed in through theRestResponse.setContent(Object)
method or returned by the Java method.protected JsonMap
Returns the properties on this bean as a map for debugging.protected void
startCall
(RestSession session) Called at the start of a request to invoke allRestStartCall
methods.Methods inherited from class org.apache.juneau.Context
copy, createBuilder, firstAnnotation, firstAnnotation, firstAnnotation, firstAnnotation, firstDeclaredAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachAnnotation, forEachDeclaredAnnotation, getSession, hasAnnotation, hasAnnotation, hasAnnotation, hasAnnotation, init, isDebug, lastAnnotation, lastAnnotation, lastAnnotation, lastAnnotation, lastDeclaredAnnotation, toString
-
Constructor Details
-
RestContext
Constructor.- Parameters:
builder
- The builder containing the settings for this bean.- Throws:
Exception
- If any initialization problems were encountered.
-
-
Method Details
-
getGlobalRegistry
Returns a registry of all createdRestContext
objects.- Returns:
- An unmodifiable map of resource classes to
RestContext
objects.
-
create
public static RestContext.Builder create(Class<?> resourceClass, RestContext parentContext, jakarta.servlet.ServletConfig servletConfig) throws jakarta.servlet.ServletException Creates a new builder for this object.- Parameters:
resourceClass
- The class annotated with@Rest .
Must not benull .parentContext
- The parent context if the REST bean was registered viaRest.children()
.
Can benull if the bean is a top-level resource.servletConfig
- The servlet config passed into the servlet by the servlet container.
Can benull if not available.
Ifnull , then some features (such as access to servlet init params) will not be available.- Returns:
- A new builder object.
- Throws:
jakarta.servlet.ServletException
- Something bad happened.
-
createSession
Description copied from class:Context
Create a session builder based on the properties defined on this context.Use this method for creating sessions where you want to override basic settings. Otherwise, use
Context.getSession()
directly.- Overrides:
createSession
in classContext
- Returns:
- A new session builder.
-
getBeanStore
Returns the bean store associated with this context.The bean store is used for instantiating child resource classes.
- Returns:
- The resource resolver associated with this context.
-
getBeanContext
Returns the bean context associated with this context.- Returns:
- The bean store associated with this context.
-
getEncoders
Returns the encoders associated with this context.- Returns:
- The encoders associated with this context.
-
getSerializers
Returns the serializers associated with this context.- Returns:
- The serializers associated with this context.
-
getParsers
Returns the parsers associated with this context.- Returns:
- The parsers associated with this context.
-
getMethodExecStats
Returns the time statistics gatherer for the specified method.- Parameters:
m
- The method to get statistics for.- Returns:
- The cached time-stats object.
-
getVarResolver
Returns the variable resolver for this servlet.Variable resolvers are used to replace variables in property values. They can be nested arbitrarily deep. They can also return values that themselves contain other variables.
Example:
@Rest ( messages="nls/Messages" , properties={@Property (name="title" ,value="$L{title}" ),// Localized variable in Messages.properties @Property (name="javaVendor" ,value="$S{java.vendor,Oracle}" ),// System property with default value @Property (name="foo" ,value="bar" ),@Property (name="bar" ,value="baz" ),@Property (name="v1" ,value="$R{foo}" ),// Request variable. value="bar" @Property (name="v1" ,value="$R{foo,bar}" ),// Request variable. value="bar" } )public class MyRestResourceextends BasicRestServlet {A typical usage pattern involves using variables inside the
@HtmlDocConfig
annotation:@RestGet ("/{name}/*" )@HtmlDocConfig ( navlinks={"up: $R{requestParentURI}" ,"api: servlet:/api" ,"stats: servlet:/stats" ,"editLevel: servlet:/editLevel?logger=$A{attribute.name, OFF}" } header={"<h1>$L{MyLocalizedPageTitle}</h1>" }, aside={"$F{resources/AsideText.html}" } )public LoggerEntry getLogger(RestRequestreq ,@Path Stringname )throws Exception {See Also:
- Returns:
- The var resolver in use by this resource.
-
getConfig
Returns the config file associated with this servlet.The config file is identified via one of the following:
- Returns:
- The resolving config file associated with this servlet.
Nevernull .
-
getPath
Returns the path for this resource as defined by the@Rest(path)
annotation orRestContext.Builder.path(String)
method.If path is not specified, returns
"" .See Also:
- Returns:
- The servlet path.
-
getFullPath
Returns the path for this resource as defined by the@Rest(path)
annotation orRestContext.Builder.path(String)
method concatenated with those on all parent classes.If path is not specified, returns
"" .See Also:
- Returns:
- The full path.
-
getCallLogger
Returns the call logger to use for this resource.See Also:
- Returns:
- The call logger to use for this resource.
Nevernull .
-
getMessages
Returns the resource bundle used by this resource.- Returns:
- The resource bundle for this resource.
Nevernull .
-
getSwaggerProvider
Returns the Swagger provider used by this resource.See Also:
- Returns:
- The information provider for this resource.
Nevernull .
-
getResource
Returns the resource object.This is the instance of the class annotated with the
@Rest
annotation, usually an instance ofRestServlet
.- Returns:
- The resource object.
Nevernull .
-
getServletInitParameter
Returns the servlet init parameter returned byServletConfig.getInitParameter(String)
.- Parameters:
name
- The init parameter name.- Returns:
- The servlet init parameter, or
null if not found.
-
getRestChildren
Returns the child resources associated with this servlet.- Returns:
- An unmodifiable map of child resources.
Keys are the
@Rest(path)
annotation defined on the child resource.
-
isRenderResponseStackTraces
Returns whether it's safe to render stack traces in HTTP responses.- Returns:
true if setting is enabled.
-
isAllowContentParam
Returns whether it's safe to pass the HTTP content as a"content" GET parameter.See Also:
- Returns:
true if setting is enabled.
-
getAllowedHeaderParams
Allowed header URL parameters.See Also:
- Returns:
- The header names allowed to be passed as URL parameters.
The set is case-insensitive ordered and unmodifiable.
-
getAllowedMethodHeaders
Allowed method headers.See Also:
- Returns:
- The method names allowed to be passed as
X-Method headers.
The set is case-insensitive ordered and unmodifiable.
-
getAllowedMethodParams
Allowed method URL parameters.See Also:
- Returns:
- The method names allowed to be passed as
method URL parameters.
The set is case-insensitive ordered and unmodifiable.
-
getClientVersionHeader
Returns the name of the client version header name used by this resource.See Also:
- Returns:
- The name of the client version header used by this resource.
Nevernull .
-
getStaticFiles
Returns the static files associated with this context.- Returns:
- The static files for this resource.
Nevernull .
-
getLogger
Returns the logger associated with this context.- Returns:
- The logger for this resource.
Nevernull .
-
getThrownStore
Returns the stack trace database associated with this context.- Returns:
- The stack trace database for this resource.
Nevernull .
-
getPartParser
Returns the HTTP-part parser associated with this resource.- Returns:
- The HTTP-part parser associated with this resource.
Nevernull .
-
getPartSerializer
Returns the HTTP-part serializer associated with this resource.- Returns:
- The HTTP-part serializer associated with this resource.
Nevernull .
-
getJsonSchemaGenerator
Returns the JSON-Schema generator associated with this resource.- Returns:
- The HTTP-part serializer associated with this resource.
Nevernull .
-
getProduces
Returns the explicit list of supported accept types for this resource.Consists of the media types for production common to all operations on this class.
Can be overridden by
RestContext.Builder.produces(MediaType...)
.- Returns:
- An unmodifiable list of supported
Accept header values for this resource.
Nevernull .
-
getConsumes
Returns the explicit list of supported content types for this resource.Consists of the media types for consumption common to all operations on this class.
Can be overridden by
RestContext.Builder.consumes(MediaType...)
.- Returns:
- An unmodifiable list of supported
Content-Type header values for this resource.
Nevernull .
-
getDefaultRequestHeaders
Returns the default request headers for this resource.See Also:
- Returns:
- The default request headers for this resource in an unmodifiable list.
Nevernull .
-
getDefaultRequestAttributes
Returns the default request attributes for this resource.See Also:
- Returns:
- The default request headers for this resource in an unmodifiable list.
Nevernull .
-
getDefaultResponseHeaders
Returns the default response headers for this resource.See Also:
- Returns:
- The default response headers for this resource in an unmodifiable list.
Nevernull .
-
getUriAuthority
Returns the authority path of the resource.See Also:
- Returns:
- The authority path of this resource.
If not specified, returns the context path of the ascendant resource.
-
getUriContext
Returns the context path of the resource.See Also:
- Returns:
- The context path of this resource.
If not specified, returns the context path of the ascendant resource.
-
getUriRelativity
Returns the setting on how relative URIs should be interpreted as relative to.See Also:
- Returns:
- The URI-resolution relativity setting value.
Nevernull .
-
getUriResolution
Returns the setting on how relative URIs should be resolved.See Also:
- Returns:
- The URI-resolution setting value.
Nevernull .
-
getRestOperations
Returns the REST Java methods defined in this resource.These are the methods annotated with the
@RestOp
annotation.- Returns:
- An unmodifiable map of Java method names to call method objects.
-
getMethodExecStore
Returns the timing statistics on all method executions on this class.- Returns:
- The timing statistics on all method executions on this class.
-
getStats
Gives access to the internal statistics on this context.- Returns:
- The context statistics.
-
getResourceClass
Returns the resource class type.- Returns:
- The resource class type.
-
getBuilder
Returns the builder that created this context.- Returns:
- The builder that created this context.
-
getPathMatcher
Returns the path matcher for this context.- Returns:
- The path matcher for this context.
-
getRootBeanStore
Returns the root bean store for this context.- Returns:
- The root bean store for this context.
-
getSwagger
Returns the swagger for the REST resource.- Parameters:
locale
- The locale of the swagger to return.- Returns:
- The swagger as an
Optional
. Nevernull .
-
findRestOperationArgs
Finds theRestOpArg
instances to handle resolving objects on the calls to the specified Java method.- Parameters:
m
- The Java method being called.beanStore
- The factory used for creating beans and retrieving injected beans.
Created byRestContext.Builder.beanStore()
.- Returns:
- The array of resolvers.
-
getPreCallMethods
Returns the list of methods to invoke before the actual REST method is called.- Returns:
- The list of methods to invoke before the actual REST method is called.
-
getPostCallMethods
Returns the list of methods to invoke after the actual REST method is called.- Returns:
- The list of methods to invoke after the actual REST method is called.
-
execute
public void execute(Object resource, jakarta.servlet.http.HttpServletRequest r1, jakarta.servlet.http.HttpServletResponse r2) throws jakarta.servlet.ServletException, IOException The main service method.Subclasses can optionally override this method if they want to tailor the behavior of requests.
- Parameters:
resource
- The REST servlet or bean that this context defines.
Note that this bean may not be the same bean used during initialization as it may have been replaced at runtime.r1
- The incoming HTTP servlet request object.r2
- The incoming HTTP servlet response object.- Throws:
jakarta.servlet.ServletException
- General servlet exception.IOException
- Thrown by underlying stream.
-
getDebugEnablement
Returns the debug enablement bean for this context.- Returns:
- The debug enablement bean for this context.
-
processResponse
protected void processResponse(RestOpSession opSession) throws IOException, BasicHttpException, NotImplemented The main method for serializing POJOs passed in through theRestResponse.setContent(Object)
method or returned by the Java method.Subclasses may override this method if they wish to modify the way the output is rendered or support other output formats.
The default implementation simply iterates through the response handlers on this resource looking for the first one whose
ResponseProcessor.process(RestOpSession)
method returnstrue .- Parameters:
opSession
- The HTTP call.- Throws:
IOException
- Thrown by underlying stream.BasicHttpException
- Non-200 response.NotImplemented
- No registered response processors could handle the call.
-
convertThrowable
Method that can be subclassed to allow uncaught throwables to be treated as other types of throwables.The default implementation looks at the throwable class name to determine whether it can be converted to another type:
"*AccessDenied*" - Converted toUnauthorized
."*Empty*" ,"*NotFound*" - Converted toNotFound
.
- Parameters:
t
- The thrown object.- Returns:
- The converted thrown object.
-
handleNotFound
Handle the case where a matching method was not found.Subclasses can override this method to provide a 2nd-chance for specifying a response. The default implementation will simply throw an exception with an appropriate message.
- Parameters:
session
- The HTTP call.- Throws:
Exception
- Any exception can be thrown.
-
handleError
Method for handling response errors.Subclasses can override this method to provide their own custom error response handling.
- Parameters:
session
- The rest call.e
- The exception that occurred.- Throws:
IOException
- Can be thrown if a problem occurred trying to write to the output stream.
-
startCall
Called at the start of a request to invoke allRestStartCall
methods.- Parameters:
session
- The current request.- Throws:
BasicHttpException
- If thrown from call methods.
-
preCall
Called during a request to invoke allRestPreCall
methods.- Parameters:
session
- The current request.- Throws:
Throwable
- If thrown from call methods.
-
postCall
Called during a request to invoke allRestPostCall
methods.- Parameters:
session
- The current request.- Throws:
Throwable
- If thrown from call methods.
-
endCall
Called at the end of a request to invoke allRestEndCall
methods.This is the very last method called in
execute(Object, HttpServletRequest, HttpServletResponse)
.- Parameters:
session
- The current request.
-
postInit
Called during servlet initialization to invoke allRestPostInit
child-last methods.- Returns:
- This object.
- Throws:
jakarta.servlet.ServletException
- Error occurred.
-
postInitChildFirst
Called during servlet initialization to invoke allRestPostInit
child-first methods.- Returns:
- This object.
- Throws:
jakarta.servlet.ServletException
- Error occurred.
-
destroy
Called during servlet destruction to invoke allRestDestroy
methods. -
getLocalSession
Returns the HTTP call for the current request.- Returns:
- The HTTP call for the current request, never
null ? - Throws:
InternalServerError
- If no active request exists on the current thread.
-
getAnnotations
Returns the annotations applied to this context.- Returns:
- The annotations applied to this context.
-
properties
Description copied from class:Context
Returns the properties on this bean as a map for debugging.- Overrides:
properties
in classContext
- Returns:
- The properties on this bean as a map for debugging.
-