Class RestContext

java.lang.Object
org.apache.juneau.marshall.Context
org.apache.juneau.rest.server.RestContext

public class RestContext extends Context
Defines the initial configuration of a RestServlet or @Rest annotated object.

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. encoders, parsers, restDebugFormatter) to the REST resource's bean store. Where direct construction is needed (test rigs, mock clients, embedded usage), the public constructor takes a RestContext.Args record carrying the bootstrap state.

Example:

@Rest(path="/myresource", serializers=JsonSerializer.class, parsers=JsonParser.class) public class MyResource { // Programmatically contribute a bean to the resource's bean store. @Bean public RestDebugFormatter restDebugFormatter() { return new MyCustomRestDebugFormatter(); } }

The historical public MyResource(RestContext.Builder builder) constructor-injection pattern and the @RestInit public void init(RestContext.Builder builder) method-injection pattern were both removed in 10.0. 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:
  • Field Details

  • Constructor Details

    • RestContext

      public RestContext(RestContext.Args args) throws Exception
      Constructor.
      Parameters:
      args - The bootstrap arguments. Must not be null.
      Throws:
      Exception - If any initialization problems were encountered.
      Since:
      10.0.0
  • Method Details

    • getGlobalRegistry

      public static final Map<Class<?>,RestContext> getGlobalRegistry()
      Returns a registry of all created RestContext objects.
      Returns:
      An unmodifiable map of resource classes to RestContext objects.
    • 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 the RestContext has been constructed (e.g. JettyServerComponent's auto-discovery loop, or Spring Boot's ServletRegistrationBean wiring).

      Operates on the same chain as getPaths() but skips the programmatic Builder rung (which is only meaningful inside the RestContext constructor):

      1. The resource's getPaths() virtual getter (defined on RestServlet / RestResource). null return falls through; non-null (including empty array) wins.
      2. @Rest(paths) annotation default on the most-derived class, SVL-resolved per element and comma-split. A VarResolver is looked up on store (when present); SVL variables like $C{key} resolve against beans visible to the bean store.
      Parameters:
      resourceClass - The @Rest-annotated resource class. Must not be null.
      resource - The resource instance. May be null (in which case the getter rung is skipped).
      store - The bean store used to look up the VarResolver for SVL substitution on annotation elements, and to back the resolver session for bean-driven SVL vars like $C{key}. May be null (SVL is then skipped; literals pass through unchanged).
      Returns:
      The resolved paths array (never null; possibly empty).
      Since:
      10.0.0
    • isMixinContext

      public boolean isMixinContext()
      Returns true when this context is a per-mixin sub-context constructed by the host's restOperations memoizer.

      A mixin sub-context is parent-linked to the host's RestContext so that annotation-property walks prepend the host's @Rest chain 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's non-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:
      true if this is a mixin sub-context, false for top-level resources and child resources.
      Since:
      10.0.0
    • getParentContext

      Returns the parent RestContext, or null for top-level resources.

      The parent linkage drives the inheritance walk in getRestAnnotationsForProperty(String) for mixin sub-contexts, and the parentContext walks performed by getMessages(), getVarResolver(), getFullPath(), and the bean-store layering.

      Returns:
      The parent context, or null for 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

      protected void authenticate(RestOpSession session) throws AuthenticationException
      Runs the effective authenticator chain for this request, folding results and applying the resolved principal/roles to the RestRequest.

      Invoked by RestSession before preCall. When no authenticators are configured this is a no-op (anonymous passthrough). Each authenticator's AuthenticationException propagates to abort the request with a 401.

      Parameters:
      session - The op session for this request.
      Throws:
      AuthenticationException - If credentials are present but invalid.
      Since:
      10.0.0
    • getMixinContexts

      Returns the per-mixin RestContext sub-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; never null.
      Since:
      10.0.0
    • getMixinMountPrefixes

      Returns the host-chosen mount prefix(es) declared on the @Mixin that produced this mixin sub-context, for re-mounting the mixin's endpoints under host-chosen path(s).

      Resolved from Mixin.path() and Mixin.paths() (SVL-resolved, then normalized via the same pathToken cleanup the bundled SVL-configurable mixins use — leading/trailing slashes and a trailing /* wildcard stripped to a bare token). Mixin.path() (single) and Mixin.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: 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 class Context
      Returns:
      A new session builder.
    • getRestAnnotations

      Returns all Rest annotations on the resource class hierarchy, in child-to-parent order.
      Returns:
      An unmodifiable list of AnnotationInfo for Rest, never null.
    • getRestAnnotation

      Returns the nearest Rest annotation on this resource.
      Returns:
      An Optional containing the first (most-derived) Rest AnnotationInfo.
    • getRestAnnotationsTopDown

      Returns the Rest annotations 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 AnnotationInfo for Rest, never null.
    • isInherited

      protected boolean isInherited(String property)
      Returns true if values for the given annotation attribute may be inherited from parentContext.

      Inheritance is blocked when the nearest @Rest(noInherit) lists the property name (case-insensitive).

      Parameters:
      property - The annotation attribute name (e.g. "allowedSerializerOptions").
      Returns:
      true if parent values should be included.
    • resolve

      protected String resolve(String s)
      Resolves SVL variables in the given string.
      Parameters:
      s - The raw string. Can be null.
      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

      public void destroy()
      Called during servlet destruction to invoke all RestDestroy methods.

      Fires this context's own @RestDestroy methods 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 or X-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

      public jakarta.servlet.ServletConfig 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 > a RestDebugFormatter bean registered in the bean store (or a @Bean-annotated factory method) > BasicRestDebugFormatter.

      See Also:
      Returns:
      The debug formatter to use for this resource.
      Never null.
    • getRequestIdSettings

      Returns the effective RequestIdSettings for this resource's always-on request-id correlation resolver.

      Resolved once (memoized) via the three-rung precedence: registered bean, @Bean factory method, then the built-in defaults. Consumed by RestSession at build time to mint or honor the X-Request-Id correlation 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.
      Never null.
    • getConfig

      public Config 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.
      Never null.
    • 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.
      Never null.
    • getDefaultRequestAttributes

      Returns the default request attributes for this resource.
      See Also:
      Returns:
      The default request headers for this resource in an unmodifiable list.
      Never null.
    • getDefaultRequestHeaders

      Returns the default request headers for this resource.
      See Also:
      Returns:
      The default request headers for this resource in an unmodifiable list.
      Never null.
    • getDefaultResponseHeaders

      Returns the default response headers for this resource.
      See Also:
      Returns:
      The default response headers for this resource in an unmodifiable list.
      Never null.
    • getEncoders

      Returns the encoders associated with this context.
      Returns:
      The encoders associated with this context.
    • getFullPath

      public String getFullPath()
      Returns the path for this resource as defined by the @Rest(path) annotation or Rest.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.
      Never null.
    • 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.
      Never null.
    • getMessages

      Returns the resource bundle used by this resource.
      Returns:
      The resource bundle for this resource.
      Never null.
    • 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.
      Never null.
    • getPartSerializer

      Returns the HTTP-part serializer associated with this resource.
      Returns:
      The HTTP-part serializer associated with this resource.
      Never null.
    • getPath

      public String getPath()
      Returns the path for this resource as defined by the @Rest(path) annotation or Rest.path() annotation attribute.

      If path is not specified, returns "".

      See Also:
      Returns:
      The servlet path.
    • getPaths

      public String[] getPaths()
      Returns the resolved top-level mount paths for this resource.

      Computed once during RestContext construction by walking the runtime-override resolution chain (highest precedence first):

      1. Programmatic — RestContext.Builder.paths(String...) setter (or RestContext.Args.paths() record field). Highest precedence; an empty array (not null) explicitly clears the mount list.
      2. Getter — the resource's getPaths() virtual method (defined on RestServlet and RestResource). null return inherits; non-null (including empty array) wins over the annotation default.
      3. 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 bootstrap VarResolver, 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's ServletRegistrationBean wiring — 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
    • 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.
      Never null.
    • getResource

      public Object getResource()
      Returns the resource object.

      This is the instance of the class annotated with the @Rest annotation, usually an instance of RestServlet.

      Returns:
      The resource object.
      Never null.
    • getResourceClass

      public Class<?> 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.
      Never null.
    • getRestOpArgs

      public Class<? extends RestOpArg>[] getRestOpArgs()
      Returns the RestOpArg classes registered on this resource.

      Per-op RestOpArg instances are resolved separately at per-op setup via the bean store (see findRestOperationArgs(Method, BeanStore)); this getter returns the class list that drives that resolution.

      See Also:
      Returns:
      The REST-op-arg classes for this resource.
      Never null.
    • 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 @RestOp annotation.

      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's inheritable 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 @Bean method results and non-null @Bean field values on top of the bootstrap 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 by SpringRestServlet).

      Precedence and isolation:

      • A child's own @Bean of 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 @Rest configuration.
      • 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 RootResources extends BasicRestServletGroup { // One store shared by every child resource. @Bean public PetStore petStore() { return new PetStore(); } } @Rest(path="/pets") public class PetResource extends BasicRestResource { @Inject PetStore store; // 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
    • getSerializers

      Returns the serializers associated with this context.
      Returns:
      The serializers associated with this context.
    • getServletInitParameter

      Returns the servlet init parameter returned by ServletConfig.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.
      Never null.
    • getStats

      Gives access to the internal statistics on this context.
      Returns:
      The context statistics.
    • getSwagger

      public Optional<Swagger> getSwagger(Locale locale)
      Returns the swagger for the REST resource.
      Parameters:
      locale - The locale of the swagger to return. Must not be null.
      Returns:
      The swagger as an Optional. Never null.
    • getSwaggerProvider

      Returns the Swagger provider used by this resource.
      See Also:
      Returns:
      The information provider for this resource.
      May be null.
    • getOpenApi

      public Optional<OpenApi> getOpenApi(Locale locale)
      Returns the OpenAPI 3.1 document for the REST resource.
      Parameters:
      locale - The locale of the document to return. Must not be null.
      Returns:
      The OpenAPI document as an Optional. Never null.
    • getOpenApiProvider

      Returns the OpenAPI 3.1 provider used by this resource.
      See Also:
      Returns:
      The OpenAPI 3.1 provider for this resource.
      May be null.
    • getThrownStore

      Returns the stack trace database associated with this context.
      Returns:
      The stack trace database for this resource.
      Never null.
    • 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.
      Never null.
    • getUriResolution

      Returns the setting on how relative URIs should be resolved.
      See Also:
      Returns:
      The URI-resolution setting value.
      Never null.
    • 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 MyRestResource extends 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(RestRequest req, @Path String name) 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 Var catalog as getVarResolver() but does not have Messages or Config beans 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

      public boolean isAllowContentParam()
      Returns whether the "content" URL parameter may be used to supply the request body.

      When this returns true (the default), RestRequest still only honors the parameter on PUT/POST requests, so a simple cross-origin GET can't use it to smuggle a body past an endpoint's real Content-Type gate.

      See Also:
      Returns:
      true if setting is enabled.
    • isRenderResponseStackTraces

      public boolean isRenderResponseStackTraces()
      Returns whether it's safe to render stack traces in HTTP responses.

      Besides the full stack trace, this setting also gates the Thrown error-response header and the message text of any error-body exception that wasn't itself deliberately thrown by application code as a BasicHttpException (see handleError(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

      public boolean isProblemDetails()
      Returns whether this resource is opted into RFC 7807 application/problem+json error responses.

      When true:

      • Thrown BasicHttpExceptions are serialized as application/problem+json via RestContext.handleError — regardless of the client's Accept header.
      • @RestOp methods that return a Problem (or throw a ProblemException) are serialized by ProblemDetailsProcessor, but only when the client's Accept header matches application/problem+json (or *&#47;*).
      See Also:
      Returns:
      true if RFC 7807 problem-details responses are enabled on this resource.
    • isDebugMarshalling

      public boolean isDebugMarshalling()
      Returns whether REST-driven serializer/parser debug behavior is enabled on this resource via @Rest(debugMarshalling="true").

      When true, the REST layer forces Context.debug on 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

      public boolean 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-null executor; on runtimes older than Java 21 the executor is null and 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 in RestOpContext.

      Returns:
      The resolved @Rest(observability) string, or null when not set.
    • isObservabilityDisabled

      public boolean isObservabilityDisabled()
      Returns whether the resource explicitly opted out of observability via @Rest(observability="false").
      Returns:
      true when the resource-level observability is disabled.
    • isResponseTraceparent

      public boolean isResponseTraceparent()
      Returns whether the server writes W3C traceparent / tracestate response headers when a TracerHook is active on the request.

      Defaults to true (on-when-tracer); resolved from the RestContext.responseTraceparent env-driven default. When true, a TraceContextResponseProcessor is registered in the response-processor chain — it writes the headers only when a non-no-op TracerHook stashed a trace context for the request, so it stays zero-cost on the no-tracer path. When false, the processor is not registered at all.

      Returns:
      true if trace-context response-header propagation is enabled on this resource.
    • isMdcAsyncPropagation

      public boolean isMdcAsyncPropagation()
      Returns whether SLF4J MDC propagation is enabled for CompletableFuture completion threads on this resource.

      Defaults to true; resolved first from the programmatic RestContext.Builder.mdcAsyncPropagation(boolean) override (if set), then from the RestContext.mdcAsyncPropagation env-driven default. When true, MdcAsyncListener wraps the whenComplete callback registered by AsyncResponseProcessor so the completion thread sees the request thread's MDC context. When false, no MDC work is done.

      Returns:
      true if MDC async propagation is enabled on this resource.
    • getRestContextProperties

      Returns the bound RestContextProperties for this resource.

      These are the env-driven RestContext.* defaults that seed this context's resolved settings before the @Rest annotation chain is applied. The same instance is registered in this resource's bean store, so it is also retrievable via beanStore().getBean(RestContextProperties.class) — unless the resource registers its own RestContextProperties bean, 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, or null when @Rest(virtualThreads=true) is unset, the runtime is older than Java 21, or executor construction failed (in which case a WARNING was logged at context init).
      Returns:
      The executor, or null if virtual-thread dispatch is not active for this resource.
    • getAsyncTimeoutMillis

      public long getAsyncTimeoutMillis()
      Returns the configured async-response timeout (milliseconds) for this resource. -1 indicates that no value was supplied at the resource level — the per-op value (or AsyncResponseProcessor's 30-second default) applies in that case.
      Returns:
      The async timeout in milliseconds, or -1 when unset.
    • getAsyncCompletionExecutor

      Returns the Executor configured for routing CompletableFuture completion callbacks on this resource, or null when @Rest(asyncCompletionExecutor) is unset (natural completion thread).
      Returns:
      The executor, or null if no async-completion executor is configured.
      Since:
      10.0.0
    • isEagerInit

      public boolean 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

      public boolean 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):

      1. RestContext.Builder.lazyChildInit(boolean) programmatic knob (if explicitly set).
      2. @Rest(lazyChildren) annotation chain (most-derived wins).
      3. RestContext.lazyChildren env-driven default (default false).
      See Also:
      Returns:
      true if lazy child initialization is enabled.
      Since:
      10.0.0
    • postInit

      public RestContext postInit() throws jakarta.servlet.ServletException
      Called during servlet initialization to invoke all RestPostInit child-last methods.
      Returns:
      This object.
      Throws:
      jakarta.servlet.ServletException - Error occurred.
    • postInitChildFirst

      public RestContext postInitChildFirst() throws jakarta.servlet.ServletException
      Called during servlet initialization to invoke all RestPostInit child-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:

      Parameters:
      t - The thrown object.
      Returns:
      The converted thrown object.
    • endCall

      protected void endCall(RestSession session)
      Called at the end of a request to invoke all RestEndCall methods on this context.

      Fires this context's own @RestEndCall methods against its own resource instance. The host's endCall(...) is invoked from execute(Object, HttpServletRequest, HttpServletResponse); for mixin-endpoint requests, that path additionally calls endCall on the mixin sub-context after the host's so host hooks fire first, then the mixin's.

      Parameters:
      session - The current request.
    • findRestOperationArgs

      protected RestOpArg[] findRestOperationArgs(Method m, BeanStore beanStore)
      Finds the RestOpArg 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 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

      protected void handleError(RestSession session, Throwable e) throws IOException
      Method for handling response errors.

      Subclasses can override this method to provide their own custom error response handling.

      The Thrown response header and the cause-chain detail normally appended to the error body are both gated behind isRenderResponseStackTraces() (see @Rest(renderResponseStackTraces)), which is off by default. With that flag off, only a message the calling code deliberately supplied via a thrown BasicHttpException (its subclasses, e.g. NotFound or BadRequest) 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 Thrown header is still always set for RRPC dispatch responses (an operation invoked through @RestOp(method=HttpMethod.RRPC)), regardless of isRenderResponseStackTraces(). The RRPC/ @Remote client 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

      protected void handleNotFound(RestSession session) throws Exception
      Throws:
      Exception
    • postCall

      protected void postCall(RestOpSession session) throws Exception
      Called during a request to invoke all RestPostCall methods.

      For mixin-endpoint requests, fires the host's @RestPostCall methods first (via the host's localPostCallInvokers), 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

      protected void preCall(RestOpSession session) throws Exception
      Called during a request to invoke all RestPreCall methods.

      For mixin-endpoint requests, fires the host's @RestPreCall methods first (via the host's localPreCallInvokers), 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

      The main method for serializing POJOs passed in through the RestResponse.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 returns true.

      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: Context
      Returns the properties on this bean as a map for debugging.
      Overrides:
      properties in class Context
      Returns:
      The properties on this bean as a map for debugging.
    • startCall

      protected void startCall(RestSession session) throws BasicHttpException
      Called at the start of a request to invoke all RestStartCall methods on this context.

      Fires this context's own @RestStartCall methods against its own resource instance. The host version is invoked from execute(Object, HttpServletRequest, HttpServletResponse) before the operation is resolved; once the operation is known to belong to a mixin sub-context, RestSession.run() additionally calls startCall on the mixin context so host hooks fire first, then the mixin's.

      Parameters:
      session - The current request.
      Throws:
      BasicHttpException - If thrown from call methods.