Class RestContext

java.lang.Object
org.apache.juneau.Context
org.apache.juneau.rest.RestContext
All Implemented Interfaces:
AnnotationProvider

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.

Methods are provided for overriding or augmenting the information provided by the @Rest annotation. In general, most information provided in the @Rest annotation can be specified programmatically through calls on this object.

To interact with this object, simply pass it in as a constructor argument or in an INIT hook.

// Option #1 - Pass in through constructor. public MyResource(RestContext.Builder builder) { builder .swaps(TemporalCalendarSwap.IsoLocalDateTime.class); } // Option #2 - Use an init hook. @RestInit public void init(RestContext.Builder builder) throws Exception { builder .swaps(TemporalCalendarSwap.IsoLocalDateTime.class); }

Notes:
  • This class is thread safe and reusable.
See Also:
  • Constructor Details

  • 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.
    • 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 be null.
      parentContext - The parent context if the REST bean was registered via Rest.children().
      Can be null if the bean is a top-level resource.
      servletConfig - The servlet config passed into the servlet by the servlet container.
      Can be null if not available.
      If null, then some features (such as access to servlet init params) will not be available.
      Returns:
      A new builder object.
      Throws:
      jakarta.servlet.ServletException - Something bad happened.
    • createSession

      Description copied from class: Context
      Create a session builder based on the properties defined on this context.

      Use this method for creating sessions where you want to override basic settings. Otherwise, use Context.getSession() directly.

      Overrides:
      createSession in class Context
      Returns:
      A new session builder.
    • getBeanStore

      Returns the bean store associated with this context.

      The bean store is used for instantiating child resource classes.

      Returns:
      The resource resolver associated with this context.
    • getBeanContext

      Returns the bean context associated with this context.
      Returns:
      The bean store associated with this context.
    • getEncoders

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

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

      Returns the parsers associated with this context.
      Returns:
      The parsers associated with this context.
    • getMethodExecStats

      Returns the time statistics gatherer for the specified method.
      Parameters:
      m - The method to get statistics for.
      Returns:
      The cached time-stats object.
    • getVarResolver

      Returns the variable resolver for this servlet.

      Variable resolvers are used to replace variables in property values. They can be nested arbitrarily deep. They can also return values that themselves contain other variables.

      Example:

      @Rest( messages="nls/Messages", properties={ @Property(name="title",value="$L{title}"), // Localized variable in Messages.properties @Property(name="javaVendor",value="$S{java.vendor,Oracle}"), // System property with default value @Property(name="foo",value="bar"), @Property(name="bar",value="baz"), @Property(name="v1",value="$R{foo}"), // Request variable. value="bar" @Property(name="v1",value="$R{foo,bar}"), // Request variable. value="bar" } ) public class 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.
    • getConfig

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

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

      If path is not specified, returns "".

      See Also:
      Returns:
      The servlet path.
    • getFullPath

      public String getFullPath()
      Returns the path for this resource as defined by the @Rest(path) annotation or RestContext.Builder.path(String) method concatenated with those on all parent classes.

      If path is not specified, returns "".

      See Also:
      Returns:
      The full path.
    • getCallLogger

      Returns the call logger to use for this resource.
      See Also:
      Returns:
      The call logger to use for this resource.
      Never null.
    • getMessages

      Returns the resource bundle used by this resource.
      Returns:
      The resource bundle for this resource.
      Never null.
    • getSwaggerProvider

      Returns the Swagger provider used by this resource.
      See Also:
      Returns:
      The information provider 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.
    • 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.
    • getRestChildren

      Returns the child resources associated with this servlet.
      Returns:
      An unmodifiable map of child resources. Keys are the @Rest(path) annotation defined on the child resource.
    • isRenderResponseStackTraces

      public boolean isRenderResponseStackTraces()
      Returns whether it's safe to render stack traces in HTTP responses.
      Returns:
      true if setting is enabled.
    • isAllowContentParam

      public boolean isAllowContentParam()
      Returns whether it's safe to pass the HTTP content as a "content" GET parameter.
      See Also:
      Returns:
      true if setting is enabled.
    • getAllowedHeaderParams

      Returns:
      The header names allowed to be passed as URL parameters.
      The set is case-insensitive ordered and unmodifiable.
    • getAllowedMethodHeaders

      Returns:
      The method names allowed to be passed as X-Method headers.
      The set is case-insensitive ordered and unmodifiable.
    • getAllowedMethodParams

      Returns:
      The method names allowed to be passed as method URL parameters.
      The set is case-insensitive ordered and unmodifiable.
    • getClientVersionHeader

      Returns the name of the client version header name used by this resource.
      See Also:
      Returns:
      The name of the client version header used by this resource.
      Never null.
    • getStaticFiles

      Returns the static files associated with this context.
      Returns:
      The static files for this resource.
      Never null.
    • getLogger

      public Logger getLogger()
      Returns the logger associated with this context.
      Returns:
      The logger for this resource.
      Never null.
    • getThrownStore

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

      Returns the JSON-Schema generator associated with this resource.
      Returns:
      The HTTP-part serializer associated with this resource.
      Never null.
    • 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.
      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.

      Can be overridden by RestContext.Builder.consumes(MediaType...).

      Returns:
      An unmodifiable list of supported Content-Type header values for this resource.
      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.
    • 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.
    • 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.
    • 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.
    • getRestOperations

      Returns the REST Java methods defined in this resource.

      These are the methods annotated with the @RestOp annotation.

      Returns:
      An unmodifiable map of Java method names to call method objects.
    • getMethodExecStore

      Returns the timing statistics on all method executions on this class.
      Returns:
      The timing statistics on all method executions on this class.
    • getStats

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

      public Class<?> getResourceClass()
      Returns the resource class type.
      Returns:
      The resource class type.
    • getBuilder

      public jakarta.servlet.ServletConfig getBuilder()
      Returns the builder that created this context.
      Returns:
      The builder that created this context.
    • getPathMatcher

      Returns the path matcher for this context.
      Returns:
      The path matcher for this context.
    • getRootBeanStore

      Returns the root bean store for this context.
      Returns:
      The root bean store for this context.
    • getSwagger

      public Optional<Swagger> getSwagger(Locale locale)
      Returns the swagger for the REST resource.
      Parameters:
      locale - The locale of the swagger to return.
      Returns:
      The swagger as an Optional. Never null.
    • 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 by RestContext.Builder.beanStore().
      Returns:
      The array of resolvers.
    • getPreCallMethods

      Returns the list of methods to invoke before the actual REST method is called.
      Returns:
      The list of methods to invoke before the actual REST method is called.
    • getPostCallMethods

      Returns the list of methods to invoke after the actual REST method is called.
      Returns:
      The list of methods to invoke after the actual REST method is called.
    • execute

      public void execute(Object resource, jakarta.servlet.http.HttpServletRequest r1, jakarta.servlet.http.HttpServletResponse r2) throws jakarta.servlet.ServletException, IOException
      The main service method.

      Subclasses can optionally override this method if they want to tailor the behavior of requests.

      Parameters:
      resource - The REST servlet or bean that this context defines.
      Note that this bean may not be the same bean used during initialization as it may have been replaced at runtime.
      r1 - The incoming HTTP servlet request object.
      r2 - The incoming HTTP servlet response object.
      Throws:
      jakarta.servlet.ServletException - General servlet exception.
      IOException - Thrown by underlying stream.
    • getDebugEnablement

      Returns the debug enablement bean for this context.
      Returns:
      The debug enablement bean for this context.
    • processResponse

      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.
    • 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.
    • handleNotFound

      protected void handleNotFound(RestSession session) throws Exception
      Handle the case where a matching method was not found.

      Subclasses can override this method to provide a 2nd-chance for specifying a response. The default implementation will simply throw an exception with an appropriate message.

      Parameters:
      session - The HTTP call.
      Throws:
      Exception - Any exception can be thrown.
    • handleError

      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.

      Parameters:
      session - The rest call.
      e - The exception that occurred.
      Throws:
      IOException - Can be thrown if a problem occurred trying to write to the output stream.
    • startCall

      protected void startCall(RestSession session) throws BasicHttpException
      Called at the start of a request to invoke all RestStartCall methods.
      Parameters:
      session - The current request.
      Throws:
      BasicHttpException - If thrown from call methods.
    • preCall

      protected void preCall(RestOpSession session) throws Throwable
      Called during a request to invoke all RestPreCall methods.
      Parameters:
      session - The current request.
      Throws:
      Throwable - If thrown from call methods.
    • postCall

      protected void postCall(RestOpSession session) throws Throwable
      Called during a request to invoke all RestPostCall methods.
      Parameters:
      session - The current request.
      Throws:
      Throwable - If thrown from call methods.
    • endCall

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

      This is the very last method called in execute(Object, HttpServletRequest, HttpServletResponse).

      Parameters:
      session - The current request.
    • 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.
    • destroy

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

      Returns the HTTP call for the current request.
      Returns:
      The HTTP call for the current request, never null?
      Throws:
      InternalServerError - If no active request exists on the current thread.
    • getAnnotations

      Returns the annotations applied to this context.
      Returns:
      The annotations applied to this context.
    • properties

      protected JsonMap 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.