⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 contextmanager.java

📁 低版本的tomcat 对于有些老版本的应用还真的需要老版的中间件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
    /** Handle the case of status handler generating an error
     */
    private boolean statusLoop( Context ctx, Request req, int newCode ) {
        Integer lastCode = (Integer)req.getAttribute("javax.servlet.error.status_code");
        // If status code repeated, assume recursive loop
        if ( lastCode != null && lastCode.intValue() == newCode) {
            if( ctx.getDebug() > 0 )
                ctx.log( "Error: nested error inside status servlet " +
                        req.getAttribute("javax.servlet.error.status_code"));
            return true;
        }
        return false;
    }

	 /**
	  *  Called if the request does not map into any context.  This code
	  * was lifted from DefaultCMSetter.NotFoundHandler becuase without
	  * a valid context we really can't execute that servlet.
	  */
	 private void  handleContextNotFound(Request req, Response res) throws IOException
	 {
		 StringManager sm=StringManager.getManager("org.apache.tomcat.resources");
		 res.setContentType("text/html");	// ISO-8859-1 default

		 String requestURI = (String)req.
			  getAttribute("javax.servlet.include.request_uri");

		 if (requestURI == null || res.isIncluded()) {
			  requestURI = req.getRequestURI();
		 }

		 StringBuffer buf = new StringBuffer();
		 buf.append("<head><title>")
			  .append(sm.getString("defaulterrorpage.notfound404"))
			  .append("</title></head>\r\n");
		 buf.append("<body><h1>")
			  .append(sm.getString("defaulterrorpage.notfound404"))
			  .append("</h1>\r\n<b>");
		 buf.append(sm.getString("defaulterrorpage.originalrequest"))
			  .append("</b> ")
			  .append(RequestUtil.filter(requestURI));

		 if (getShowDebugInfo()) {
			  if (res.isIncluded()) {
			 requestURI = (String)req.
				  getAttribute("javax.servlet.include.request_uri");
			  }
			  if (requestURI != null) {
			 buf.append("<br><br>\r\n<b>")
				  .append(sm.getString("defaulterrorpage.notfoundrequest"))
				  .append("</b> ")
				  .append(RequestUtil.filter(requestURI));
			  }
		 }

		 buf.append("</body>\r\n");

		 String body = buf.toString();

		 res.setContentLength(body.length());

		 if( res.isUsingStream() ) {
			  ServletOutputStream out = res.getOutputStream();
			  out.print(body);
			  out.flush();
		 } else {
			  PrintWriter out = res.getWriter();
			  out.print(body);
			  out.flush();
		 }
	  }

    // -------------------- Support for notes --------------------

    /** Note id counters. Synchronized access is not necesarily needed
     *  ( the initialization is in one thread ), but anyway we do it
     */
    private  int noteId[]=new int[4];

    /** Maximum number of notes supported
     */
    public static final int MAX_NOTES=32;
    public static final int RESERVED=3;

    public static final int SERVER_NOTE=0;
    public static final int CONTAINER_NOTE=1;
    public static final int REQUEST_NOTE=2;
    public static final int HANDLER_NOTE=3;

    public static final int REQ_RE_NOTE=0;

    String noteName[][]=new String[4][MAX_NOTES];

    /** used to allow interceptors to set specific per/request, per/container
     * and per/CM informations.
     *
     * This will allow us to remove all "specialized" methods in
     * Request and Container/Context, without losing the functionality.
     * Remember - Interceptors are not supposed to have internal state
     * and minimal configuration, all setup is part of the "core", under
     *  central control.
     *  We use indexed notes instead of attributes for performance -
     * this is internal to tomcat and most of the time in critical path
     */

    /** Create a new note id. Interceptors will get an Id at init time for
     *  all notes that it needs.
     *
     *  Throws exception if too many notes are set ( shouldn't happen in
     *  normal use ).
     *  @param noteType The note will be associated with the server,
     *   container or request.
     *  @param name the name of the note.
     */
    public synchronized int getNoteId( int noteType, String name )
	throws TomcatException
    {
	// find if we already have a note with this name
	// ( this is in init(), not critical )
	for( int i=0; i< noteId[noteType] ; i++ ) {
	    if( name.equals( noteName[noteType][i] ) )
		return i;
	}

	if( noteId[noteType] >= MAX_NOTES )
	    throw new TomcatException( "Too many notes ");

	// make sure the note id is > RESERVED
	if( noteId[noteType] < RESERVED ) noteId[noteType]=RESERVED;

	noteName[noteType][ noteId[noteType] ]=name;
	return noteId[noteType]++;
    }

    public String getNoteName( int noteType, int noteId ) {
	return noteName[noteType][noteId];
    }

    // -------------------- Per-server notes --------------------
    Object notes[]=new Object[MAX_NOTES];

    public void setNote( int pos, Object value ) {
	notes[pos]=value;
    }

    public Object getNote( int pos ) {
	return notes[pos];
    }

    // -------------------- Logging and debug --------------------
    boolean firstLog = true;
    LogHelper loghelper = new LogHelper("tc_log", "ContextManager");

    // Not used, except in server.xml, and usage is unclear -- should
    // we kill it? Looks very obsolete.
    public void addLogger(Logger l) {
	// Will use this later once I feel more sure what I want to do here.
	// -akv
	// firstLog=false;
	//	if("tc_log".equals( logger.getName()) cmLog=logger;
	String path=l.getPath();
	if( path!=null ) {
	    File f=new File( path );
	    if( ! f.isAbsolute() ) {
		// Make it relative to home !
		File wd= getAbsolute( f );
		l.setPath( wd.getAbsolutePath() );
	    }
	    // create the files, ready to log.
	}
	l.open();
    }


    public void setDebug( int level ) {
	if( level != 0 ) System.out.println( "Setting level to " + level);
	debug=level;
    }

    public int getDebug() {
	return debug;
    }

    public final void log(String msg) {
	loghelper.log(msg);
    }

    private final void logInt(String msg) {
	loghelper.log(msg);
    }

    public final void doLog(String msg) {
	loghelper.log(msg);
    }

    public final void doLog(String msg, Throwable t) {
	loghelper.log(msg, t);
    }

    public final void doLog(String msg, Throwable t, int level) {
	loghelper.log(msg, t, level);
    }

    // -------------------- Accounting --------------------
    // XXX Can be implemented as note !

    public static final int ACC_INIT_START=0;
    public static final int ACC_INIT_END=0;

    public static final int ACCOUNTS=7;
    long accTable[]=new long[ACCOUNTS];

    public void setAccount( int pos, long value ) {
	accTable[pos]=value;
    }

    public long getAccount( int pos ) {
	return accTable[pos];
    }

    // -------------------- DEPRECATED --------------------
    // XXX host and port are used only to construct a unique
    // work-dir for contexts, using them and the path
    // Since nobody sets them - I guess we can just drop them
    // anyway.
    // XXX ask and find if there is any other use!
    public static final String DEFAULT_HOSTNAME="localhost";
    public static final int DEFAULT_PORT=8080;
    String hostname;
    int port;

    /**
     * Sets the port number on which this server listens.
     *
     * @param port The new port number
     * @deprecated
     */
    public void setPort(int port) {
	if( debug > 20 )/*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
	this.port=port;
    }

    /**
     * Gets the port number on which this server listens.
     * @deprecated
     */
    public int getPort() {
	//	/*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
	if(port==0) port=DEFAULT_PORT;
	return port;
    }

    /**
     * Sets the virtual host name of this server.
     *
     * @param host The new virtual host name
     * @deprecated
     */
    public void setHostName( String host) {
	if( debug > 20 ) /*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
	this.hostname=host;
    }

    /**
     * Gets the virtual host name of this server.
     * @deprecated
     */
    public String getHostName() {
	//	/*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
	if(hostname==null)
	    hostname=DEFAULT_HOSTNAME;
	return hostname;
    }
    // -------------------- DEPRECATED --------------------

    /**
     * The set of Contexts associated with this ContextManager,
     * keyed by context paths.
     * @deprecated - the server shouldn't make any assumptions about
     *  the key.
     */
    private Hashtable contexts = new Hashtable();

    /**
     * Get the names of all the contexts in this server.
     * @deprecated Path is not "unique key".
     */
    public Enumeration getContextNames() {
	if( debug>20 ) /*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
        return contexts.keys();
    }

    /**
     * Gets a context by it's name, or <code>null</code> if there is
     * no such context.
     *
     * @param name Name of the requested context
     * @deprecated Use an external iterator to find the context that
     *  matches your conditions.
     *
     */
    public Context getContext(String name) {
	// System.out.println("Using deprecated getContext");
	//	/*DEBUG*/ try {throw new Exception(); } catch(Exception ex) {ex.printStackTrace();}
	return (Context)contexts.get(name);
    }

    /**
     * Shut down and removes a context from service.
     *
     * @param name Name of the Context to be removed
     * @deprecated Use removeContext( Context ).
     */
    public void removeContext(String name) throws TomcatException {
	Context context = (Context)contexts.get(name);
	log( "Removing context " + context.toString());

	ContextInterceptor cI[]=getContextInterceptors();
	for( int i=0; i< cI.length; i++ ) {
	    cI[i].removeContext( this, context );
	}

	if(context != null) {
	    shutdownContext( context );
	    contexts.remove(name);
	}
    }

    public void doPreServletInit(Context ctx, ServletWrapper sw)
	throws TomcatException
    {
	ContextInterceptor cI[]=getContextInterceptors();
	for( int i=0; i< cI.length; i++ ) {
	    try {
		cI[i].preServletInit( ctx, sw );
	    } catch( TomcatException ex) {
		ex.printStackTrace();
	    }
	}
    }

    public void doPostServletInit(Context ctx, ServletWrapper sw)
	throws TomcatException
    {
	ContextInterceptor cI[]=getContextInterceptors();
	for( int i=0; i< cI.length; i++ ) {
	    try {
		cI[i].postServletInit( ctx, sw );
	    } catch( TomcatException ex) {
		ex.printStackTrace();
	    }
	}
    }

    public void doPreServletDestroy(Context ctx, ServletWrapper sw)
	throws TomcatException
    {
	ContextInterceptor cI[]=getContextInterceptors();
	for( int i=0; i< cI.length; i++ ) {
	    try {
		cI[i].preServletDestroy( ctx, sw );
	    } catch( TomcatException ex) {
		ex.printStackTrace();
	    }
	}
    }

    public void doPostServletDestroy(Context ctx, ServletWrapper sw)
	throws TomcatException
    {
	ContextInterceptor cI[]=getContextInterceptors();
	for( int i=0; i< cI.length; i++ ) {
	    try {
		cI[i].postServletDestroy( ctx, sw );
	    } catch( TomcatException ex) {
		ex.printStackTrace();
	    }
	}
    }

    /** @deprecated
     */
    public void setTomcatHome( String s ) {
	setInstallDir( s );
    }

    /** @deprecated
     */
    public String getTomcatHome() {
	return getInstallDir();
    }

    /** Convert a relative name to absolute by using the "home" property
     */
    public File getAbsolute(File f) {
        if (!f.isAbsolute()) {
            // evaluate repository path relative to the context's home
	    // directory
	    return new File(getHome(), f.getPath());
        }
        return f;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -