org.apache.tomcat.core
Class BaseInterceptor

java.lang.Object
  extended byorg.apache.tomcat.core.BaseInterceptor
Direct Known Subclasses:
AccessInterceptor, AccessLogInterceptor, AccountingInterceptor, AutoDeploy, AutoWebApp, BaseJkConfig, ContextXmlReader, CredentialsInterceptor, DecodeInterceptor, ErrorHandler, HookSetter, InvokerInterceptor, Jdk12Interceptor, JNIConnectionHandler, JservConfig, JspInterceptor, LoaderInterceptor11, LoadOnStartupInterceptor, LogEvents, LogSetter, PathSetter, PolicyLoader, PoolTcpConnector, ProfileLoader, RealmBase, ReloadInterceptor, ServerXmlReader, Servlet22Interceptor, SessionExpirer, SessionId, SessionIdGenerator, SimpleMapper1, SimpleSessionStore, StaticInterceptor, TagPoolManagerInterceptor, TrustedLoader, WebXmlReader, WorkDirSetup

public class BaseInterceptor
extends java.lang.Object

Implement "Chain of Responsiblity" pattern ( == hooks ). You can extend this class and implement a number of hooks. The interceptor is added to a Container ( that represents a group of URLs where the interceptor will operate ) and the methods that are re-defined in the subclass are detected ( using introspection ) and used to select the chains where the intercepptor is interested to participate. It is possible to define new chains by adding a new method to this class. The caller ( "chain user" ) will determine the behavior in case of error and "call all" or "call until [condition]" rules. Interceptors are the main extension mechanism for tomcat. They have full access and control all aspects in tomcat operation.

Sandboxing. Tomcat may be run in a java2 sandboxed environment. All request processing callbacks can be initiated as a result of user ( untrusted ) code ( for example - a servlet creating a new session ). The module is responsible for using doPriviledged() blocks for all actions that require special priviledges. "Base" modules ( included in the distribution ) that perform essential functionality must also ensure JDK1.1 compatibility. The priviledged block must be as small as possible and do only a clearly defined action.


Field Summary
protected  ContextManager cm
           
protected  Container ct
           
protected  Context ctx
           
protected  int debug
           
static int DECLINED
           
protected  Log loghelper
           
static int OK
           
 
Constructor Summary
BaseInterceptor()
           
 
Method Summary
 void addContainer(Container container)
          Notify that certain properties are defined for a URL pattern.
 void addContext(ContextManager cm, Context ctx)
          Called when a context is added to a CM.
 void addHandler(Handler h)
          Notification of a new content handler added to a context
 void addInterceptor(ContextManager cm, Context ctx, BaseInterceptor i)
          Hook called when a new interceptor is added.
 void addSecurityConstraint(Context ctx, java.lang.String path, Container ct)
           
 int afterBody(Request request, Response response)
          Called after the output stream is closed ( either by servlet or automatically at end of service ).
 int authenticate(Request request, Response response)
          This callback is used to extract and verify the user identity and credentials.
 int authorize(Request request, Response response, java.lang.String[] reqRoles)
          Will check if the current ( authenticated ) user is authorized to access a resource, by checking if it have one of the required roles.
 int beforeBody(Request rrequest, Response response)
          Called before the first body write, and before sending the headers.
 int beforeCommit(Request request, Response response)
          Called before the output buffer is commited.
 void contextInit(Context ctx)
          Notify when a context is initialized.
 int contextMap(Request rrequest)
          Will detect the context path for a request.
 void contextShutdown(Context ctx)
          Called when a context is stoped, before removeContext.
 void contextState(Context ctx, int newState)
          Notify that the context state changed
 void copyContext(Request req, Context oldC, Context newC)
          Reload notification - called whenever a full reload is done.
 void engineInit(ContextManager cm)
          Initialize the module.
 void engineShutdown(ContextManager cm)
          Shut down the module.
 void engineStart(ContextManager cm)
          Notify that the server is ready and able to process requests
 void engineState(ContextManager cm, int state)
          Notifies the module that the server changed it's state.
 void engineStop(ContextManager cm)
          Notify that the server is disabled and shoulnd't process more requests
 ServerSession findSession(Request req, java.lang.String reqSessionId, boolean create)
          The hook for session managers.
 Context getContext()
           
 ContextManager getContextManager()
           
 int getDebug()
           
 java.lang.Object getInfo(Context ctx, Request request, int id, java.lang.String key)
          Hook for lazy evaluation of request info.
 Log getLog()
           
 java.lang.Object getNote(int pos)
           
 java.lang.Object getNote(java.lang.String name)
           
 int handleError(Request request, Response response, java.lang.Throwable t)
          This callback is called whenever an exception happen.
 void log(java.lang.String s)
           
 void log(java.lang.String s, int level)
           
 void log(java.lang.String s, java.lang.Throwable t)
           
 void log(java.lang.String s, java.lang.Throwable t, int level)
           
 int postInitCheck(Request req, Handler sw)
           
 int postReadRequest(Request request)
          Called immediately after the request has been received, before any mapping.
 int postRequest(Request request, Response response)
          Experimental hook: called after the request is finished, before returning to the caller.
 int postService(Request request, Response response)
          Called after service method ends.
 void postServletDestroy(Context ctx, Handler sw)
           
 void postServletInit(Context ctx, Handler sw)
           
 int preInitCheck(Request req, Handler sw)
          Setup before calling init.
 int preService(Request request, Response response)
          Called before service method is invoked.
 void preServletDestroy(Context ctx, Handler sw)
          Servlet Destroy notification
 void preServletInit(Context ctx, Handler sw)
          Servlet Init notification
 int registerHooks(Hooks h, ContextManager cm, Context ctx)
          Special method for self-registered hooks, intended to support a mechanism similar with Apache2.0 and further extensibility without interface changes.
 void reload(Request req, Context ctx)
          Reload notification - called whenever a reload is done.
 void removeContainer(Container container)
          A rule was removed, update the internal strucures.
 void removeContext(ContextManager cm, Context ctx)
          Called when a context is removed from a CM.
 void removeHandler(Handler h)
          Notification of a content handler removal
 void removeInterceptor(ContextManager cm, Context ctx, BaseInterceptor i)
          Hook called when interceptors are removed.
 int requestMap(Request request)
          Handle mappings inside a context.
 int sessionState(Request req, ServerSession sess, int newState)
          Hook for session state changes.
 void setContext(Context ctx)
          Called for context-level interceptors
 void setContextManager(ContextManager cm)
           
 void setDebug(int d)
           
 int setInfo(Context ctx, Request request, int id, java.lang.String key, java.lang.Object obj)
           
 void setNote(int pos, java.lang.Object value)
           
 void setNote(java.lang.String name, java.lang.Object value)
           
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DECLINED

public static final int DECLINED
See Also:
Constant Field Values

OK

public static final int OK
See Also:
Constant Field Values

cm

protected ContextManager cm

ct

protected Container ct

ctx

protected Context ctx

debug

protected int debug

loghelper

protected Log loghelper
Constructor Detail

BaseInterceptor

public BaseInterceptor()
Method Detail

postReadRequest

public int postReadRequest(Request request)
Called immediately after the request has been received, before any mapping. This allows modules to alter the request before it is mapped, and implement decoding/encoding, detect charsets, etc. The request URI and (some) headers will be available. Similar with Apache's post_read_request


requestMap

public int requestMap(Request request)
Handle mappings inside a context. You are required to respect the mappings in web.xml.


contextMap

public int contextMap(Request rrequest)
Will detect the context path for a request. It need to set: context, contextPath, lookupPath A possible use for this would be a "user-home" interceptor that will implement ~costin servlets ( add and map them at run time).


authenticate

public int authenticate(Request request,
                        Response response)
This callback is used to extract and verify the user identity and credentials. It will set the RemoteUser field if it can authenticate. The auth event is generated by a user asking for the remote user field of by tomcat if a request requires authenticated id.


authorize

public int authorize(Request request,
                     Response response,
                     java.lang.String[] reqRoles)
Will check if the current ( authenticated ) user is authorized to access a resource, by checking if it have one of the required roles. This is used by tomcat to delegate the authorization to modules. The authorize is called by isUserInRole() and by ContextManager if the request have security constraints.


preService

public int preService(Request request,
                      Response response)
Called before service method is invoked.


beforeBody

public int beforeBody(Request rrequest,
                      Response response)
Called before the first body write, and before sending the headers. The interceptor have a chance to change the output headers. Before body allows you do do various actions before the first byte of the response is sent. After all those callbacks are called tomcat may send the status and headers


findSession

public ServerSession findSession(Request req,
                                 java.lang.String reqSessionId,
                                 boolean create)
The hook for session managers. It'll be called to find or create a ServerSession object associated with a request. There are 2 components of tomcat's session management - finding the session ID, typically done during mapping ( either in tomcat or by a load balancer or web server ) and the actual storage manager ( including expiration, persistence, events, etc ). This hook allow to plug different session managers. The mapping hooks ( combined with native code in the server/load balancer ) are used to determine the session id and do low-level operations. The hook will be called from the mapping hook whenever a session is detected ( create==false ) - the manager can update the timers. It will also be called if the user requests a new session, and none is created. XXX should we return a status code and let the manager call req.setSession() ? Returning ServerSession seems more flexible, ( but different from the rest of the hooks )

Parameters:
reqSessionId - if null the manager will generate the id

sessionState

public int sessionState(Request req,
                        ServerSession sess,
                        int newState)
Hook for session state changes. Will be called every time a session change it's state. A session module will announce all changes - like STATE_NEW when the session is created, STATE_EXPIRED when the session is expired, STATE_INVALID when the session is invalidated.


beforeCommit

public int beforeCommit(Request request,
                        Response response)
Called before the output buffer is commited.


afterBody

public int afterBody(Request request,
                     Response response)
Called after the output stream is closed ( either by servlet or automatically at end of service ). It is called after the servlet finished sending the response ( either closeing the stream or ending ). You can deal with connection reuse or do other actions


postService

public int postService(Request request,
                       Response response)
Called after service method ends. Log is a particular use.


postRequest

public int postRequest(Request request,
                       Response response)
Experimental hook: called after the request is finished, before returning to the caller. This will be called only on the main request, and will give interceptors a chance to clean up - that would be difficult in postService, that is called after included servlets too. Don't use this hook until it's marked final, I added it to deal with recycle() in facades - if we find a better solution this can go. ( unless people find it useful


getInfo

public java.lang.Object getInfo(Context ctx,
                                Request request,
                                int id,
                                java.lang.String key)
Hook for lazy evaluation of request info. This provides and uniform mechanism to allow modules to evaluate certain expensive request attributes/parameters when they are needed ( if ever ), and allows specialized modules and better integration with the web server/server modules. This replaces a number of hard-coded constructs and should clean up the core for un-needed dependencies, as well as provide flexibility in key areas as encoding, etc.


setInfo

public int setInfo(Context ctx,
                   Request request,
                   int id,
                   java.lang.String key,
                   java.lang.Object obj)

handleError

public int handleError(Request request,
                       Response response,
                       java.lang.Throwable t)
This callback is called whenever an exception happen. If t is null assume this is a "status" report ( 500, 404, etc). During this hook it is possible to create a sub-request and call the handler, and it is possible that the sub-request will also generate an exception. The handler must insure no loops will happen - but it's free to choose whatever method it wants. It's also the handler responsiblity to insure correct servlet API semantics - if the spec becomes incopmatible with previous versions ( or multiple interpretations are possible) that can be made a context-specific handler.


addInterceptor

public void addInterceptor(ContextManager cm,
                           Context ctx,
                           BaseInterceptor i)
                    throws TomcatException
Hook called when a new interceptor is added. All existing modules will be notified of the new added module. This hook will be called before the interceptor is initialized ( using engineInit hook ) An interceptor can add/remove other interceptors or applications, or alter the ordering of hooks, or change/set server properties.

Parameters:
cm - the server
ctx - not null if this is a local interceptor
i - the new added interceptor
Throws:
TomcatException - The module will not be added if any module throws an exception.

removeInterceptor

public void removeInterceptor(ContextManager cm,
                              Context ctx,
                              BaseInterceptor i)
                       throws TomcatException
Hook called when interceptors are removed. All existing modules will be notified of the module removal. This hook will be called before the interceptor is removed

Parameters:
cm - the server
ctx - not null if this is a local interceptor
i - the removed interceptor
Throws:
TomcatException - is logged, but will not have any effect

engineInit

public void engineInit(ContextManager cm)
                throws TomcatException
Initialize the module.

Throws:
TomcatException - The module will not be added if any exception is thrown by engineInit.

engineShutdown

public void engineShutdown(ContextManager cm)
                    throws TomcatException
Shut down the module.

Throws:
If - any exception is reported, the module will be removed. XXX (?)
TomcatException

engineStart

public void engineStart(ContextManager cm)
                 throws TomcatException
Notify that the server is ready and able to process requests

Throws:
TomcatException

engineStop

public void engineStop(ContextManager cm)
                throws TomcatException
Notify that the server is disabled and shoulnd't process more requests

Throws:
TomcatException

engineState

public void engineState(ContextManager cm,
                        int state)
                 throws TomcatException
Notifies the module that the server changed it's state. XXX this seems more flexible than init/start/stop/shutdown.

Throws:
TomcatException

addContext

public void addContext(ContextManager cm,
                       Context ctx)
                throws TomcatException
Called when a context is added to a CM. The context is probably not initialized yet, only path, docRoot, host, and properties set before adding the context ( in server.xml for example ) are available. At this stage mappers can start creating structures for the context ( the actual loading of the context may be delayed in future versions of tomcat until the first access ). DefaultCMSetter will also adjust the logger and paths based on context manager properties. Any activity that depends on web.xml must be done at init time.

Throws:
TomcatException

removeContext

public void removeContext(ContextManager cm,
                          Context ctx)
                   throws TomcatException
Called when a context is removed from a CM. A context is removed either as a result of admin ( remove or update), to support "clean" servlet reloading or at shutdown.

Throws:
TomcatException

contextInit

public void contextInit(Context ctx)
                 throws TomcatException
Notify when a context is initialized. The first interceptor in the chain for contextInit must read web.xml and set the context. When this method is called you can expect the context to be filled in with all the informations from web.xml.

Throws:
If - the interceptor throws exception the context will not be initialized ( state==NEW or ADDED or DISABLED ).
TomcatException

contextShutdown

public void contextShutdown(Context ctx)
                     throws TomcatException
Called when a context is stoped, before removeContext. You must free all resources associated with this context.

Throws:
TomcatException

contextState

public void contextState(Context ctx,
                         int newState)
                  throws TomcatException
Notify that the context state changed

Throws:
TomcatException

reload

public void reload(Request req,
                   Context ctx)
            throws TomcatException
Reload notification - called whenever a reload is done. This can be used to serialize sessions, log the event, remove any resource that was class-loader dependent. Note. The current implementation uses a note "oldLoader" that will keep a reference to the previous class loader during this hook. It will be set by the module that creates the loaders, and should be destroyed when the hook is done. This can also be implemented using a get/setOldClassLoader in Context, but so far this is used in only 2 modules, adding new API is not needed.

Throws:
TomcatException

copyContext

public void copyContext(Request req,
                        Context oldC,
                        Context newC)
                 throws TomcatException
Reload notification - called whenever a full reload is done. This can be used to serialize sessions, log the event, clone any resource that was class-loader dependent.

Throws:
TomcatException

addContainer

public void addContainer(Container container)
                  throws TomcatException
Notify that certain properties are defined for a URL pattern. Properties can be a "handler" that will be called for URLs matching the pattern or "security constraints" ( or any other properties that can be associated with URL patterns ) Interceptors will maintain their own mapping tables if they are interested in a certain property. General-purpose mapping code is provided in utils. The method will be called once for every properties associated with a URL - it's up to the interceptor to interpret the URL and deal with "merging". A Container that defines a servlet mapping ( handler ) will have the handlerName set to the name of the handler. The Handler ( getHandler) can be null for dynamically added servlets, and will be set by a facade interceptor. XXX We use this hook to create ServletWrappers for dynamically added servlets in InvokerInterceptor ( JspInterceptor is JDK1.2 specific ). It may be good to add a new hook specifically for that

Throws:
TomcatException

removeContainer

public void removeContainer(Container container)
                     throws TomcatException
A rule was removed, update the internal strucures. You can also clean up and reload everything using Context.getContainers()

Throws:
TomcatException

addSecurityConstraint

public void addSecurityConstraint(Context ctx,
                                  java.lang.String path,
                                  Container ct)
                           throws TomcatException
Throws:
TomcatException

addHandler

public void addHandler(Handler h)
                throws TomcatException
Notification of a new content handler added to a context

Throws:
TomcatException

removeHandler

public void removeHandler(Handler h)
                   throws TomcatException
Notification of a content handler removal

Throws:
TomcatException

preServletInit

public void preServletInit(Context ctx,
                           Handler sw)
                    throws TomcatException
Servlet Init notification

Throws:
TomcatException

postServletInit

public void postServletInit(Context ctx,
                            Handler sw)
                     throws TomcatException
Throws:
TomcatException

preInitCheck

public int preInitCheck(Request req,
                        Handler sw)
                 throws TomcatException
Setup before calling init.

Throws:
TomcatException

postInitCheck

public int postInitCheck(Request req,
                         Handler sw)
                  throws TomcatException
Throws:
TomcatException

preServletDestroy

public void preServletDestroy(Context ctx,
                              Handler sw)
                       throws TomcatException
Servlet Destroy notification

Throws:
TomcatException

postServletDestroy

public void postServletDestroy(Context ctx,
                               Handler sw)
                        throws TomcatException
Throws:
TomcatException

setDebug

public final void setDebug(int d)

setContextManager

public void setContextManager(ContextManager cm)

getContextManager

public final ContextManager getContextManager()

setContext

public void setContext(Context ctx)
Called for context-level interceptors


getContext

public Context getContext()

log

public final void log(java.lang.String s)

log

public final void log(java.lang.String s,
                      java.lang.Throwable t)

log

public final void log(java.lang.String s,
                      int level)

log

public final void log(java.lang.String s,
                      java.lang.Throwable t,
                      int level)

getLog

public Log getLog()

getDebug

public final int getDebug()

registerHooks

public int registerHooks(Hooks h,
                         ContextManager cm,
                         Context ctx)
Special method for self-registered hooks, intended to support a mechanism similar with Apache2.0 and further extensibility without interface changes. Most modules are added to the Hooks automatically. A module overriding this method has full control over this process. If OK is returned, no other processing is done ( i.e. no introspection, we assume the module set up the right hooks )


setNote

public final void setNote(int pos,
                          java.lang.Object value)

getNote

public final java.lang.Object getNote(int pos)

getNote

public java.lang.Object getNote(java.lang.String name)
                         throws TomcatException
Throws:
TomcatException

setNote

public void setNote(java.lang.String name,
                    java.lang.Object value)
             throws TomcatException
Throws:
TomcatException


Copyright ? 2001 Apache Software Foundation. All Rights Reserved.