Class ContextHandler

All Implemented Interfaces:
AliasCheck, Handler, Handler.Container, Handler.Singleton, Request.Handler, Attributes, Container, Destroyable, Dumpable, Dumpable.DumpableContainer, LifeCycle, Invocable
Direct Known Subclasses:
HttpSpiContextHandler, MovedContextHandler, ResourceHandler.ResourceContext, ServletContextHandler

@ManagedObject public class ContextHandler extends Handler.Wrapper implements Attributes, AliasCheck
A Handler that scopes a request to a specific Context.
  • Field Details

    • MANAGED_ATTRIBUTES

      public static final String MANAGED_ATTRIBUTES
      See Also:
    • CROSS_CONTEXT_ATTRIBUTE

      public static final String CROSS_CONTEXT_ATTRIBUTE
      The attribute name that is set as a Request attribute to indicate the request is a cross context dispatch. The value can be set to a ServletDispatcher type if the target is known to be a servlet context.
      See Also:
  • Constructor Details

    • ContextHandler

      public ContextHandler()
    • ContextHandler

      public ContextHandler(Handler handler)
    • ContextHandler

      public ContextHandler(String contextPath)
    • ContextHandler

      public ContextHandler(Handler handler, String contextPath)
  • Method Details

    • getCurrentContext

      public static Context getCurrentContext()
      Get the current Context if any.
      Returns:
      The Context from a ContextHandler; or null if the current Thread is not scoped to a ContextHandler.
    • getCurrentContext

      public static Context getCurrentContext(Server server)
      Get the current Context if any, or else server context if any.
      Parameters:
      server - The server.
      Returns:
      The Context from a ContextHandler; or Server.getContext() if the current Thread is not scoped to a ContextHandler.
    • getCurrentContextHandler

      public static ContextHandler getCurrentContextHandler()
    • getContextHandler

      public static ContextHandler getContextHandler(Request request)
    • setServer

      public void setServer(Server server)
      Description copied from interface: Handler
      Set the Server to associate to this Handler.
      Specified by:
      setServer in interface Handler
      Overrides:
      setServer in class Handler.AbstractContainer
      Parameters:
      server - the Server to associate to this Handler
    • newContext

      protected ContextHandler.ScopedContext newContext()
    • getTempDirectory

      @ManagedAttribute(value="temporary directory location", readonly=true) public File getTempDirectory()
      Returns:
      The temporary directory configured for the context, or null if none configured.
      See Also:
    • setTempDirectory

      public void setTempDirectory(File tempDirectory)

      Set the temporary directory returned by ContextHandler.ScopedContext.getTempDirectory(). If not set here, then the Server.getTempDirectory() is returned by ContextHandler.ScopedContext.getTempDirectory().

      If isTempDirectoryPersistent() is true, the directory set here is used directly but may be created if it does not exist. If isTempDirectoryPersistent() is false, then any File set here will be deleted and recreated as a directory during AbstractLifeCycle.start() and will be deleted during AbstractLifeCycle.stop().

      Parameters:
      tempDirectory - A directory. If it does not exist, it must be able to be created during start.
      See Also:
    • setTempDirectoryPersistent

      public void setTempDirectoryPersistent(boolean persist)

      Set if the temp directory for this context will be kept over a stop and start cycle.

      Parameters:
      persist - true to persist the temp directory on shutdown / exit of the context
      See Also:
    • isTempDirectoryPersistent

      public boolean isTempDirectoryPersistent()
      Returns:
      true if tmp directory will persist between startups of the context
    • getMimeTypes

      public MimeTypes.Mutable getMimeTypes()
      Returns:
      A mutable MimeTypes that wraps the Server.getMimeTypes() once setServer(Server) has been called.
      See Also:
    • dump

      public void dump(Appendable out, String indent) throws IOException
      Description copied from interface: Dumpable
      Dump this object (and children) into an Appendable using the provided indent after any new lines. The indent should not be applied to the first object dumped.
      Specified by:
      dump in interface Dumpable
      Overrides:
      dump in class ContainerLifeCycle
      Parameters:
      out - The appendable to dump to
      indent - The indent to apply after any new lines.
      Throws:
      IOException - if unable to write to Appendable
    • getContext

      @ManagedAttribute("Context") public ContextHandler.ScopedContext getContext()
    • getAllowNullPathInContext

      @ManagedAttribute("Checks if the /context is not redirected to /context/") public boolean getAllowNullPathInContext()
      Returns:
      the allowNullPathInfo true if /context is not redirected to /context/
    • setAllowNullPathInContext

      public void setAllowNullPathInContext(boolean allowNullPathInContext)
      Set true if /context is not redirected to /context/.
      Parameters:
      allowNullPathInContext - true if /context is not redirected to /context/
    • setVirtualHosts

      public void setVirtualHosts(List<String> vhosts)
      Set the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a matching virtual host name.
      Parameters:
      vhosts - List of virtual hosts that this context responds to. A null/empty list means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with "*." to wildcard one level of names. Hosts and wildcard hosts may be followed with "@connectorname" (eg: "*.example.org@connectorname"), in which case they will match only if the Connector.getName() for the request also matches. If an entry is just "@connectorname" it will match any host if that connector was used.
    • addVirtualHosts

      public void addVirtualHosts(String... virtualHosts)
      Either set virtual hosts or add to an existing set of virtual hosts.
      Parameters:
      virtualHosts - Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with "@connectorname", in which case they will match only if the Connector.getName() for the request also matches. If an entry is just "@connectorname" it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed and none of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
    • removeVirtualHosts

      public void removeVirtualHosts(String... virtualHosts)
      Removes an array of virtual host entries, if this removes all entries the _vhosts will be set to null
      Parameters:
      virtualHosts - Array of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with "@connectorname", in which case they will match only if the Connector.getName() for the request also matches. If an entry is just "@connectorname" it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed and none of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
    • getVirtualHosts

      @ManagedAttribute(value="Virtual hosts accepted by the context", readonly=true) public List<String> getVirtualHosts()
      Get the virtual hosts for the context. Only requests that have a matching host header or fully qualified URL will be passed to that context with a virtual host name. A context with no virtual host names or a null virtual host name is available to all requests that are not served by a context with a matching virtual host name.
      Returns:
      list of virtual hosts that this context responds to. A null/empty array means any hostname is acceptable. Host names may be String representation of IP addresses. Host names may start with '*.' to wildcard one level of names. Hosts and wildcard hosts may be followed with "@connectorname", in which case they will match only if the Connector.getName() for the request also matches. If an entry is just "@connectorname" it will match any host if that connector was used. Note - In previous versions if one or more connectorname only entries existed and none of the connectors matched the handler would not match regardless of any hostname entries. If there is one or more connectorname only entries and one or more host only entries but no hostname and connector entries we assume the old behavior and will log a warning. The warning can be removed by removing the host entries that were previously being ignored, or modifying to include a hostname and connectorname entry.
    • getAttribute

      public Object getAttribute(String name)
      Description copied from interface: Attributes
      Get an attribute
      Specified by:
      getAttribute in interface Attributes
      Parameters:
      name - the attribute to get
      Returns:
      the value of the attribute, or null if no such attribute exists
    • getAttributeNameSet

      public Set<String> getAttributeNameSet()
      Description copied from interface: Attributes
      Get the immutable set of attribute names.
      Specified by:
      getAttributeNameSet in interface Attributes
      Returns:
      Set of attribute names, or an empty set if there are no attributes.
    • setAttribute

      public Object setAttribute(String name, Object attribute)
      Description copied from interface: Attributes
      Set an attribute
      Specified by:
      setAttribute in interface Attributes
      Parameters:
      name - the attribute to set
      attribute - the value to set. A null value is equivalent to removing the attribute.
      Returns:
      the previous value of the attribute if set, else null
    • removeAttribute

      public Object removeAttribute(String name)
      Description copied from interface: Attributes
      Remove an attribute
      Specified by:
      removeAttribute in interface Attributes
      Parameters:
      name - the attribute to remove
      Returns:
      the value of the attribute if removed, else null
    • getClassLoader

      public ClassLoader getClassLoader()
    • setClassLoader

      public void setClassLoader(ClassLoader contextLoader)
    • getClassPath

      @ManagedAttribute("The file classpath") public String getClassPath()
      Make best effort to extract a file classpath from the context classloader
      Returns:
      Returns the classLoader.
    • getContextPath

      @ManagedAttribute("Context path of the Context") public String getContextPath()
      Returns:
      Returns the contextPath.
    • getDisplayName

      @ManagedAttribute("Display name of the Context") public String getDisplayName()
    • isCrossContextDispatchSupported

      @ManagedAttribute("Cross context dispatch is support by the context") public boolean isCrossContextDispatchSupported()
      Get if this context support cross context dispatch, either as originator or target.
      Returns:
      True if this context supports cross context dispatch.
    • setCrossContextDispatchSupported

      public void setCrossContextDispatchSupported(boolean crossContextDispatchSupported)
      Set if this context support cross context dispatch, either as originator or target.
      Parameters:
      crossContextDispatchSupported - True if this context supports cross context dispatch.
    • getCrossContextHandler

      public ContextHandler getCrossContextHandler(String path)
      If cross context dispatch is supported by this context then find a context by contextPath that also supports cross context dispatch. If more than one context is found, then those with disjoint virtual hosts are excluded and the first remaining context returned.
      Parameters:
      path - The path that will be served by the context
      Returns:
      The found ContextHandler or null.
    • addEventListener

      public boolean addEventListener(EventListener listener)
      Add a context event listeners.
      Specified by:
      addEventListener in interface Container
      Specified by:
      addEventListener in interface LifeCycle
      Overrides:
      addEventListener in class ContainerLifeCycle
      Parameters:
      listener - the event listener to add
      Returns:
      true if the listener was added
      See Also:
    • removeEventListener

      public boolean removeEventListener(EventListener listener)
      Description copied from interface: Container
      Remove an event listener.
      Specified by:
      removeEventListener in interface Container
      Specified by:
      removeEventListener in interface LifeCycle
      Overrides:
      removeEventListener in class ContainerLifeCycle
      Parameters:
      listener - the listener to remove
      Returns:
      true if the listener was removed
      See Also:
    • enterScope

      protected ClassLoader enterScope(Request contextRequest)
    • notifyEnterScope

      protected void notifyEnterScope(Request request)
      Parameters:
      request - A request that is applicable to the scope, or null
    • exitScope

      protected void exitScope(Request request, Context lastContext, ClassLoader lastLoader)
    • notifyExitScope

      protected void notifyExitScope(Request request)
      Parameters:
      request - A request that is applicable to the scope, or null
    • isAvailable

      public boolean isAvailable()
      Returns:
      false if this context is unavailable (sends 503)
    • setAvailable

      public void setAvailable(boolean available)
      Set Available status.
      Parameters:
      available - true to set as enabled
    • doStart

      protected void doStart() throws Exception
      Description copied from class: ContainerLifeCycle
      Starts the managed lifecycle beans in the order they were added.
      Overrides:
      doStart in class Handler.Abstract
      Throws:
      AbstractLifeCycle.StopException - If thrown, the lifecycle will immediately be stopped.
      Exception - If there was a problem starting. Will cause a transition to FAILED state
    • createTempDirectory

      protected void createTempDirectory()

      Create the temporary directory. If the directory exists, but is not persistent, then it is first deleted and then recreated. Once created, this method is a noop if called again before stopping the context.

    • doStop

      protected void doStop() throws Exception
      Description copied from class: ContainerLifeCycle
      Stops the managed lifecycle beans in the reverse order they were added.
      Overrides:
      doStop in class Handler.Abstract
      Throws:
      Exception - If there was a problem stopping. Will cause a transition to FAILED state
    • cleanupAfterStop

      protected void cleanupAfterStop() throws Exception
      Throws:
      Exception
    • makeTempDirectory

      protected void makeTempDirectory() throws Exception
      Generate a reasonable name for the temp directory because one has not been explicitly configured by the user with setTempDirectory(File). The directory may also be created, if it is not persistent. If it is persistent it will be created as necessary by createTempDirectory() later during the startup of the context.
      Throws:
      Exception - IllegalStateException if the parent tmp directory does not exist, or IOException if the child tmp directory cannot be created.
    • getCanonicalNameForTmpDir

      protected String getCanonicalNameForTmpDir()
      Create a canonical name for a context temp directory.

      The form of the name is:

      "jetty-"+host+"-"+port+"-"+resourceBase+"-_"+context+"-"+virtualhost+"-"+randomdigits+".dir"
      host and port uniquely identify the server context and virtual host uniquely identify the context randomdigits ensure every tmp directory is unique
      Returns:
      the canonical name for the context temp directory
    • getResourceForTempDirName

      protected Resource getResourceForTempDirName()
      Returns:
      the baseResource for the context to use in the temp dir name
    • getBaseName

      protected static String getBaseName(Resource resource)
      Parameters:
      resource - the resource whose filename minus suffix to extract
      Returns:
      the filename of the resource without suffix
    • checkVirtualHost

      public boolean checkVirtualHost(Request request)
    • destroy

      public void destroy()
      Description copied from class: ContainerLifeCycle
      Destroys the managed Destroyable beans in the reverse order they were added.
      Specified by:
      destroy in interface Destroyable
      Overrides:
      destroy in class Handler.Abstract
    • handle

      public boolean handle(Request request, Response response, Callback callback) throws Exception
      Description copied from interface: Request.Handler

      Invoked to handle the passed HTTP request and response.

      The request is accepted by returning true, then handling must be concluded by completing the passed callback. The handling may be asynchronous, i.e. this method may return true and complete the given callback later, possibly from a different thread. If this method returns false, then the callback must not be invoked and any mutation on the response reversed.

      Exceptions thrown by this method may be subsequently handled by an error Request.Handler, if present, otherwise a default HTTP 500 error is generated and the callback completed while writing the error response.

      The simplest implementation is:

       public boolean handle(Request request, Response response, Callback callback)
       {
           callback.succeeded();
           return true;
       }
       

      A HelloWorld implementation is:

       public boolean handle(Request request, Response response, Callback callback)
       {
           response.write(true, ByteBuffer.wrap("Hello World\n".getBytes(StandardCharsets.UTF_8)), callback);
           return true;
       }
       
      Specified by:
      handle in interface Request.Handler
      Overrides:
      handle in class Handler.Wrapper
      Parameters:
      request - the HTTP request to handle
      response - the HTTP response to handle
      callback - the callback to complete when the handling is complete
      Returns:
      True if and only if the request will be handled, a response generated and the callback eventually called. This may occur within the scope of the call to this method, or asynchronously some time later. If false is returned, then this method must not generate a response, nor complete the callback.
      Throws:
      Exception - if there is a failure during the handling. Catchers cannot assume that the callback will be called and thus should attempt to complete the request as if a false had been returned.
      See Also:
    • handleByContextHandler

      protected boolean handleByContextHandler(String pathInContext, ContextRequest request, Response response, Callback callback)
    • handleMovedPermanently

      protected void handleMovedPermanently(Request request, Response response, Callback callback)
    • handleUnavailable

      protected void handleUnavailable(Request request, Response response, Callback callback)
    • setContextPath

      public void setContextPath(String contextPath)
      Parameters:
      contextPath - The _contextPath to set.
    • setDisplayName

      public void setDisplayName(String servletContextName)
      Parameters:
      servletContextName - The servletContextName to set.
    • getBaseResource

      @ManagedAttribute(value="document root for context", readonly=true) public Resource getBaseResource()
      Returns:
      Returns the base resource as a string.
    • setBaseResource

      public void setBaseResource(Resource resourceBase)

      Set the base resource to serve content from for this context, which must exist and be readable when the context is started.

      Parameters:
      resourceBase - The base resource for the context.
    • setBaseResourceAsPath

      public void setBaseResourceAsPath(Path path)

      Set the base resource to serve content from.

      Note: the Resource is created from ResourceFactory.of(org.eclipse.jetty.util.component.Container) which is tied to the lifecycle of this context.

      Parameters:
      path - The path to create a base resource from.
      See Also:
    • setBaseResourceAsString

      public void setBaseResourceAsString(String base)

      Set the base resource to serve content from.

      Note: the Resource is created from ResourceFactory.of(org.eclipse.jetty.util.component.Container) which is tied to the lifecycle of this context.

      Parameters:
      base - The path to create a base resource from.
      See Also:
    • getErrorHandler

      @ManagedAttribute("The error handler to use for the context") public Request.Handler getErrorHandler()
      Returns:
      Returns the errorHandler.
    • setErrorHandler

      public void setErrorHandler(Request.Handler errorHandler)
      Parameters:
      errorHandler - The error handler to set.
    • wrapRequest

      protected ContextRequest wrapRequest(Request request, Response response)
    • wrapResponse

      protected ContextResponse wrapResponse(ContextRequest request, Response response)
    • clearAttributes

      public void clearAttributes()
      Description copied from interface: Attributes
      Clear all attribute names
      Specified by:
      clearAttributes in interface Attributes
    • isProtectedTarget

      public boolean isProtectedTarget(String target)
      Check the target when a target within a context is determined. If the target is protected, 404 is returned.
      Parameters:
      target - the target to test
      Returns:
      true if target is a protected target
    • setProtectedTargets

      public void setProtectedTargets(String[] targets)
      Parameters:
      targets - Array of URL prefix. Each prefix is in the form /path and will match either /path exactly or /path/anything
    • getProtectedTargets

      public String[] getProtectedTargets()
    • addAliasCheck

      public void addAliasCheck(AliasCheck check)
      Add an AliasCheck instance to possibly permit aliased resources
      Parameters:
      check - The alias checker
    • getAliasChecks

      public List<AliasCheck> getAliasChecks()
      Returns:
      Immutable list of Alias checks
    • setAliasChecks

      public void setAliasChecks(List<AliasCheck> checks)
      Set list of AliasCheck instances.
      Parameters:
      checks - list of AliasCheck instances
    • clearAliasChecks

      public void clearAliasChecks()
      clear the list of AliasChecks
    • checkAlias

      public boolean checkAlias(String pathInContext, Resource resource)
      Description copied from interface: AliasCheck
      Check if an alias is allowed to be served. If any AliasCheck returns true then the alias will be allowed to be served, therefore any alias checker should take things like the getProtectedTargets() and Security Constraints into consideration before allowing a return a value of true.
      Specified by:
      checkAlias in interface AliasCheck
      Parameters:
      pathInContext - The path the aliased resource was created for.
      resource - The aliased resourced.
      Returns:
      True if the resource is OK to be served.
    • toString

      public String toString()
      Overrides:
      toString in class AbstractLifeCycle