org.mortbay.http

Class HttpContext

public class HttpContext extends Container implements LifeCycle, HttpHandler, EventProvider, Serializable

Context for a collection of HttpHandlers. HTTP Context provides an ordered container for HttpHandlers that share the same path prefix, filebase, resourcebase and/or classpath.

A HttpContext is analagous to a ServletContext in the Servlet API, except that it may contain other types of handler other than servlets.

A ClassLoader is created for the context and it uses Thread.currentThread().getContextClassLoader(); as it's parent loader. The class loader is initialized during start(), when a derived context calls initClassLoader() or on the first call to loadClass()

Note. that order is important when configuring a HttpContext. For example, if resource serving is enabled before servlets, then resources take priority.

Version: $Id: HttpContext.java,v 1.136 2006/02/21 09:47:43 gregwilkins Exp $

Author: Greg Wilkins (gregw)

See Also: HttpServer HttpHandler ServletHttpContext

Field Summary
static String__ErrorHandler
static String__fileClassPathAttr
File class path attribute.
Constructor Summary
HttpContext()
Constructor.
HttpContext(HttpServer httpServer, String contextPathSpec)
Constructor.
Method Summary
voidaddClassPath(String classPath)
Add the class path element to the context.
voidaddClassPaths(Resource lib)
Add elements to the class path for the context from the jar and zip files found in the specified resource.
voidaddHandler(int i, HttpHandler handler)
Add a handler.
voidaddHandler(HttpHandler handler)
Add a HttpHandler to the context.
voidaddPermission(Permission permission)
Add a permission to this context.
voidaddSecurityConstraint(String pathSpec, SecurityConstraint sc)
voidaddVirtualHost(String hostname)
Add a virtual host alias to this context.
voidaddWelcomeFile(String welcomeFile)
static StringcanonicalContextPathSpec(String contextPathSpec)
booleancheckSecurityConstraints(String pathInContext, HttpRequest request, HttpResponse response)
voidclearSecurityConstraints()
voiddestroy()
Destroy a context.
protected voiddoStart()
protected voiddoStop()
Stop the context.
ObjectenterContextScope(HttpRequest request, HttpResponse response)
Enter the context scope.
voidflushCache()
ObjectgetAttribute(String name)
EnumerationgetAttributeNames()
MapgetAttributes()
AuthenticatorgetAuthenticator()
ResourcegetBaseResource()
ClassLoadergetClassLoader()
Get the classloader.
StringgetClassPath()
Get the context classpath.
StringgetContextPath()
StringgetEncodingByMimeType(String type)
MapgetEncodingMap()
StringgetFileClassPath()
Get the file classpath of the context.
HttpHandlergetHandler(Class handlerClass)
Get a handler by class.
intgetHandlerIndex(HttpHandler handler)
Get handler index.
HttpHandler[]getHandlers()
Get all handlers.
String[]getHosts()
Get the hosts for the context.
HttpConnectiongetHttpConnection()
Get the ThreadLocal HttpConnection.
HttpContextgetHttpContext()
StringgetHttpContextName()
HttpServergetHttpServer()
StringgetInitParameter(String param)
Get context init parameter.
EnumerationgetInitParameterNames()
Get context init parameter.
intgetMaxCachedFileSize()
intgetMaxCacheSize()
StringgetMimeByExtension(String filename)
MapgetMimeMap()
StringgetName()
ClassLoadergetParentClassLoader()
PermissionCollectiongetPermissions()
Get the permissions to be used for this context.
UserRealmgetRealm()
StringgetRealmName()
RequestLoggetRequestLog()
intgetRequests()
intgetRequestsActive()
intgetRequestsActiveMax()
ResourcegetResource(String pathInContext)
StringgetResourceBase()
ResourceCache.ResourceMetaDatagetResourceMetaData(Resource resource)
intgetResponses1xx()
intgetResponses2xx()
intgetResponses3xx()
intgetResponses4xx()
intgetResponses5xx()
String[]getServerClasses()
Get system classes.
booleangetStatsOn()
longgetStatsOnMs()
booleangetStopGracefully()
String[]getSystemClasses()
Get system classes.
FilegetTempDirectory()
Get Context temporary directory.
String[]getVirtualHosts()
Get the virtual hosts for the context.
StringgetWelcomeFile(Resource resource)
String[]getWelcomeFiles()
voidhandle(HttpRequest request, HttpResponse response)
Handler request.
voidhandle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
Handler request.
protected voidinitClassLoader(boolean forceContextLoader)
Initialize the context classloader.
voidinitialize(HttpContext context)
booleanisClassLoaderJava2Compliant()
Get Java2 compliant classloading.
booleanisRedirectNullPath()
voidleaveContextScope(HttpRequest request, HttpResponse response, Object oldScope)
Leave the context scope.
ClassloadClass(String className)
voidlog(HttpRequest request, HttpResponse response, int length)
Log a request and response.
voidremoveAttribute(String name)
HttpHandlerremoveHandler(int i)
Remove a handler.
voidremoveHandler(HttpHandler handler)
Remove a handler.
voidremoveVirtualHost(String hostname)
remove a virtual host alias to this context.
voidremoveWelcomeFile(String welcomeFile)
static voidsendContextError(HttpResponse response, int code, String msg)
Send an error response.
voidsendError(HttpResponse response, int code, String msg)
Send an error response.
voidsetAttribute(String name, Object value)
Set a context attribute.
voidsetAttributes(Map attributes)
voidsetAuthenticator(Authenticator authenticator)
voidsetBaseResource(Resource base)
voidsetClassLoader(ClassLoader loader)
Set ClassLoader.
voidsetClassLoaderJava2Compliant(boolean compliant)
Set Java2 compliant classloading.
voidsetClassPath(String classPath)
Sets the class path for the context.
voidsetContextPath(String contextPathSpec)
voidsetEncodingMap(Map encodingMap)
voidsetHandlers(HttpHandler[] handlers)
voidsetHosts(String[] hosts)
Set the hosts for the context.
voidsetHttpContextName(String s)
voidsetInitParameter(String param, String value)
Set context init parameter.
voidsetMaxCachedFileSize(int maxCachedFileSize)
voidsetMaxCacheSize(int maxCacheSize)
voidsetMimeMap(Map mimeMap)
voidsetMimeMapping(String extension, String type)
voidsetParentClassLoader(ClassLoader loader)
Set Parent ClassLoader.
voidsetPermissions(PermissionCollection permissions)
Set the permissions to be used for this context.
voidsetRealm(UserRealm realm)
Set the realm.
voidsetRealmName(String realmName)
Set the realm name.
voidsetRedirectNullPath(boolean b)
Set null path redirection.
voidsetRequestLog(RequestLog log)
Set the request log.
voidsetResourceBase(String resourceBase)
voidsetServerClasses(String[] classes)
Set system classes.
voidsetStatsOn(boolean on)
True set statistics recording on for this context.
voidsetStopGracefully(boolean graceful)
voidsetSystemClasses(String[] classes)
Set system classes.
voidsetTempDirectory(File dir)
Set temporary directory for context.
voidsetTypeEncoding(String mimeType, String encoding)
voidsetVirtualHosts(String[] hosts)
Set the virtual hosts for the context.
voidsetWelcomeFiles(String[] welcomes)
protected voidstartHandlers()
Start the handlers.
voidstatsReset()
voidstop(boolean graceful)
Stop the context.
StringtoString()
StringtoString(boolean detail)

Field Detail

__ErrorHandler

public static final String __ErrorHandler

__fileClassPathAttr

public static final String __fileClassPathAttr
File class path attribute. If this name is set as a context init parameter, then the attribute name given will be used to set the file classpath for the context as a context attribute.

Constructor Detail

HttpContext

public HttpContext()
Constructor.

HttpContext

public HttpContext(HttpServer httpServer, String contextPathSpec)
Constructor.

Parameters: httpServer contextPathSpec

Method Detail

addClassPath

public void addClassPath(String classPath)
Add the class path element to the context. A class path is only required for a context if it uses classes that are not in the system class path.

Parameters: classPath a comma or ';' separated list of class resources. These may be jar files, directories or URLs to jars or directories.

addClassPaths

public void addClassPaths(Resource lib)
Add elements to the class path for the context from the jar and zip files found in the specified resource.

Parameters: lib the resource that contains the jar and/or zip files. append true if the classpath entries are to be appended to any existing classpath, or false if they replace the existing classpath.

See Also: setClassPath

addHandler

public void addHandler(int i, HttpHandler handler)
Add a handler.

Parameters: i The position in the handler list handler The handler.

addHandler

public void addHandler(HttpHandler handler)
Add a HttpHandler to the context.

Parameters: handler

addPermission

public void addPermission(Permission permission)
Add a permission to this context. The collection of permissions set here are used for all classes loaded by this context. This is simpler that creating a security policy file, as not all code sources may be statically known.

Parameters: permission

addSecurityConstraint

public void addSecurityConstraint(String pathSpec, SecurityConstraint sc)

addVirtualHost

public void addVirtualHost(String hostname)
Add a virtual host alias to this context.

Parameters: hostname A hostname. A null host name means any hostname is acceptable. Host names may String representation of IP addresses.

See Also: HttpContext

addWelcomeFile

public void addWelcomeFile(String welcomeFile)

canonicalContextPathSpec

public static String canonicalContextPathSpec(String contextPathSpec)

checkSecurityConstraints

public boolean checkSecurityConstraints(String pathInContext, HttpRequest request, HttpResponse response)

clearSecurityConstraints

public void clearSecurityConstraints()

destroy

public void destroy()
Destroy a context. Destroy a context and remove it from the HttpServer. The HttpContext must be stopped before it can be destroyed.

doStart

protected void doStart()

doStop

protected void doStop()
Stop the context.

enterContextScope

public Object enterContextScope(HttpRequest request, HttpResponse response)
Enter the context scope. This method is called (by handle or servlet dispatchers) to indicate that request handling is entering the scope of this context. The opaque scope object returned, should be passed to the leaveContextScope method.

flushCache

public void flushCache()

getAttribute

public Object getAttribute(String name)

Parameters: name attribute name

Returns: attribute value or null

getAttributeNames

public Enumeration getAttributeNames()

Returns: enumaration of names.

getAttributes

public Map getAttributes()

getAuthenticator

public Authenticator getAuthenticator()

getBaseResource

public Resource getBaseResource()

Returns:

getClassLoader

public ClassLoader getClassLoader()
Get the classloader. If no classloader has been set and the context has been loaded normally, then null is returned. If no classloader has been set and the context was loaded from a classloader, that loader is returned. If a classloader has been set and no classpath has been set then the set classloader is returned. If a classloader and a classpath has been set, then a new URLClassloader initialized on the classpath with the set loader as a partent is return.

Returns: Classloader or null.

getClassPath

public String getClassPath()
Get the context classpath. This method only returns the paths that have been set for this context and does not include any paths from a parent or the system classloader. Note that this may not be a legal javac classpath.

Returns: a comma or ';' separated list of class resources. These may be jar files, directories or URLs to jars or directories.

See Also: getFileClassPath

getContextPath

public String getContextPath()

Returns: The context prefix

getEncodingByMimeType

public String getEncodingByMimeType(String type)

Parameters: type

Returns:

getEncodingMap

public Map getEncodingMap()

Returns:

getFileClassPath

public String getFileClassPath()
Get the file classpath of the context. This method makes a best effort to return a complete file classpath for the context. It is obtained by walking the classloader hierarchy and looking for URLClassLoaders. The system property java.class.path is also checked for file elements not already found in the loader hierarchy.

Returns: Path of files and directories for loading classes.

Throws: IllegalStateException HttpContext.initClassLoader has not been called.

getHandler

public HttpHandler getHandler(Class handlerClass)
Get a handler by class.

Parameters: handlerClass

Returns: The first handler that is an instance of the handlerClass

getHandlerIndex

public int getHandlerIndex(HttpHandler handler)
Get handler index.

Parameters: handler instance

Returns: Index of handler in context or -1 if not found.

getHandlers

public HttpHandler[] getHandlers()
Get all handlers.

Returns: List of all HttpHandlers

getHosts

public String[] getHosts()
Get the hosts for the context.

getHttpConnection

public HttpConnection getHttpConnection()
Get the ThreadLocal HttpConnection. Get the HttpConnection for current thread, if any. This method is not static in order to control access.

Returns: HttpConnection for this thread.

getHttpContext

public HttpContext getHttpContext()

getHttpContextName

public String getHttpContextName()

getHttpServer

public HttpServer getHttpServer()

getInitParameter

public String getInitParameter(String param)
Get context init parameter.

Parameters: param param name

Returns: param value or null

getInitParameterNames

public Enumeration getInitParameterNames()
Get context init parameter.

Returns: Enumeration of names

getMaxCachedFileSize

public int getMaxCachedFileSize()

Returns:

getMaxCacheSize

public int getMaxCacheSize()

Returns:

getMimeByExtension

public String getMimeByExtension(String filename)

Parameters: filename

Returns:

getMimeMap

public Map getMimeMap()

Returns:

getName

public String getName()

getParentClassLoader

public ClassLoader getParentClassLoader()

getPermissions

public PermissionCollection getPermissions()
Get the permissions to be used for this context.

getRealm

public UserRealm getRealm()

getRealmName

public String getRealmName()

getRequestLog

public RequestLog getRequestLog()

getRequests

public int getRequests()

Returns: Get the number of requests handled by this context since last call of statsReset(). If setStatsOn(false) then this is undefined.

getRequestsActive

public int getRequestsActive()

Returns: Number of requests currently active. Undefined if setStatsOn(false).

getRequestsActiveMax

public int getRequestsActiveMax()

Returns: Maximum number of active requests since statsReset() called. Undefined if setStatsOn(false).

getResource

public Resource getResource(String pathInContext)

Parameters: pathInContext

Returns:

Throws: IOException

getResourceBase

public String getResourceBase()

Returns:

getResourceMetaData

public ResourceCache.ResourceMetaData getResourceMetaData(Resource resource)

Parameters: resource

Returns:

getResponses1xx

public int getResponses1xx()

Returns: Get the number of responses with a 2xx status returned by this context since last call of statsReset(). Undefined if if setStatsOn(false).

getResponses2xx

public int getResponses2xx()

Returns: Get the number of responses with a 100 status returned by this context since last call of statsReset(). Undefined if if setStatsOn(false).

getResponses3xx

public int getResponses3xx()

Returns: Get the number of responses with a 3xx status returned by this context since last call of statsReset(). Undefined if if setStatsOn(false).

getResponses4xx

public int getResponses4xx()

Returns: Get the number of responses with a 4xx status returned by this context since last call of statsReset(). Undefined if if setStatsOn(false).

getResponses5xx

public int getResponses5xx()

Returns: Get the number of responses with a 5xx status returned by this context since last call of statsReset(). Undefined if if setStatsOn(false).

getServerClasses

public String[] getServerClasses()
Get system classes. System classes cannot be seen by context classloaders.

Returns: array of classname Strings. Names ending with '.' are treated as package names. Names starting with '-' are treated as negative matches and must be listed before any enclosing packages. Null if not set.

getStatsOn

public boolean getStatsOn()

getStatsOnMs

public long getStatsOnMs()

getStopGracefully

public boolean getStopGracefully()

getSystemClasses

public String[] getSystemClasses()
Get system classes. System classes cannot be overriden by context classloaders.

Returns: array of classname Strings. Names ending with '.' are treated as package names. Names starting with '-' are treated as negative matches and must be listed before any enclosing packages. Null if not set.

getTempDirectory

public File getTempDirectory()
Get Context temporary directory. A tempory directory is generated if it has not been set. The "javax.servlet.context.tempdir" attribute is consulted and if not set, the host, port and context are used to generate a directory within the JVMs temporary directory.

Returns: Temporary directory as a File.

getVirtualHosts

public 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: Array of virtual hosts that this context responds to. A null host name or empty array means any hostname is acceptable. Host names may be String representation of IP addresses.

getWelcomeFile

public String getWelcomeFile(Resource resource)

getWelcomeFiles

public String[] getWelcomeFiles()

handle

public void handle(HttpRequest request, HttpResponse response)
Handler request. Determine the path within the context and then call handle(pathInContext,request,response).

Parameters: request response

Returns: True if the request has been handled.

Throws: HttpException IOException

handle

public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
Handler request. Call each HttpHandler until request is handled.

Parameters: pathInContext Path in context pathParams Path parameters such as encoded Session ID request response

Returns: True if the request has been handled.

Throws: HttpException IOException

initClassLoader

protected void initClassLoader(boolean forceContextLoader)
Initialize the context classloader. Initialize the context classloader with the current parameters. Any attempts to change the classpath after this call will result in a IllegalStateException

Parameters: forceContextLoader If true, a ContextLoader is always if no loader has been set.

initialize

public void initialize(HttpContext context)

isClassLoaderJava2Compliant

public boolean isClassLoaderJava2Compliant()
Get Java2 compliant classloading.

Returns: If true, the class loader will conform to the java 2 specification and delegate all loads to the parent classloader. If false, the context classloader only delegate loads for system classes or classes that it can't find itself.

isRedirectNullPath

public boolean isRedirectNullPath()

Returns: True if a /context request is redirected to /context/ if there is not path in the context.

leaveContextScope

public void leaveContextScope(HttpRequest request, HttpResponse response, Object oldScope)
Leave the context scope. This method is called (by handle or servlet dispatchers) to indicate that request handling is leaveing the scope of this context. The opaque scope object returned by enterContextScope should be passed in.

loadClass

public Class loadClass(String className)

log

public void log(HttpRequest request, HttpResponse response, int length)
Log a request and response. Statistics are also collected by this method.

Parameters: request response

removeAttribute

public void removeAttribute(String name)

Parameters: name attribute name

removeHandler

public HttpHandler removeHandler(int i)
Remove a handler. The handler must be stopped before being removed.

Parameters: i index of handler

removeHandler

public void removeHandler(HttpHandler handler)
Remove a handler. The handler must be stopped before being removed.

removeVirtualHost

public void removeVirtualHost(String hostname)
remove a virtual host alias to this context.

Parameters: hostname A hostname. A null host name means any hostname is acceptable. Host names may String representation of IP addresses.

See Also: HttpContext

removeWelcomeFile

public void removeWelcomeFile(String welcomeFile)

sendContextError

public static void sendContextError(HttpResponse response, int code, String msg)
Send an error response. This method obtains the responses context and call sendError for context specific error handling.

Parameters: response the response to send code The error code msg The message for the error or null for the default

Throws: IOException Problem sending response.

sendError

public void sendError(HttpResponse response, int code, String msg)
Send an error response. This method may be specialized to provide alternative error handling for errors generated by the container. The default implemenation calls HttpResponse.sendError

Parameters: response the response to send code The error code msg The message for the error or null for the default

Throws: IOException Problem sending response.

setAttribute

public void setAttribute(String name, Object value)
Set a context attribute.

Parameters: name attribute name value attribute value

setAttributes

public void setAttributes(Map attributes)

setAuthenticator

public void setAuthenticator(Authenticator authenticator)

setBaseResource

public void setBaseResource(Resource base)

Parameters: base

setClassLoader

public void setClassLoader(ClassLoader loader)
Set ClassLoader.

Parameters: loader The loader to be used by this context.

setClassLoaderJava2Compliant

public void setClassLoaderJava2Compliant(boolean compliant)
Set Java2 compliant classloading.

Parameters: compliant If true, the class loader will conform to the java 2 specification and delegate all loads to the parent classloader. If false, the context classloader only delegate loads for system classes or classes that it can't find itself.

setClassPath

public void setClassPath(String classPath)
Sets the class path for the context. A class path is only required for a context if it uses classes that are not in the system class path.

Parameters: classPath a comma or ';' separated list of class resources. These may be jar files, directories or URLs to jars or directories.

setContextPath

public void setContextPath(String contextPathSpec)

setEncodingMap

public void setEncodingMap(Map encodingMap)

Parameters: encodingMap

setHandlers

public void setHandlers(HttpHandler[] handlers)

setHosts

public void setHosts(String[] hosts)
Set the hosts for the context. Set the real hosts that this context will accept requests for. If not null or empty, then only requests from HttpListeners for hosts in this array are accepted by this context. Unlike virutal hosts, this value is not used by HttpServer for matching a request to a context.

setHttpContextName

public void setHttpContextName(String s)

setInitParameter

public void setInitParameter(String param, String value)
Set context init parameter. Init Parameters differ from attributes as they can only have string values, servlets cannot set them and they do not have a package scoped name space.

Parameters: param param name value param value or null

setMaxCachedFileSize

public void setMaxCachedFileSize(int maxCachedFileSize)

Parameters: maxCachedFileSize

setMaxCacheSize

public void setMaxCacheSize(int maxCacheSize)

Parameters: maxCacheSize

setMimeMap

public void setMimeMap(Map mimeMap)

Parameters: mimeMap

setMimeMapping

public void setMimeMapping(String extension, String type)

Parameters: extension type

setParentClassLoader

public void setParentClassLoader(ClassLoader loader)
Set Parent ClassLoader. By default the parent loader is the thread context classloader of the thread that calls initClassLoader. If setClassLoader is called, then the parent is ignored.

Parameters: loader The class loader to use for the parent loader of the context classloader.

setPermissions

public void setPermissions(PermissionCollection permissions)
Set the permissions to be used for this context. The collection of permissions set here are used for all classes loaded by this context. This is simpler that creating a security policy file, as not all code sources may be statically known.

Parameters: permissions

setRealm

public void setRealm(UserRealm realm)
Set the realm.

setRealmName

public void setRealmName(String realmName)
Set the realm name.

Parameters: realmName The name to use to retrieve the actual realm from the HttpServer

setRedirectNullPath

public void setRedirectNullPath(boolean b)
Set null path redirection.

Parameters: b if true a /context request will be redirected to /context/ if there is not path in the context.

setRequestLog

public void setRequestLog(RequestLog log)
Set the request log.

Parameters: log RequestLog to use.

setResourceBase

public void setResourceBase(String resourceBase)

Parameters: resourceBase

setServerClasses

public void setServerClasses(String[] classes)
Set system classes. Servers classes cannot be seen by context classloaders.

Parameters: classes array of classname Strings. Names ending with '.' are treated as package names. Names starting with '-' are treated as negative matches and must be listed before any enclosing packages.

setStatsOn

public void setStatsOn(boolean on)
True set statistics recording on for this context.

Parameters: on If true, statistics will be recorded for this context.

setStopGracefully

public void setStopGracefully(boolean graceful)

setSystemClasses

public void setSystemClasses(String[] classes)
Set system classes. System classes cannot be overriden by context classloaders.

Parameters: classes array of classname Strings. Names ending with '.' are treated as package names. Names starting with '-' are treated as negative matches and must be listed before any enclosing packages.

setTempDirectory

public void setTempDirectory(File dir)
Set temporary directory for context. The javax.servlet.context.tempdir attribute is also set.

Parameters: dir Writable temporary directory.

setTypeEncoding

public void setTypeEncoding(String mimeType, String encoding)

Parameters: mimeType encoding

setVirtualHosts

public void setVirtualHosts(String[] hosts)
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: hosts Array of virtual hosts that this context responds to. A null host name or null/empty array means any hostname is acceptable. Host names may String representation of IP addresses.

setWelcomeFiles

public void setWelcomeFiles(String[] welcomes)

startHandlers

protected void startHandlers()
Start the handlers. This is called by start after the classloader has been initialized and set as the thread context loader. It may be specialized to provide custom handling before any handlers are started.

Throws: Exception

statsReset

public void statsReset()

stop

public void stop(boolean graceful)
Stop the context.

Parameters: graceful If true and statistics are on, then this method will wait for requestsActive to go to zero before calling stop()

toString

public String toString()

toString

public String toString(boolean detail)
Copyright © 2004 Mortbay Consulting Pty. Ltd. All Rights Reserved.