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
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic enum
static interface
Listener for all threads entering context scope, including async IO callbacksclass
Nested classes/interfaces inherited from class org.eclipse.jetty.server.Handler.Abstract
Handler.Abstract.NonBlocking
Nested classes/interfaces inherited from class org.eclipse.jetty.util.component.AbstractLifeCycle
AbstractLifeCycle.AbstractLifeCycleListener, AbstractLifeCycle.StopException
Nested classes/interfaces inherited from interface org.eclipse.jetty.util.Attributes
Attributes.Layer, Attributes.Lazy, Attributes.Mapped, Attributes.Synthetic, Attributes.Wrapper
Nested classes/interfaces inherited from interface org.eclipse.jetty.util.component.Container
Container.InheritedListener, Container.Listener
Nested classes/interfaces inherited from interface org.eclipse.jetty.util.component.Dumpable
Dumpable.DumpableContainer
Nested classes/interfaces inherited from interface org.eclipse.jetty.server.Handler
Handler.Abstract, Handler.AbstractContainer, Handler.Collection, Handler.Container, Handler.Sequence, Handler.Singleton, Handler.Wrapper
Nested classes/interfaces inherited from interface org.eclipse.jetty.util.thread.Invocable
Invocable.Callable, Invocable.InvocationType, Invocable.ReadyTask, Invocable.Task
Nested classes/interfaces inherited from interface org.eclipse.jetty.util.component.LifeCycle
LifeCycle.Listener
Nested classes/interfaces inherited from interface org.eclipse.jetty.server.Request.Handler
Request.Handler.AbortException
-
Field Summary
Modifier and TypeFieldDescriptionstatic final String
The attribute name that is set as aRequest
attribute to indicate the request is a cross context dispatch.static final String
Fields inherited from class org.eclipse.jetty.util.component.AbstractLifeCycle
FAILED, STARTED, STARTING, STOPPED, STOPPING
Fields inherited from interface org.eclipse.jetty.util.Attributes
NULL
Fields inherited from interface org.eclipse.jetty.util.thread.Invocable
__nonBlocking, NOOP
-
Constructor Summary
ConstructorDescriptionContextHandler
(String contextPath) ContextHandler
(Handler handler) ContextHandler
(Handler handler, String contextPath) -
Method Summary
Modifier and TypeMethodDescriptionvoid
addAliasCheck
(AliasCheck check) Add an AliasCheck instance to possibly permit aliased resourcesboolean
addEventListener
(EventListener listener) Add a context event listeners.void
addVirtualHosts
(String... virtualHosts) Either set virtual hosts or add to an existing set of virtual hosts.boolean
checkAlias
(String pathInContext, Resource resource) Check if an alias is allowed to be served.boolean
checkVirtualHost
(Request request) protected void
void
clear the list of AliasChecksvoid
Clear all attribute namesprotected void
Create the temporary directory.void
destroy()
Destroys the managed Destroyable beans in the reverse order they were added.protected void
doStart()
Starts the managed lifecycle beans in the order they were added.protected void
doStop()
Stops the managed lifecycle beans in the reverse order they were added.void
dump
(Appendable out, String indent) Dump this object (and children) into an Appendable using the provided indent after any new lines.protected ClassLoader
enterScope
(Request contextRequest) protected void
exitScope
(Request request, Context lastContext, ClassLoader lastLoader) boolean
getAttribute
(String name) Get an attributeGet the immutable set of attribute names.protected static String
getBaseName
(Resource resource) protected String
Create a canonical name for a context temp directory.Make best effort to extract a file classpath from the context classloaderstatic ContextHandler
getContextHandler
(Request request) getCrossContextHandler
(String path) Ifcross context dispatch is supported
by this context then find a context bycontextPath
that also supports cross context dispatch.static Context
Get the current Context if any.static Context
getCurrentContext
(Server server) Get the current Context if any, or else server context if any.static ContextHandler
String[]
protected Resource
Get the virtual hosts for the context.boolean
Invoked to handle the passed HTTP request and response.protected boolean
handleByContextHandler
(String pathInContext, ContextRequest request, Response response, Callback callback) protected void
handleMovedPermanently
(Request request, Response response, Callback callback) protected void
handleUnavailable
(Request request, Response response, Callback callback) boolean
boolean
Get if this context support cross context dispatch, either as originator or target.boolean
isProtectedTarget
(String target) Check the target when a target within a context is determined.boolean
protected void
Generate a reasonable name for the temp directory because one has not been explicitly configured by the user withsetTempDirectory(File)
.protected ContextHandler.ScopedContext
protected void
notifyEnterScope
(Request request) protected void
notifyExitScope
(Request request) removeAttribute
(String name) Remove an attributeboolean
removeEventListener
(EventListener listener) Remove an event listener.void
removeVirtualHosts
(String... virtualHosts) Removes an array of virtual host entries, if this removes all entries the _vhosts will be set to nullvoid
setAliasChecks
(List<AliasCheck> checks) Set list of AliasCheck instances.void
setAllowNullPathInContext
(boolean allowNullPathInContext) Set true if /context is not redirected to /context/.setAttribute
(String name, Object attribute) Set an attributevoid
setAvailable
(boolean available) Set Available status.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.void
setBaseResourceAsPath
(Path path) Set the base resource to serve content from.void
Set the base resource to serve content from.void
setClassLoader
(ClassLoader contextLoader) void
setContextPath
(String contextPath) void
setCrossContextDispatchSupported
(boolean crossContextDispatchSupported) Set if this context support cross context dispatch, either as originator or target.void
setDisplayName
(String servletContextName) void
setErrorHandler
(Request.Handler errorHandler) void
setProtectedTargets
(String[] targets) void
Set theServer
to associate to thisHandler
.void
setTempDirectory
(File tempDirectory) Set the temporary directory returned byContextHandler.ScopedContext.getTempDirectory()
.void
setTempDirectoryPersistent
(boolean persist) Set if the temp directory for this context will be kept over a stop and start cycle.void
setVirtualHosts
(List<String> vhosts) Set the virtual hosts for the context.toString()
protected ContextRequest
wrapRequest
(Request request, Response response) protected ContextResponse
wrapResponse
(ContextRequest request, Response response) Methods inherited from class org.eclipse.jetty.server.Handler.Wrapper
getHandler, getInvocationType, setHandler
Methods inherited from class org.eclipse.jetty.server.Handler.AbstractContainer
findContainerOf, getDescendant, getDescendants, isDynamic, setDynamic
Methods inherited from class org.eclipse.jetty.server.Handler.Abstract
getServer
Methods inherited from class org.eclipse.jetty.util.component.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, updateBeans
Methods inherited from class org.eclipse.jetty.util.component.AbstractLifeCycle
getEventListeners, getState, getState, isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, setEventListeners, start, stop
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface org.eclipse.jetty.util.Attributes
asAttributeMap, equals, hashCode
Methods inherited from interface org.eclipse.jetty.util.component.Container
getCachedBeans, getEventListeners
Methods inherited from interface org.eclipse.jetty.util.component.Dumpable.DumpableContainer
isDumpable
Methods inherited from interface org.eclipse.jetty.server.Handler.Container
getContainer, getDescendant, getDescendants, getDescendants
Methods inherited from interface org.eclipse.jetty.server.Handler.Singleton
getHandlers, getTail, insertHandler, setHandler
Methods inherited from interface org.eclipse.jetty.util.component.LifeCycle
isFailed, isRunning, isStarted, isStarting, isStopped, isStopping, start, stop
-
Field Details
-
MANAGED_ATTRIBUTES
- See Also:
-
CROSS_CONTEXT_ATTRIBUTE
The attribute name that is set as aRequest
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
-
ContextHandler
-
ContextHandler
-
-
Method Details
-
getCurrentContext
Get the current Context if any.- Returns:
- The
Context
from aContextHandler
; or null if the currentThread
is not scoped to aContextHandler
.
-
getCurrentContext
Get the current Context if any, or else server context if any.- Parameters:
server
- The server.- Returns:
- The
Context
from aContextHandler
; orServer.getContext()
if the currentThread
is not scoped to aContextHandler
.
-
getCurrentContextHandler
-
getContextHandler
-
setServer
Description copied from interface:Handler
Set theServer
to associate to thisHandler
.- Specified by:
setServer
in interfaceHandler
- Overrides:
setServer
in classHandler.AbstractContainer
- Parameters:
server
- theServer
to associate to thisHandler
-
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 anyFile
set 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: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 interfaceDumpable
- Overrides:
dump
in 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:Attributes
Get an attribute- Specified by:
getAttribute
in interfaceAttributes
- Parameters:
name
- the attribute to get- Returns:
- the value of the attribute, or
null
if no such attribute exists
-
getAttributeNameSet
Description copied from interface:Attributes
Get the immutable set of attribute names.- Specified by:
getAttributeNameSet
in interfaceAttributes
- Returns:
- Set of attribute names, or an empty set if there are no attributes.
-
setAttribute
Description copied from interface:Attributes
Set an attribute- Specified by:
setAttribute
in 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:Attributes
Remove an attribute- Specified by:
removeAttribute
in interfaceAttributes
- Parameters:
name
- the attribute to remove- Returns:
- the value of the attribute if removed, else
null
-
getClassLoader
-
setClassLoader
-
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 supported
by this context then find a context bycontextPath
that also supports cross context dispatch. If more than one context is found, then those with disjointvirtual 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
Add a context event listeners.- Specified by:
addEventListener
in interfaceContainer
- Specified by:
addEventListener
in interfaceLifeCycle
- Overrides:
addEventListener
in classContainerLifeCycle
- Parameters:
listener
- the event listener to add- Returns:
- true if the listener was added
- See Also:
-
removeEventListener
Description copied from interface:Container
Remove an event listener.- Specified by:
removeEventListener
in interfaceContainer
- Specified by:
removeEventListener
in interfaceLifeCycle
- Overrides:
removeEventListener
in 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
-
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:ContainerLifeCycle
Starts the managed lifecycle beans in the order they were added.- Overrides:
doStart
in classHandler.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
Description copied from class:ContainerLifeCycle
Stops the managed lifecycle beans in the reverse order they were added.- Overrides:
doStop
in classHandler.Abstract
- Throws:
Exception
- If there was a problem stopping. Will cause a transition to FAILED state
-
cleanupAfterStop
- Throws:
Exception
-
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
- Parameters:
resource
- the resource whose filename minus suffix to extract- Returns:
- the filename of the resource without suffix
-
checkVirtualHost
-
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 interfaceDestroyable
- Overrides:
destroy
in classHandler.Abstract
-
handle
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 interfaceRequest.Handler
- Overrides:
handle
in 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
Resource
is 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
Resource
is 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:Attributes
Clear all attribute names- Specified by:
clearAttributes
in 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:AliasCheck
Check if an alias is allowed to be served. If anyAliasCheck
returns 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:
checkAlias
in 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:
toString
in classAbstractLifeCycle
-