Class ContextHandler
- All Implemented Interfaces:
AliasCheck, Handler, Handler.Container, Handler.Singleton, Request.Handler, Attributes, Container, Destroyable, Dumpable, Dumpable.DumpableContainer, LifeCycle, Invocable
- Direct Known Subclasses:
ContextHandler.CoreContextHandler, ContextHandler.CoreContextHandler, HttpSpiContextHandler, MovedContextHandler, ResourceHandler.ResourceContext, ServletContextHandler
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic enumstatic interfaceListener for all threads entering context scope, including async IO callbacksclassNested classes/interfaces inherited from class Handler.Abstract
Handler.Abstract.NonBlockingNested classes/interfaces inherited from class AbstractLifeCycle
AbstractLifeCycle.AbstractLifeCycleListener, AbstractLifeCycle.StopExceptionNested classes/interfaces inherited from interface Attributes
Attributes.Layer, Attributes.Lazy, Attributes.Mapped, Attributes.Synthetic, Attributes.WrapperNested classes/interfaces inherited from interface Container
Container.InheritedListener, Container.ListenerNested classes/interfaces inherited from interface Dumpable
Dumpable.DumpableContainerNested classes/interfaces inherited from interface Handler
Handler.Abstract, Handler.AbstractContainer, Handler.Collection, Handler.Container, Handler.Sequence, Handler.Singleton, Handler.WrapperNested classes/interfaces inherited from interface Invocable
Invocable.Callable, Invocable.InvocationType, Invocable.ReadyTask, Invocable.TaskNested classes/interfaces inherited from interface LifeCycle
LifeCycle.ListenerNested classes/interfaces inherited from interface Request.Handler
Request.Handler.AbortException -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe attribute name that is set as aRequestattribute to indicate the request is a cross context dispatch.static final StringFields inherited from interface Attributes
NULLFields inherited from interface Invocable
__nonBlocking, NOOP -
Constructor Summary
ConstructorsConstructorDescriptionContextHandler(String contextPath) ContextHandler(Handler handler) ContextHandler(Handler handler, String contextPath) -
Method Summary
Modifier and TypeMethodDescriptionvoidaddAliasCheck(AliasCheck check) Add an AliasCheck instance to possibly permit aliased resourcesbooleanaddEventListener(EventListener listener) Add a context event listeners.voidaddVirtualHosts(String... virtualHosts) Either set virtual hosts or add to an existing set of virtual hosts.booleancheckAlias(String pathInContext, Resource resource) Check if an alias is allowed to be served.booleancheckVirtualHost(Request request) protected voidvoidclear the list of AliasChecksvoidClear all attribute namesprotected voidCreate the temporary directory.voiddestroy()Destroys the managed Destroyable beans in the reverse order they were added.protected voiddoStart()Starts the managed lifecycle beans in the order they were added.protected voiddoStop()Stops the managed lifecycle beans in the reverse order they were added.voiddump(Appendable out, String indent) Dump this object (and children) into an Appendable using the provided indent after any new lines.protected ClassLoaderenterScope(Request contextRequest) protected voidexitScope(Request contextRequest, Context lastContext, ClassLoader lastLoader) Exits the scope of theContext.booleangetAttribute(String name) Get an attributeGet the immutable set of attribute names.protected static StringgetBaseName(Resource resource) protected StringCreate a canonical name for a context temp directory.Make best effort to extract a file classpath from the context classloaderstatic ContextHandlergetContextHandler(Request request) getCrossContextHandler(String path) Ifcross context dispatch is supportedby this context then find a context bycontextPaththat also supports cross context dispatch.static ContextGet the current Context if any.static ContextgetCurrentContext(Server server) Get the current Context if any, or else server context if any.static ContextHandlerString[]protected ResourceGet the virtual hosts for the context.booleanInvoked to handle the passed HTTP request and response.protected booleanhandleByContextHandler(String pathInContext, ContextRequest request, Response response, Callback callback) protected voidhandleMovedPermanently(Request request, Response response, Callback callback) protected voidhandleUnavailable(Request request, Response response, Callback callback) booleanbooleanGet if this context support cross context dispatch, either as originator or target.booleanisProtectedTarget(String target) Check the target when a target within a context is determined.booleanprotected voidGenerate a reasonable name for the temp directory because one has not been explicitly configured by the user withsetTempDirectory(File).protected ContextHandler.ScopedContextprotected voidnotifyEnterScope(Request request) protected voidnotifyExitScope(Request request) removeAttribute(String name) Remove an attributebooleanremoveEventListener(EventListener listener) Remove an event listener.voidremoveVirtualHosts(String... virtualHosts) Removes an array of virtual host entries, if this removes all entries the _vhosts will be set to nullvoidsetAliasChecks(List<AliasCheck> checks) Set list of AliasCheck instances.voidsetAllowNullPathInContext(boolean allowNullPathInContext) Set true if /context is not redirected to /context/.setAttribute(String name, Object attribute) Set an attributevoidsetAvailable(boolean available) Set Available status.voidsetBaseResource(Resource resourceBase) Set the base resource to serve content from for this context, which must exist and be readable when the context is started.voidsetBaseResourceAsPath(Path path) Set the base resource to serve content from.voidSet the base resource to serve content from.voidsetClassLoader(ClassLoader contextLoader) TheClassLoaderto set as thethread's context classloaderwhen the thread executing this handler enters the scope of this context.voidsetContextPath(String contextPath) voidsetCrossContextDispatchSupported(boolean crossContextDispatchSupported) Set if this context support cross context dispatch, either as originator or target.voidsetDisplayName(String servletContextName) voidsetErrorHandler(Request.Handler errorHandler) voidsetProtectedTargets(String[] targets) voidSet theServerto associate to thisHandler.voidsetTempDirectory(File tempDirectory) Set the temporary directory returned byContextHandler.ScopedContext.getTempDirectory().voidsetTempDirectoryPersistent(boolean persist) Set if the temp directory for this context will be kept over a stop and start cycle.voidsetVirtualHosts(List<String> vhosts) Set the virtual hosts for the context.toString()protected ContextRequestwrapRequest(Request request, Response response) protected ContextResponsewrapResponse(ContextRequest request, Response response) Methods inherited from class Handler.Wrapper
getHandler, getInvocationType, setHandlerMethods inherited from class Handler.AbstractContainer
findContainerOf, getDescendant, getDescendants, isDynamic, setDynamicMethods inherited from class Handler.Abstract
getServerMethods inherited from class ContainerLifeCycle
addBean, addBean, addManaged, contains, dump, dump, dumpObjects, dumpStdErr, getBean, getBeans, getBeans, getContainedBeans, getContainedBeans, installBean, installBean, isAuto, isManaged, isUnmanaged, manage, removeBean, removeBeans, setBeans, start, stop, unmanage, updateBean, updateBean, updateBeans, updateBeansMethods inherited from class AbstractLifeCycle
getEventListeners, getState, getState, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, setEventListeners, start, stopMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface Attributes
asAttributeMap, equals, hashCodeMethods inherited from interface Container
getCachedBeans, getEventListenersMethods inherited from interface Dumpable.DumpableContainer
isDumpableMethods inherited from interface Handler.Container
getContainer, getDescendant, getDescendants, getDescendantsMethods inherited from interface Handler.Singleton
getHandlers, getTail, insertHandler, setHandlerMethods inherited from interface LifeCycle
isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, start, stop
-
Field Details
-
MANAGED_ATTRIBUTES
- See Also:
-
CROSS_CONTEXT_ATTRIBUTE
-
-
Constructor Details
-
ContextHandler
public ContextHandler() -
ContextHandler
-
ContextHandler
-
ContextHandler
-
-
Method Details
-
getCurrentContext
Get the current Context if any.- Returns:
- The
Contextfrom aContextHandler; or null if the currentThreadis not scoped to aContextHandler.
-
getCurrentContext
Get the current Context if any, or else server context if any.- Parameters:
server- The server.- Returns:
- The
Contextfrom aContextHandler; orServer.getContext()if the currentThreadis not scoped to aContextHandler.
-
getCurrentContextHandler
-
getContextHandler
-
setServer
-
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
Set the temporary directory returned by
ContextHandler.ScopedContext.getTempDirectory(). If not set here, then theServer.getTempDirectory()is returned byContextHandler.ScopedContext.getTempDirectory().If
isTempDirectoryPersistent()is true, the directory set here is used directly but may be created if it does not exist. IfisTempDirectoryPersistent()is false, then anyFileset here will be deleted and recreated as a directory duringAbstractLifeCycle.start()and will be deleted duringAbstractLifeCycle.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
- Returns:
- A mutable MimeTypes that wraps the
Server.getMimeTypes()oncesetServer(Server)has been called. - See Also:
-
dump
Description copied from interface:DumpableDump 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:
dumpin interfaceDumpable- Overrides:
dumpin classContainerLifeCycle- Parameters:
out- The appendable to dump toindent- The indent to apply after any new lines.- Throws:
IOException- if unable to write to Appendable
-
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
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 theConnector.getName()for the request also matches. If an entry is just"@connectorname"it will match any host if that connector was used.
-
addVirtualHosts
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 theConnector.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
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 theConnector.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 theConnector.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
Description copied from interface:AttributesGet an attribute- Specified by:
getAttributein interfaceAttributes- Parameters:
name- the attribute to get- Returns:
- the value of the attribute, or
nullif no such attribute exists
-
getAttributeNameSet
Description copied from interface:AttributesGet the immutable set of attribute names.- Specified by:
getAttributeNameSetin interfaceAttributes- Returns:
- Set of attribute names, or an empty set if there are no attributes.
-
setAttribute
Description copied from interface:AttributesSet an attribute- Specified by:
setAttributein interfaceAttributes- Parameters:
name- the attribute to setattribute- 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
Description copied from interface:AttributesRemove an attribute- Specified by:
removeAttributein interfaceAttributes- Parameters:
name- the attribute to remove- Returns:
- the value of the attribute if removed, else
null
-
getClassLoader
-
setClassLoader
TheClassLoaderto set as thethread's context classloaderwhen the thread executing this handler enters the scope of this context.- Parameters:
contextLoader- theClassLoaderornullto avoid changing the thread's context classloader.
-
getClassPath
Make best effort to extract a file classpath from the context classloader- Returns:
- Returns the classLoader.
-
getContextPath
- Returns:
- Returns the contextPath.
-
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
Ifcross context dispatch is supportedby this context then find a context bycontextPaththat also supports cross context dispatch. If more than one context is found, then those with disjointvirtual hostsare excluded and the first remaining context returned.- Parameters:
path- The path that will be served by the context- Returns:
- The found
ContextHandleror null.
-
addEventListener
Add a context event listeners.- Specified by:
addEventListenerin interfaceContainer- Specified by:
addEventListenerin interfaceLifeCycle- Overrides:
addEventListenerin classContainerLifeCycle- Parameters:
listener- the event listener to add- Returns:
- true if the listener was added
- See Also:
-
removeEventListener
Description copied from interface:ContainerRemove an event listener.- Specified by:
removeEventListenerin interfaceContainer- Specified by:
removeEventListenerin interfaceLifeCycle- Overrides:
removeEventListenerin classContainerLifeCycle- Parameters:
listener- the listener to remove- Returns:
- true if the listener was removed
- See Also:
-
enterScope
-
notifyEnterScope
- Parameters:
request- A request that is applicable to the scope, or null
-
exitScope
Exits the scope of the
Context.- Parameters:
contextRequest- the context'sRequestlastContext- the previous context to restore as the current one.lastLoader- the previousthread's context classloaderto restore
-
notifyExitScope
- 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
Description copied from class:ContainerLifeCycleStarts the managed lifecycle beans in the order they were added.- Overrides:
doStartin classHandler.Abstract- Throws:
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
Description copied from class:ContainerLifeCycleStops the managed lifecycle beans in the reverse order they were added.- Overrides:
doStopin classHandler.Abstract- Throws:
Exception- If there was a problem stopping. Will cause a transition to FAILED state
-
cleanupAfterStop
-
makeTempDirectory
Generate a reasonable name for the temp directory because one has not been explicitly configured by the user withsetTempDirectory(File). The directory may also be created, if it is not persistent. If it is persistent it will be created as necessary bycreateTempDirectory()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
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
- Returns:
- the baseResource for the context to use in the temp dir name
-
getBaseName
-
checkVirtualHost
-
destroy
public void destroy()Description copied from class:ContainerLifeCycleDestroys the managed Destroyable beans in the reverse order they were added.- Specified by:
destroyin interfaceDestroyable- Overrides:
destroyin classHandler.Abstract
-
handle
Description copied from interface:Request.HandlerInvoked 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:
handlein interfaceRequest.Handler- Overrides:
handlein classHandler.Wrapper- Parameters:
request- the HTTP request to handleresponse- the HTTP response to handlecallback- 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
-
setContextPath
- Parameters:
contextPath- The _contextPath to set.
-
setDisplayName
- 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
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
Set the base resource to serve content from.
Note: the
Resourceis created fromResourceFactory.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
Set the base resource to serve content from.
Note: the
Resourceis created fromResourceFactory.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
- Parameters:
errorHandler- The error handler to set.
-
wrapRequest
-
wrapResponse
-
clearAttributes
public void clearAttributes()Description copied from interface:AttributesClear all attribute names- Specified by:
clearAttributesin interfaceAttributes
-
isProtectedTarget
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
- Parameters:
targets- Array of URL prefix. Each prefix is in the form /path and will match either /path exactly or /path/anything
-
getProtectedTargets
-
addAliasCheck
Add an AliasCheck instance to possibly permit aliased resources- Parameters:
check- The alias checker
-
getAliasChecks
- Returns:
- Immutable list of Alias checks
-
setAliasChecks
Set list of AliasCheck instances.- Parameters:
checks- list of AliasCheck instances
-
clearAliasChecks
public void clearAliasChecks()clear the list of AliasChecks -
checkAlias
Description copied from interface:AliasCheckCheck if an alias is allowed to be served. If anyAliasCheckreturns true then the alias will be allowed to be served, therefore any alias checker should take things like thegetProtectedTargets()and Security Constraints into consideration before allowing a return a value of true.- Specified by:
checkAliasin interfaceAliasCheck- 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
- Overrides:
toStringin classAbstractLifeCycle
-