Class RestContext
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
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final booleanprotected final BeanContextprotected final BeanStoreprotected final RestContext.Builderprotected final CallLoggerprotected final Stringprotected final Configprotected final DebugEnablementprotected final Charsetprotected final DefaultClassListprotected final NamedAttributeMapprotected final HeaderListprotected final HeaderListprotected final DefaultSettingsMapprotected final EncoderSetprotected final Stringprotected final BasicHttpExceptionprotected final AtomicBooleanprotected final JsonSchemaGeneratorprotected final ThreadLocal<RestSession>protected final Loggerprotected final longprotected final Messagesprotected final MethodExecStoreprotected final RestContextprotected final ParserSetprotected final HttpPartParserprotected final HttpPartSerializerprotected final Stringprotected final UrlPathMatcherprotected final booleanprotected final Class<?>protected final ResponseProcessor[]protected final RestChildrenprotected final RestOperationsprotected final BeanStoreprotected final SerializerSetprotected final Instantprotected final StaticFilesprotected final ConcurrentHashMap<Locale,Swagger> protected final SwaggerProviderprotected final ThrownStoreprotected final Stringprotected final Stringprotected final UriRelativityprotected final UriResolutionprotected final VarResolverFields inherited from class org.apache.juneau.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected ThrowableMethod that can be subclassed to allow uncaught throwables to be treated as other types of throwables.static RestContext.Buildercreate(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.voiddestroy()Called during servlet destruction to invoke allRestDestroymethods.protected voidendCall(RestSession session) Called at the end of a request to invoke allRestEndCallmethods.voidexecute(Object resource, jakarta.servlet.http.HttpServletRequest r1, jakarta.servlet.http.HttpServletResponse r2) The main service method.protected RestOpArg[]findRestOperationArgs(Method m, BeanStore beanStore) Finds theRestOpArginstances 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.ServletConfigReturns 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 createdRestContextobjects.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 MethodExecStatsReturns 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 MethodListReturns the list of methods to invoke after the actual REST method is called.protected MethodListReturns 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 voidhandleError(RestSession session, Throwable e) Method for handling response errors.protected voidhandleNotFound(RestSession session) Handle the case where a matching method was not found.booleanReturns whether it's safe to pass the HTTP content as a"content" GET parameter.booleanReturns whether it's safe to render stack traces in HTTP responses.protected voidpostCall(RestOpSession session) Called during a request to invoke allRestPostCallmethods.postInit()Called during servlet initialization to invoke allRestPostInitchild-last methods.Called during servlet initialization to invoke allRestPostInitchild-first methods.protected voidpreCall(RestOpSession session) Called during a request to invoke allRestPreCallmethods.protected voidprocessResponse(RestOpSession opSession) The main method for serializing POJOs passed in through theRestResponse.setContent(Object)method or returned by the Java method.Returns the properties on this bean as a map for debugging.protected voidstartCall(RestSession session) Called at the start of a request to invoke allRestStartCallmethods.Methods inherited from class org.apache.juneau.Context
copy, createBuilder, getAnnotationProvider, getSession, init, isDebug, toString
-
Field Details
-
allowContentParam
-
renderResponseStackTraces
-
maxInput
-
initialized
-
initException
-
beanContext
-
beanStore
-
rootBeanStore
-
builder
-
callLogger
-
defaultCharset
-
resourceClass
-
restOpArgs
-
swaggerCache
-
config
-
debugEnablement
-
defaultClasses
-
defaultSettings
-
encoders
-
defaultRequestHeaders
-
defaultResponseHeaders
-
partParser
-
partSerializer
-
startTime
-
jsonSchemaGenerator
-
consumes
-
produces
-
logger
-
messages
-
methodExecStore
-
defaultRequestAttributes
-
parsers
-
restChildren
-
parentContext
-
restOperations
-
responseProcessors
-
serializers
-
allowedHeaderParams
-
allowedMethodHeaders
-
allowedMethodParams
-
staticFiles
-
clientVersionHeader
-
fullPath
-
path
-
uriAuthority
-
uriContext
-
swaggerProvider
-
thrownStore
-
localSession
-
uriRelativity
-
uriResolution
-
pathMatcher
-
varResolver
-
-
Constructor Details
-
RestContext
Constructor.- Parameters:
builder- The builder containing the settings for this bean.- Throws:
Exception- If any initialization problems were encountered.
-
-
Method Details
-
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.
-
getGlobalRegistry
Returns a registry of all createdRestContextobjects.- Returns:
- An unmodifiable map of resource classes to
RestContextobjects.
-
createSession
Description copied from class:ContextCreate 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:
createSessionin classContext- Returns:
- A new session builder.
-
destroy
Called during servlet destruction to invoke allRestDestroymethods. -
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.
-
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.
-
getAnnotations
Returns the annotations applied to this context.- Returns:
- The annotations applied to this context.
-
getBeanContext
Returns the bean context associated with this context.- Returns:
- The bean store associated with this context.
-
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.
-
getBuilder
Returns the builder that created this context.- Returns:
- The builder that created this context.
-
getCallLogger
Returns the call logger to use for this resource.See Also:
- Returns:
- The call logger to use for this resource.
Nevernull .
-
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 .
-
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 .
-
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 .
-
getDebugEnablement
Returns the debug enablement bean for this context.- Returns:
- The debug enablement bean for this context.
-
getDefaultRequestAttributes
Returns the default request attributes for this resource.See Also:
- Returns:
- The default request headers for this resource in an unmodifiable list.
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 .
-
getDefaultResponseHeaders
Returns the default response headers for this resource.See Also:
- Returns:
- The default response headers for this resource in an unmodifiable list.
Nevernull .
-
getEncoders
Returns the encoders associated with this context.- Returns:
- The encoders associated with this context.
-
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.
-
getJsonSchemaGenerator
Returns the JSON-Schema generator associated with this resource.- Returns:
- The HTTP-part serializer associated with this resource.
Nevernull .
-
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.
-
getLogger
Returns the logger associated with this context.- Returns:
- The logger for this resource.
Nevernull .
-
getMessages
Returns the resource bundle used by this resource.- Returns:
- The resource bundle for this resource.
Nevernull .
-
getMethodExecStore
Returns the timing statistics on all method executions on this class.- Returns:
- The timing statistics on all method executions on this class.
-
getParsers
Returns the parsers associated with this context.- Returns:
- The parsers associated with this context.
-
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 .
-
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.
-
getPathMatcher
Returns the path matcher for this context.- Returns:
- The path matcher for this context.
-
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 .
-
getResource
Returns the resource object.This is the instance of the class annotated with the
@Restannotation, usually an instance ofRestServlet.- Returns:
- The resource object.
Nevernull .
-
getResourceClass
Returns the resource class type.- Returns:
- The resource class type.
-
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.
-
getRestOperations
Returns the REST Java methods defined in this resource.These are the methods annotated with the
@RestOpannotation.- Returns:
- An unmodifiable map of Java method names to call method objects.
-
getRootBeanStore
Returns the root bean store for this context.- Returns:
- The root bean store for this context.
-
getSerializers
Returns the serializers associated with this context.- Returns:
- The serializers associated with this context.
-
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.
-
getStaticFiles
Returns the static files associated with this context.- Returns:
- The static files for this resource.
Nevernull .
-
getStats
Gives access to the internal statistics on this context.- Returns:
- The context statistics.
-
getSwagger
Returns the swagger for the REST resource.- Parameters:
locale- The locale of the swagger to return.- Returns:
- The swagger as an
Optional. Nevernull .
-
getSwaggerProvider
Returns the Swagger provider used by this resource.See Also:
- Returns:
- The information provider for this resource.
Nevernull .
-
getThrownStore
Returns the stack trace database associated with this context.- Returns:
- The stack trace database for this resource.
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 .
-
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
@HtmlDocConfigannotation:@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.
-
isAllowContentParam
Returns whether it's safe to pass the HTTP content as a"content" GET parameter.See Also:
- Returns:
true if setting is enabled.
-
isRenderResponseStackTraces
Returns whether it's safe to render stack traces in HTTP responses.- Returns:
true if setting is enabled.
-
postInit
Called during servlet initialization to invoke allRestPostInitchild-last methods.- Returns:
- This object.
- Throws:
jakarta.servlet.ServletException- Error occurred.
-
postInitChildFirst
Called during servlet initialization to invoke allRestPostInitchild-first methods.- Returns:
- This object.
- Throws:
jakarta.servlet.ServletException- Error occurred.
-
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.
-
endCall
Called at the end of a request to invoke allRestEndCallmethods.This is the very last method called in
execute(Object, HttpServletRequest, HttpServletResponse).- Parameters:
session- The current request.
-
findRestOperationArgs
Finds theRestOpArginstances 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.
-
getMethodExecStats
Returns the time statistics gatherer for the specified method.- Parameters:
m- The method to get statistics for.- Returns:
- The cached time-stats object.
-
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.
-
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.
-
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.
-
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.
-
postCall
Called during a request to invoke allRestPostCallmethods.- Parameters:
session- The current request.- Throws:
Throwable- If thrown from call methods.
-
preCall
Called during a request to invoke allRestPreCallmethods.- Parameters:
session- The current request.- Throws:
Throwable- If thrown from call methods.
-
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.
-
properties
Description copied from class:ContextReturns the properties on this bean as a map for debugging.- Overrides:
propertiesin classContext- Returns:
- The properties on this bean as a map for debugging.
-
startCall
Called at the start of a request to invoke allRestStartCallmethods.- Parameters:
session- The current request.- Throws:
BasicHttpException- If thrown from call methods.
-