Class RestContext
An extension of the ServletConfig object used during servlet initialization.
Configuration is supplied declaratively through the @Rest annotation on the resource class
(and inherited from any parent classes), and programmatically through @Bean-annotated
methods/fields that contribute named beans (e.g. RestContext.Args record carrying the bootstrap state.
Example:
The historical @RestInit public void init(RestContext.Builder builder)RestContext.Builder itself is on the deletion path; new code should not depend on it.
See v10.0 Migration Guide
for replacement recipes.
Notes:
- This class is thread safe and reusable.
See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final recordBootstrap arguments forRestContext.static interfaceThe build-time kind of aRestContext— which of the three construction flavors produced it.static final recordNormalized carrier for a routed child, produced by discovery from either a bareRest.children()class or a rich@Childdeclaration — the exact structural analog ofRestContext.ResolvedMixin.static final recordThe discovery-time normalized declaration of a single mixin. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final WritableBeanStoreprotected final WritableBeanStoreprotected final org.apache.juneau.rest.server.RestContext.Builderprotected final RestContext.ContextKindThe build-time kind of this context (nevernull).protected final Stringprotected final WritableBeanStoreprotected final BasicHttpExceptionprotected final AtomicBooleanprotected final booleanprotected final ThreadLocal<RestSession>protected final ConcurrentHashMap<Locale,OpenApi> protected final RestContextprotected final Stringprotected final UrlPathMatcherprotected final String[]protected final RestContext.ResolvedChildThe normalized child declaration that produced this sub-context, ornullwhen not a child context.protected final RestContext.ResolvedMixinThe normalized mixin declaration that produced this sub-context, ornullwhen not a mixin context.protected final Class<?>protected final Instantprotected final ConcurrentHashMap<Locale,Swagger> Fields inherited from class org.apache.juneau.marshall.Context
CONTEXT_APPLY_FILTER -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidauthenticate(RestOpSession session) Runs the effective authenticator chain for this request, folding results and applying the resolved principal/roles to theRestRequest.Method that can be subclassed to allow uncaught throwables to be treated as other types of throwables.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 on this context.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 parser session-option keys allowed for this resource.Returns the serializer session-option keys allowed for this resource.Returns the annotations applied to this context.Returns theExecutorconfigured for routingCompletableFuturecompletion callbacks on this resource, ornullwhen@Rest(asyncCompletionExecutor)is unset (natural completion thread).longReturns the configured async-response timeout (milliseconds) for this resource.Returns the bean store associated with this context.Returns the bootstrap bean store for this context.Returns the bootstrap (pre-runtime) variable resolver used during context construction.jakarta.servlet.ServletConfigReturns the builder that created this context.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 default request attributes for this resource.Returns the default request headers for this resource.Returns the default response headers for this resource.Returns the list of methods to invoke during servlet destruction.Returns the effective (root-to-this) authenticator chain for this resource.Returns the encoders associated with this context.Returns the list of methods to invoke at the end of each HTTP request.Returns the path for this resource as defined by the@Rest(path)annotation orRest.path()annotation attribute concatenated with those on all parent classes.static final Map<Class<?>,RestContext> Returns a registry of all createdRestContextobjects.Returns the bean store that this resource exposes to its@Rest(children)sub-resources.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 marshalling context 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.Map<Class<?>,RestContext> Returns the per-mixinRestContextsub-contexts indexed by mixin class.Returns the host-chosen mount prefix(es) declared on the@Mixinthat produced this mixin sub-context, for re-mounting the mixin's endpoints under host-chosen path(s).Returns the raw resource-level observability attribute value from@Rest(observability).getOpenApi(Locale locale) Returns the OpenAPI 3.1 document for the REST resource.Returns the OpenAPI 3.1 provider used by this resource.Returns the parentRestContext, ornullfor top-level resources.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 orRest.path()annotation attribute.Returns the path matcher for this context.String[]getPaths()Returns the resolved top-level mount paths for this resource.Returns the list of methods to invoke after the actual REST method is called.Returns the list of methods to invoke during servlet post-initialization (child-first phase).Returns the list of methods to invoke during servlet post-initialization (child-last phase).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 effectiveRequestIdSettingsfor this resource's always-on request-id correlation resolver.Returns the resource object.Class<?>Returns the resource class type.Returns the response processors registered on this resource.protected Optional<AnnotationInfo<Rest>>Returns the nearestRestannotation on this resource.protected List<AnnotationInfo<Rest>>Returns allRestannotations on the resource class hierarchy, in child-to-parent order.protected List<AnnotationInfo<Rest>>Returns theRestannotations for this resource in parent-to-child (top-down) order.Returns the child resources associated with this servlet.Returns the boundRestContextPropertiesfor this resource.Returns the debug formatter to use for this resource.Returns theRestOpArgclasses registered on this resource.Returns the REST Java methods defined in this resource.Returns the serializers associated with this context.Returns the servlet init parameter returned byServletConfig.getInitParameter(String).Returns the list of methods to invoke at the start of each HTTP request.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.Returns the lazily-instantiated virtual-thread executor for this resource, ornullwhen@Rest(virtualThreads=true)is unset, the runtime is older than Java 21, or executor construction failed (in which case aWARNINGwas logged at context init).protected voidhandleError(RestSession session, Throwable e) Method for handling response errors.protected voidhandleNotFound(RestSession session) booleanReturns whether the"content" URL parameter may be used to supply the request body.booleanReturns whether REST-driven serializer/parser debug behavior is enabled on this resource via@Rest(debugMarshalling="true").booleanReturns whether framework beans and operation/child contexts are eagerly initialized at construction time.protected booleanisInherited(String property) Returnstrueif values for the given annotation attribute may be inherited fromparentContext.booleanReturns whether this resource's@Rest(children=...)entries are built lazily on first invocation rather than eagerly at parent startup.booleanReturns whether SLF4J MDC propagation is enabled forCompletableFuturecompletion threads on this resource.booleanReturnstruewhen this context is a per-mixin sub-context constructed by the host'srestOperationsmemoizer.booleanReturns whether the resource explicitly opted out of observability via@Rest(observability="false").booleanReturns whether this resource is opted into RFC 7807application/problem+jsonerror responses.booleanReturns whether it's safe to render stack traces in HTTP responses.booleanReturns whether the server writes W3Ctraceparent/tracestateresponse headers when aTracerHookis active on the request.booleanReturns whether the resource opted into per-request virtual-thread dispatch (Java 21+) via@Rest(virtualThreads=true).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.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 StringResolves SVL variables in the given string.static String[]resolveTopLevelPaths(Class<?> resourceClass, Object resource, BeanStore store) Public mount-time path resolver for use by hosting runtimes that mount@Rest-annotated resources before theRestContexthas been constructed (e.g.protected voidstartCall(RestSession session) Called at the start of a request to invoke allRestStartCallmethods on this context.Methods inherited from class org.apache.juneau.marshall.Context
copy, createBuilder, getAnnotationProvider, getSession, init, isDebug, toString
-
Field Details
-
initialized
-
initException
-
beanStore
-
bootstrapBeanStore
-
inheritableBeanStore
-
builder
-
resourceClass
-
swaggerCache
-
openApiCache
-
startTime
-
parentContext
-
isMixinContext
-
contextKind
The build-time kind of this context (nevernull). -
resolvedMixin
The normalized mixin declaration that produced this sub-context, ornullwhen not a mixin context. -
resolvedChild
The normalized child declaration that produced this sub-context, ornullwhen not a child context. -
fullPath
-
path
-
paths
-
localSession
-
pathMatcher
-
-
Constructor Details
-
RestContext
Constructor.- Parameters:
args- The bootstrap arguments. Must not benull .- Throws:
Exception- If any initialization problems were encountered.- Since:
- 10.0.0
-
-
Method Details
-
getGlobalRegistry
Returns a registry of all createdRestContextobjects.- Returns:
- An unmodifiable map of resource classes to
RestContextobjects.
-
resolveTopLevelPaths
public static String[] resolveTopLevelPaths(Class<?> resourceClass, Object resource, BeanStore store) Public mount-time path resolver for use by hosting runtimes that mount@Rest-annotated resources before theRestContexthas been constructed (e.g.JettyServerComponent's auto-discovery loop, or Spring Boot'sServletRegistrationBeanwiring).Operates on the same chain as
getPaths()but skips the programmatic Builder rung (which is only meaningful inside theRestContextconstructor):- The resource's
getPaths()virtual getter (defined onRestServlet/RestResource).nullreturn falls through; non-null(including empty array) wins. @Rest(paths)annotation default on the most-derived class, SVL-resolved per element and comma-split. AVarResolveris looked up onstore(when present); SVL variables like$C{key}resolve against beans visible to the bean store.
- Parameters:
resourceClass- The@Rest-annotated resource class. Must not benull.resource- The resource instance. May benull(in which case the getter rung is skipped).store- The bean store used to look up theVarResolverfor SVL substitution on annotation elements, and to back the resolver session for bean-driven SVL vars like$C{key}. May benull(SVL is then skipped; literals pass through unchanged).- Returns:
- The resolved paths array (never
null; possibly empty). - Since:
- 10.0.0
- The resource's
-
isMixinContext
Returnstruewhen this context is a per-mixin sub-context constructed by the host'srestOperationsmemoizer.A mixin sub-context is parent-linked to the host's
RestContextso thatannotation-property walksprepend the host's@Restchain before the mixin's own — serializers, parsers, encoders, converters, response processors, REST op args, guards, restDebugFormatter, messages, and varResolver tokens all inherit from the host first, with the mixin's contributions appended. Use@Rest(noInherit)on the mixin class to cut off inheritance for any specific property.@Rest(children)sub-resources are not mixin contexts — they retain pre-10.0.0 isolated resolution (no parent-context walk), and inherit only the parent'snon-framework beans. The mixin-vs-child divergence is intentional: mixins are inline composers that share the host's URL namespace; children are heavyweight independent resources mounted at their own URL prefix.- Returns:
trueif this is a mixin sub-context,falsefor top-level resources and child resources.- Since:
- 10.0.0
-
getParentContext
Returns the parentRestContext, ornullfor top-level resources.The parent linkage drives the inheritance walk in
getRestAnnotationsForProperty(String)for mixin sub-contexts, and theparentContextwalks performed bygetMessages(),getVarResolver(),getFullPath(), and the bean-store layering.- Returns:
- The parent context, or
nullfor top-level (host) resources. - Since:
- 10.0.0
-
getEffectiveAuthenticators
Returns the effective (root-to-this) authenticator chain for this resource.- Returns:
- The effective authenticator chain, never
null ; may be empty. - Since:
- 10.0.0
-
authenticate
Runs the effective authenticator chain for this request, folding results and applying the resolved principal/roles to theRestRequest.Invoked by
RestSessionbeforepreCall. When no authenticators are configured this is a no-op (anonymous passthrough). Each authenticator'sAuthenticationExceptionpropagates to abort the request with a401.- Parameters:
session- The op session for this request.- Throws:
AuthenticationException- If credentials are present but invalid.- Since:
- 10.0.0
-
getMixinContexts
Returns the per-mixinRestContextsub-contexts indexed by mixin class.Returns an empty map when this context is itself a mixin sub-context, or when no mixins are declared.
- Returns:
- An unmodifiable map of mixin class to its sub-
RestContext; nevernull. - Since:
- 10.0.0
-
getMixinMountPrefixes
Returns the host-chosen mount prefix(es) declared on the@Mixinthat produced this mixin sub-context, for re-mounting the mixin's endpoints under host-chosen path(s).Resolved from
Mixin.path()andMixin.paths()(SVL-resolved, then normalized via the samepathTokencleanup the bundled SVL-configurable mixins use — leading/trailing slashes and a trailing/*wildcard stripped to a bare token).Mixin.path()(single) andMixin.paths()(multi) are unioned; an empty result means "no host re-mount" (the mixin's own op paths apply unchanged).- Returns:
- The normalized, de-duplicated mount-prefix tokens (no slashes), or an empty list when none; never
null. - Since:
- 10.0.0
-
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.
-
getRestAnnotations
Returns allRestannotations on the resource class hierarchy, in child-to-parent order.- Returns:
- An unmodifiable list of
AnnotationInfoforRest, nevernull.
-
getRestAnnotation
Returns the nearestRestannotation on this resource.- Returns:
- An
Optionalcontaining the first (most-derived)RestAnnotationInfo.
-
getRestAnnotationsTopDown
Returns theRestannotations for this resource in parent-to-child (top-down) order.This is the reverse of
getRestAnnotations(): most-ancestor annotation first, most-derived last. Use this when annotation values should accumulate in inheritance order (e.g. parent values are applied first and child values append or override them).- Returns:
- An unmodifiable list of
AnnotationInfoforRest, nevernull.
-
isInherited
Returnstrueif values for the given annotation attribute may be inherited fromparentContext.Inheritance is blocked when the nearest
@Rest(noInherit)lists the property name (case-insensitive).- Parameters:
property- The annotation attribute name (e.g."allowedSerializerOptions").- Returns:
trueif parent values should be included.
-
resolve
Resolves SVL variables in the given string.- Parameters:
s- The raw string. Can benull.- Returns:
- The resolved string.
-
getAllowedParserOptions
Returns the parser session-option keys allowed for this resource.- Returns:
- An unmodifiable case-insensitive sorted set, never
null.
-
getAllowedSerializerOptions
Returns the serializer session-option keys allowed for this resource.- Returns:
- An unmodifiable case-insensitive sorted set, never
null.
-
destroy
Called during servlet destruction to invoke allRestDestroymethods.Fires this context's own
@RestDestroymethods first, then walks any mixin sub-contexts (host destroys before each mixin's), then any@Rest(children=...)sub-resources, then closes the bean store. Mixin sub-contexts recursively destroy themselves via the same path; flat-inheritance guarantees no further mixin descent occurs from inside a mixin sub-context. -
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 ,X-HTTP-Method-Override ,X-HTTP-Method orX-Method-Override 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.
-
getMarshallingContext
Returns the marshalling context associated with this context.- Returns:
- The marshalling context 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 bean store associated with this context.
-
getBuilder
Returns the builder that created this context.- Returns:
- The builder that created this context.
-
getRestDebugFormatter
Returns the debug formatter to use for this resource.Resolution precedence: the resource class itself implementing
RestDebugFormatter> aRestDebugFormatterbean registered in the bean store (or a@Bean-annotated factory method) >BasicRestDebugFormatter.See Also:
- Returns:
- The debug formatter to use for this resource.
Nevernull .
-
getRequestIdSettings
Returns the effectiveRequestIdSettingsfor this resource's always-on request-id correlation resolver.Resolved once (memoized) via the three-rung precedence: registered bean,
@Beanfactory method, then the built-in defaults. Consumed byRestSessionat build time to mint or honor theX-Request-Idcorrelation id for every request.- Returns:
- The effective request-id settings. Never
null . - Since:
- 10.0.0
-
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
Rest.config().- 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.
Derived from
Rest.consumes()across the resource annotation chain.- Returns:
- An unmodifiable list of supported
Content-Type header values for this resource.
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 .
-
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 orRest.path()annotation attribute 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 orRest.path()annotation attribute.If path is not specified, returns
"" .See Also:
- Returns:
- The servlet path.
-
getPaths
Returns the resolved top-level mount paths for this resource.Computed once during
RestContextconstruction by walking the runtime-override resolution chain (highest precedence first):- Programmatic —
RestContext.Builder.paths(String...)setter (orRestContext.Args.paths()record field). Highest precedence; an empty array (notnull) explicitly clears the mount list. - Getter — the resource's
getPaths()virtual method (defined onRestServletandRestResource).nullreturn inherits; non-null(including empty array) wins over the annotation default. - Annotation default —
Rest.paths(), walked top-down across the resource-class hierarchy with the most-derived non-empty value winning. Each element is REST Server SVL Variables-resolved against the bootstrapVarResolver, then comma-split (trim each piece, drop empties). A single element like"$C{health.paths}"can therefore expand to multiple mount paths.
The resolved array is what hosting runtimes — Jetty's auto-discovery flow in
JettyServerComponent, and Spring Boot'sServletRegistrationBeanwiring — should consume when mounting the resource at the top level.Notes:
-
Returns an empty array (not
null) when none of the rungs resolve. Hosting runtimes interpret an empty array as "no top-level mounts" and surface a clear error naming the resource. -
The scalar
getPath()accessor remains orthogonal to this method.
See Also:
- Returns:
- The resolved mount paths (never
null; possibly empty). - Since:
- 10.0.0
- Programmatic —
-
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.
Derived from
Rest.produces()across the resource annotation chain.- 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.
-
getResponseProcessors
Returns the response processors registered on this resource.Returned in the order they're invoked by
processResponse(RestOpSession). The returned array is the live backing array — callers must not mutate it.See Also:
- Returns:
- The response processors for this resource.
Nevernull .
-
getRestOpArgs
Returns theRestOpArgclasses registered on this resource.Per-op
RestOpArginstances are resolved separately at per-op setup via the bean store (seefindRestOperationArgs(Method, BeanStore)); this getter returns the class list that drives that resolution.See Also:
- Returns:
- The REST-op-arg classes for this resource.
Nevernull .
-
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.
-
getBootstrapBeanStore
Returns the bootstrap bean store for this context.This is the bean store inherited from the parent resource and does not include any beans added by this class. For a
@Rest(children)sub-resource, this is the parent'sinheritable bean store.- Returns:
- The bootstrap bean store for this context.
-
getInheritableBeanStore
Returns the bean store that this resource exposes to its@Rest(children)sub-resources.This store layers this resource's own
@Beanmethod results and non-null @Beanfield values on top of thebootstrap bean store, and is used as the bootstrap bean store of every child. Since each child's inheritable store sits on top of its parent's, a grandchild sees the beans of its parent, its grandparent, and so on up to the root (including any Spring context bridged in at the root bySpringRestServlet).Precedence and isolation:
- A child's own
@Beanof the same type and name wins over the inherited one. - Framework-managed types (serializers, parsers,
MethodExecStore,RestChildren, ...) are not exported; each child builds its own from its own@Restconfiguration. - Beans flow down only: a child's beans are never visible to its parent or its siblings.
Example:
@Rest (children={PetResource.class , OrderResource.class })public class RootResourcesextends BasicRestServletGroup {// One store shared by every child resource. @Bean public PetStore petStore() {return new PetStore(); } }@Rest (path="/pets" )public class PetResourceextends BasicRestResource {@Inject PetStorestore ;// Resolved from the group's @Bean method. @RestGet ("/" )public Collection<Pet> getPets() {return store .getPets(); } }- Returns:
- The bean store exposed to child resources.
- Since:
- 10.0.0
- A child's own
-
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. Must not benull .- 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.
May benull .
-
getOpenApi
Returns the OpenAPI 3.1 document for the REST resource.- Parameters:
locale- The locale of the document to return. Must not benull .- Returns:
- The OpenAPI document as an
Optional. Nevernull .
-
getOpenApiProvider
Returns the OpenAPI 3.1 provider used by this resource.See Also:
- Returns:
- The OpenAPI 3.1 provider for this resource.
May benull .
-
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.
-
getBootstrapVarResolver
Returns the bootstrap (pre-runtime) variable resolver used during context construction.The bootstrap resolver has the same
Varcatalog asgetVarResolver()but does not haveMessagesorConfigbeans wired in — it is used to resolve annotation attribute values (e.g.@Rest(messages=...) ) before those beans are built. Override via@Bean(name="bootstrapVarResolver")on a static method of the resource class.- Returns:
- The bootstrap var resolver in use by this resource.
-
isAllowContentParam
Returns whether the"content" URL parameter may be used to supply the request body.When this returns
true (the default),RestRequeststill only honors the parameter onPUT /POST requests, so a simple cross-originGET can't use it to smuggle a body past an endpoint's realContent-Type gate.See Also:
- Returns:
true if setting is enabled.
-
isRenderResponseStackTraces
Returns whether it's safe to render stack traces in HTTP responses.Besides the full stack trace, this setting also gates the
Thrownerror-response header and the message text of any error-body exception that wasn't itself deliberately thrown by application code as aBasicHttpException(seehandleError(RestSession, Throwable)). Leave this off (the default) outside of local debugging so that unplanned exception types (a database driver error, a file-system exception, and the like) don't incidentally echo their class name or message back to the caller.- Returns:
true if setting is enabled.
-
isProblemDetails
Returns whether this resource is opted into RFC 7807application/problem+jsonerror responses.When
true:- Thrown
BasicHttpExceptions are serialized asapplication/problem+jsonviaRestContext.handleError— regardless of the client'sAcceptheader. @RestOpmethods that return aProblem(or throw aProblemException) are serialized byProblemDetailsProcessor, but only when the client'sAcceptheader matchesapplication/problem+json(or*/*).
See Also:
- Returns:
true if RFC 7807 problem-details responses are enabled on this resource.
- Thrown
-
isDebugMarshalling
Returns whether REST-driven serializer/parser debug behavior is enabled on this resource via@Rest(debugMarshalling="true").When
true, the REST layer forcesContext.debugon the serializer/parser sessions it creates to handle requests — engaging recursion-detection-that-throws, parse-input buffering, and stack-trace-prefixed marshalling exceptions. This is independent of the JUL logger level.See Also:
- Returns:
true if REST-driven marshalling debug is enabled on this resource.
-
isVirtualThreadsEnabled
Returns whether the resource opted into per-request virtual-thread dispatch (Java 21+) via@Rest(virtualThreads=true).The flag is honored only when
getVirtualThreadExecutor()returns a non-nullexecutor; on runtimes older than Java 21 the executor isnulland the flag is logged once at context init.- Returns:
true if virtual-thread dispatch is configured on this resource.
-
getObservabilityAttribute
Returns the raw resource-level observability attribute value from@Rest(observability)."true"— strict opt-in: all operations on this resource require a wired backend."false"— explicit opt-out: the observability block is disabled for all operations.null/ empty — default (inherit / no-op fallback) behavior.
Per-operation overrides from
RestOp.observability()(and verb annotations) take precedence over this value; they are resolved inRestOpContext.- Returns:
- The resolved
@Rest(observability)string, ornullwhen not set.
-
isObservabilityDisabled
Returns whether the resource explicitly opted out of observability via@Rest(observability="false").- Returns:
true when the resource-level observability is disabled.
-
isResponseTraceparent
Returns whether the server writes W3Ctraceparent/tracestateresponse headers when aTracerHookis active on the request.Defaults to
true(on-when-tracer); resolved from theRestContext.responseTraceparentenv-driven default. Whentrue, aTraceContextResponseProcessoris registered in the response-processor chain — it writes the headers only when a non-no-opTracerHookstashed a trace context for the request, so it stays zero-cost on the no-tracer path. Whenfalse, the processor is not registered at all.- Returns:
true if trace-context response-header propagation is enabled on this resource.
-
isMdcAsyncPropagation
Returns whether SLF4J MDC propagation is enabled forCompletableFuturecompletion threads on this resource.Defaults to
true; resolved first from the programmaticRestContext.Builder.mdcAsyncPropagation(boolean)override (if set), then from theRestContext.mdcAsyncPropagationenv-driven default. Whentrue,MdcAsyncListenerwraps thewhenCompletecallback registered byAsyncResponseProcessorso the completion thread sees the request thread's MDC context. Whenfalse, no MDC work is done.- Returns:
true if MDC async propagation is enabled on this resource.
-
getRestContextProperties
Returns the boundRestContextPropertiesfor this resource.These are the env-driven
RestContext.*defaults that seed this context's resolved settings before the@Restannotation chain is applied. The same instance is registered in this resource's bean store, so it is also retrievable viabeanStore().getBean(RestContextProperties.class)— unless the resource registers its ownRestContextPropertiesbean, in which case that bean wins in the store while this method continues to return the instance bound for this context. For a mixin sub-context, this is the mixin's own bound instance, distinct from the host resource's.- Returns:
- The bound instance. Never
null . - Since:
- 10.0.0
-
getVirtualThreadExecutor
Returns the lazily-instantiated virtual-thread executor for this resource, ornullwhen@Rest(virtualThreads=true)is unset, the runtime is older than Java 21, or executor construction failed (in which case aWARNINGwas logged at context init).- Returns:
- The executor, or
nullif virtual-thread dispatch is not active for this resource.
-
getAsyncTimeoutMillis
Returns the configured async-response timeout (milliseconds) for this resource.-1indicates that no value was supplied at the resource level — the per-op value (orAsyncResponseProcessor's 30-second default) applies in that case.- Returns:
- The async timeout in milliseconds, or
-1when unset.
-
getAsyncCompletionExecutor
Returns theExecutorconfigured for routingCompletableFuturecompletion callbacks on this resource, ornullwhen@Rest(asyncCompletionExecutor)is unset (natural completion thread).- Returns:
- The executor, or
nullif no async-completion executor is configured. - Since:
- 10.0.0
-
isEagerInit
Returns whether framework beans and operation/child contexts are eagerly initialized at construction time.See Also:
- Returns:
true if eager initialization is enabled.
-
isLazyChildren
Returns whether this resource's@Rest(children=...)entries are built lazily on first invocation rather than eagerly at parent startup.Resolution order (highest wins):
RestContext.Builder.lazyChildInit(boolean)programmatic knob (if explicitly set).@Rest(lazyChildren)annotation chain (most-derived wins).RestContext.lazyChildrenenv-driven default (defaultfalse).
See Also:
Rest.lazyChildren()RestContext.Builder.lazyChildInit(boolean)
- Returns:
true if lazy child initialization is enabled.- Since:
- 10.0.0
-
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:
BeanQuerySyntaxException- Converted toBadRequestcarrying the exception's message and an "X-BeanQuery-Error" header set to itscode().BeanQueryExecutionException- Converted toInternalServerErrorwith the generic message"Query execution failed." ; the original exception (and its cause) stays attached for logging."*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 on this context.Fires this context's own
@RestEndCallmethods against its own resource instance. The host'sendCall(...)is invoked fromexecute(Object, HttpServletRequest, HttpServletResponse); for mixin-endpoint requests, that path additionally callsendCallon the mixin sub-context after the host's so host hooks fire first, then the mixin's.- 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 during context bootstrap.- 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.
-
getDestroyMethods
Returns the list of methods to invoke during servlet destruction.- Returns:
- The destroy method list, never
null.
-
getEndCallMethods
Returns the list of methods to invoke at the end of each HTTP request.- Returns:
- The end-call method list, never
null.
-
getPostInitMethods
Returns the list of methods to invoke during servlet post-initialization (child-last phase).- Returns:
- The post-init method list, never
null.
-
getPostInitChildFirstMethods
Returns the list of methods to invoke during servlet post-initialization (child-first phase).- Returns:
- The post-init-child-first method list, never
null.
-
getStartCallMethods
Returns the list of methods to invoke at the start of each HTTP request.- Returns:
- The start-call method list, never
null.
-
handleError
Method for handling response errors.Subclasses can override this method to provide their own custom error response handling.
The
Thrownresponse header and the cause-chain detail normally appended to the error body are both gated behindisRenderResponseStackTraces()(see@Rest(renderResponseStackTraces)), which is off by default. With that flag off, only a message the calling code deliberately supplied via a thrownBasicHttpException(its subclasses, e.g.NotFoundorBadRequest) is echoed back; the class name and message text of any other, unplanned exception type bubbling up from application code is kept out of both the header and the body, since that text was never authored with a client audience in mind and may otherwise incidentally carry implementation detail (file paths, driver/database error text, and the like). Turn the flag on for local debugging to get the full detail back.The
Thrownheader is still always set for RRPC dispatch responses (an operation invoked through@RestOp(method=HttpMethod.RRPC)), regardless ofisRenderResponseStackTraces(). The RRPC/@Remoteclient stub has no other channel for learning the server-side exception's class in order to reconstruct and rethrow the equivalent type locally, so that one header is part of the RPC contract rather than incidental debug detail. The error body's cause-chain message is unaffected by this exemption and remains suppressed the same as any other operation.- 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
- Throws:
Exception
-
postCall
Called during a request to invoke allRestPostCallmethods.For mixin-endpoint requests, fires the host's
@RestPostCallmethods first (via the host'slocalPostCallInvokers), then the mixin's per-op invokers (RestOpContext.getPostCallMethods()). Host-endpoint requests fire only the host's per-op invokers (the established path; unchanged from pre-10.0.0).- Parameters:
session- The current request.- Throws:
Exception- If thrown from call methods.
-
preCall
Called during a request to invoke allRestPreCallmethods.For mixin-endpoint requests, fires the host's
@RestPreCallmethods first (via the host'slocalPreCallInvokers), then the mixin's per-op invokers (RestOpContext.getPreCallMethods()). Host-endpoint requests fire only the host's per-op invokers (the established path; unchanged from pre-10.0.0).- Parameters:
session- The current request.- Throws:
Exception- If thrown from call methods.
-
processResponse
public 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 on this context.Fires this context's own
@RestStartCallmethods against its own resource instance. The host version is invoked fromexecute(Object, HttpServletRequest, HttpServletResponse)before the operation is resolved; once the operation is known to belong to a mixin sub-context,RestSession.run()additionally callsstartCallon the mixin context so host hooks fire first, then the mixin's.- Parameters:
session- The current request.- Throws:
BasicHttpException- If thrown from call methods.
-