errorpagemanager.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 811 行 · 第 1/2 页

JAVA
811
字号
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT.  See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * *   Free Software Foundation, Inc. *   59 Temple Place, Suite 330 *   Boston, MA 02111-1307  USA * * @author Scott Ferguson */package com.caucho.server.webapp;import com.caucho.Version;import com.caucho.config.*;import com.caucho.i18n.CharacterEncoding;import com.caucho.java.LineMap;import com.caucho.java.LineMapException;import com.caucho.java.ScriptStackTrace;import com.caucho.server.connection.AbstractHttpRequest;import com.caucho.server.connection.AbstractHttpResponse;import com.caucho.server.connection.CauchoRequest;import com.caucho.server.connection.CauchoResponse;import com.caucho.server.dispatch.BadRequestException;import com.caucho.server.util.CauchoSystem;import com.caucho.server.resin.Resin;import com.caucho.util.*;import com.caucho.vfs.ClientDisconnectException;import com.caucho.vfs.Encoding;import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.UnavailableException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.CharArrayWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Locale;import java.util.logging.Level;import java.util.logging.Logger;/** * Represents the final servlet in a filter chain. */public class ErrorPageManager {  private final static L10N L = new L10N(ErrorPageManager.class);  private final static Logger log    = Logger.getLogger(ErrorPageManager.class.getName());    public static final char []MSIE_PADDING;    public static String REQUEST_URI = "javax.servlet.include.request_uri";  public static String CONTEXT_PATH = "javax.servlet.include.context_path";  public static String SERVLET_PATH = "javax.servlet.include.servlet_path";  public static String PATH_INFO = "javax.servlet.include.path_info";  public static String QUERY_STRING = "javax.servlet.include.query_string";    public static String STATUS_CODE = "javax.servlet.error.status_code";  public static String EXCEPTION_TYPE = "javax.servlet.error.exception_type";  public static String MESSAGE = "javax.servlet.error.message";  public static String EXCEPTION = "javax.servlet.error.exception";  public static String ERROR_URI = "javax.servlet.error.request_uri";  public static String SERVLET_NAME = "javax.servlet.error.servlet_name";    public static String JSP_EXCEPTION = "javax.servlet.jsp.jspException";    public static String SHUTDOWN = "com.caucho.shutdown";    private final WebApp _app;  private WebAppContainer _appContainer;  private HashMap<Object,String> _errorPageMap = new HashMap<Object,String>();  private String _defaultLocation;  private ErrorPageManager _parent;  /**   * Create error page manager.   */  public ErrorPageManager(WebApp app)  {    _app = app;  }  /**   * Sets the manager parent.   */  public void setParent(ErrorPageManager parent)  {    _parent = parent;  }  /**   * Gets the manager parent.   */  public ErrorPageManager getParent()  {    return _parent;  }  /**   * Adds an error page.   */  public void addErrorPage(ErrorPage errorPage)  {    if (errorPage.getExceptionType() != null) {      _errorPageMap.put(errorPage.getExceptionType(),                        errorPage.getLocation());    }    else if (errorPage.getErrorCode() < 0) {      _defaultLocation = errorPage.getLocation();    }    else      _errorPageMap.put(new Integer(errorPage.getErrorCode()),                        errorPage.getLocation());  }  /**   * Sets the webApp container.   */  public void setWebAppContainer(WebAppContainer appContainer)  {    _appContainer = appContainer;  }  /**   * Returns true if we should return a development-friendly error page.   */  protected boolean isDevelopmentModeErrorPage()  {    if (_app != null && _app.getServer() != null)      return _app.getServer().isDevelopmentModeErrorPage();    else if (Resin.getCurrent() != null	     && Resin.getCurrent().getServer() != null) {      return Resin.getCurrent().getServer().isDevelopmentModeErrorPage();    }    else      return true;  }    /**   * Displays a parse error.   */  public void sendServletError(Throwable e,                               ServletRequest req,                               ServletResponse res)    throws IOException  {    HttpServletResponse response = (HttpServletResponse) res;    HttpServletRequest request = (HttpServletRequest) req;    Throwable rootExn = e;    Throwable errorPageExn = null;    LineMap lineMap = null;    if (response instanceof AbstractHttpResponse) {      ((AbstractHttpResponse) response).killCache();      ((AbstractHttpResponse) response).setNoCache(true);    }    try {      response.reset();    } catch (IllegalStateException e1) {    }    if (rootExn instanceof ClientDisconnectException)      throw (ClientDisconnectException) rootExn;    String location = null;    String title = "500 Servlet Exception";    boolean badRequest = false;    boolean doStackTrace = true;    boolean isCompileException = false;    boolean isLineCompileException = false;    boolean isServletException = false;    Throwable compileException = null;    String lineMessage = null;    boolean lookupErrorPage = true;        while (true) {      if (rootExn instanceof LineMapException)        lineMap = ((LineMapException) rootExn).getLineMap();      if (lookupErrorPage) {	errorPageExn = rootExn;      }      if (rootExn instanceof DisplayableException) {        doStackTrace = false;        isCompileException = true;	if (compileException == null)	  compileException = rootExn;      }      else if (rootExn instanceof CompileException) {        doStackTrace = false;        isCompileException = true;        // use outer exception because it might have added more location info	/*        if (rootExn instanceof LineCompileException) {	  compileException = rootExn;	            isLineCompileException = true;        }	else if (compileException == null) // ! isLineCompileException)          compileException = rootExn;	*/	if (compileException == null) // ! isLineCompileException)          compileException = rootExn;      }      else if (rootExn instanceof LineException) {	if (lineMessage == null)	  lineMessage = rootExn.getMessage();      }      if (rootExn instanceof BadRequestException)        badRequest = true;      if (location != null || ! lookupErrorPage) {      }      else if (rootExn instanceof LineMapException               && rootExn instanceof ServletException               && ! (rootExn instanceof LineCompileException)               && rootExn.getCause() != null) {	// hack to deal with JSP wrapping      }      else if (! isServletException) {	// SRV.9.9.2 Servlet 2.4        //location = getErrorPage(rootExn, ServletException.class);        location = getErrorPage(rootExn);	isServletException = true;      }      else {        location = getErrorPage(rootExn);	lookupErrorPage = false;      }      if (location != null)	lookupErrorPage = false;      Throwable cause = null;      if (rootExn instanceof ServletException          && ! (rootExn instanceof LineCompileException))        cause = ((ServletException) rootExn).getRootCause();      else {	lookupErrorPage = false;        cause = rootExn.getCause();      }      if (cause != null)        rootExn = cause;      else {        break;      }    }    if (location == null && lookupErrorPage) {      location = getErrorPage(rootExn);    }    if (location == null)      location = getErrorPage(500);    if (location == null && _defaultLocation == null && _parent != null) {      _parent.sendServletError(e, req, res);      return;    }    if (badRequest) {      title = rootExn.getMessage();      doStackTrace = false;      badRequest = true;      if (request instanceof CauchoRequest)	((CauchoRequest) request).killKeepalive();            response.resetBuffer();            response.setStatus(response.SC_BAD_REQUEST, rootExn.getMessage());    }    else if (rootExn instanceof UnavailableException) {      UnavailableException unAvail = (UnavailableException) rootExn;      if (unAvail.isPermanent()) {	response.setStatus(HttpServletResponse.SC_NOT_FOUND);	title = "404 Not Found";	if (location == null)	  location = getErrorPage(response.SC_NOT_FOUND);      }      else {	response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);	title = "503 Unavailable";	if (unAvail.getUnavailableSeconds() > 0)	  response.setIntHeader("Retry-After",				unAvail.getUnavailableSeconds());		if (location == null)	  location = getErrorPage(response.SC_SERVICE_UNAVAILABLE);      }    }    /*    else if (_app != null && app.getServer().isClosed()) {      response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);      title = "503 Unavailable";    }    */    else      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);        if (location == null)      location = _defaultLocation;    Level level = location == null ? Level.WARNING : Level.FINE;    if (isCompileException)      log.log(level, compileException.getMessage());    else if (! doStackTrace)      log.log(level, rootExn.toString());    else      log.log(level, e.toString(), e);        if (location != null) {      if (errorPageExn == null)	errorPageExn = rootExn;            request.setAttribute(JSP_EXCEPTION, errorPageExn);      request.setAttribute(EXCEPTION, errorPageExn);      request.setAttribute(EXCEPTION_TYPE, errorPageExn.getClass());      if (request instanceof HttpServletRequest)        request.setAttribute(ERROR_URI,                             ((HttpServletRequest) request).getRequestURI());      if (request instanceof AbstractHttpRequest)        request.setAttribute(AbstractHttpRequest.SERVLET_NAME,                             ((AbstractHttpRequest) request).getServletName());      request.setAttribute(STATUS_CODE, new Integer(500));      request.setAttribute(MESSAGE, errorPageExn.getMessage());      /*        if (_app != null && _app.getServer().isClosed())        setAttribute(SHUTDOWN, "shutdown");      */      try {        RequestDispatcher disp = null;        // can't use filters because of error pages due to filters        // or security.	if (_app != null)	  disp = _app.getRequestDispatcher(location);	else if (_appContainer != null)	  disp = _appContainer.getRequestDispatcher(location);	          if (disp != null) {          ((RequestDispatcherImpl) disp).error(request, response);          return;        }      } catch (Throwable e1) {        log.log(Level.INFO, e1.toString(), e1);        rootExn = e1;      }    }    response.setContentType("text/html");    String encoding = CharacterEncoding.getLocalEncoding();    if (encoding != null)      response.setCharacterEncoding(encoding);    else {      Locale locale = Locale.getDefault();      if (! "ISO-8859-1".equals(Encoding.getMimeName(locale)))	response.setLocale(Locale.getDefault());    }    PrintWriter out = response.getWriter();    if (isDevelopmentModeErrorPage()) {      out.println("<html>");      if (! response.isCommitted())	out.println("<head><title>" + escapeHtml(title) + "</title></head>");      out.println("<body>");      out.println("<h1>" + escapeHtml(title) + "</h1>");

⌨️ 快捷键说明

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