Java Code Examples for org.apache.catalina.connector.Response#sendError()

The following examples show how to use org.apache.catalina.connector.Response#sendError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticatorBase.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private JaspicState getJaspicState(AuthConfigProvider jaspicProvider, Request request,
        Response response, boolean authMandatory) throws IOException {
    JaspicState jaspicState = new JaspicState();

    jaspicState.messageInfo =
            new MessageInfoImpl(request.getRequest(), response.getResponse(), authMandatory);

    try {
        CallbackHandler callbackHandler = createCallbackHandler();
        ServerAuthConfig serverAuthConfig = jaspicProvider.getServerAuthConfig(
                "HttpServlet", jaspicAppContextID, callbackHandler);
        String authContextID = serverAuthConfig.getAuthContextID(jaspicState.messageInfo);
        jaspicState.serverAuthContext = serverAuthConfig.getAuthContext(authContextID, null, null);
    } catch (AuthException e) {
        log.warn(sm.getString("authenticator.jaspicServerAuthContextFail"), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    return jaspicState;
}
 
Example 2
Source File: RedisSessionRequestValve.java    From redis-session-manager with Apache License 2.0 6 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    Context context = request.getContext();
    if (context == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, sm.getString("standardHost.noContext"));
        return;
    }
    Thread.currentThread().setContextClassLoader(context.getLoader().getClassLoader());

    boolean processed = false;
    try {
        if (ignorePattern == null || !ignorePattern.matcher(request.getRequestURI()).matches()) {
            processed = true;
            if (log.isTraceEnabled()) {
                log.trace("Will save to redis after request for [" + getQueryString(request) + "]");
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Ignoring [" + getQueryString(request) + "]");
            }
        }
        getNext().invoke(request, response);
    } finally {
        manager.afterRequest(processed);
    }
}
 
Example 3
Source File: StandardEngineValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Select the appropriate child Host to process this request,
 * based on the requested server name.  If no matching Host can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Select the Host to be used for this Request
    Host host = request.getHost();
    if (host == null) {
        response.sendError
            (HttpServletResponse.SC_BAD_REQUEST,
             sm.getString("standardEngine.noHost", 
                          request.getServerName()));
        return;
    }
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(host.getPipeline().isAsyncSupported());
    }

    // 责任链模式:将请求传递给 Host 管道
    // 从请求对象中取出该请求关联的Host(默认情况下是org.apache.catalina.core.StandardHost对象),
    // StandardHost 初始化的时候会设置基础阀 StandardHostValue
    // Ask this Host to process this request
    host.getPipeline().getFirst().invoke(request, response);

}
 
Example 4
Source File: StandardEngineValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Select the appropriate child Host to process this request,
 * based on the requested server name.  If no matching Host can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Select the Host to be used for this Request
    Host host = request.getHost();
    if (host == null) {
        response.sendError
            (HttpServletResponse.SC_BAD_REQUEST,
             sm.getString("standardEngine.noHost", 
                          request.getServerName()));
        return;
    }
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(host.getPipeline().isAsyncSupported());
    }

    // Ask this Host to process this request
    host.getPipeline().getFirst().invoke(request, response);

}
 
Example 5
Source File: RemoteCIDRValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void invoke(final Request request, final Response response) throws IOException, ServletException {

    if (isAllowed(request.getRequest().getRemoteAddr())) {
        getNext().invoke(request, response);
    } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}
 
Example 6
Source File: RequestFilterValve.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 7
Source File: StandardContextValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Select the appropriate child Wrapper to process this request,
 * based on the specified request URI.  If no matching Wrapper can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Disallow any direct access to resources under WEB-INF or META-INF
    MessageBytes requestPathMB = request.getRequestPathMB();
    if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/META-INF"))
            || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Select the Wrapper to be used for this Request
    Wrapper wrapper = request.getWrapper();
    if (wrapper == null || wrapper.isUnavailable()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Acknowledge the request
    try {
        response.sendAcknowledgement();
    } catch (IOException ioe) {
        container.getLogger().error(sm.getString(
                "standardContextValve.acknowledgeException"), ioe);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
    }
    wrapper.getPipeline().getFirst().invoke(request, response);
}
 
Example 8
Source File: RequestFilterValve.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 9
Source File: StandardEngineValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Select the appropriate child Host to process this request,
 * based on the requested server name.  If no matching Host can
 * be found, return an appropriate HTTP error.
 *
 * 选择合适的Host去执行此次请求。
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Select the Host to be used for this Request
    //StandardHost.
    Host host = request.getHost();
    if (host == null) {
        response.sendError
            (HttpServletResponse.SC_BAD_REQUEST,
             sm.getString("standardEngine.noHost",
                          request.getServerName()));
        return;
    }
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(host.getPipeline().isAsyncSupported());
    }

    // Ask this Host to process this request
    /**
     *  委托对应的Host处理请求。
     * {@link StandardHostValve#invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response)}
     */
    host.getPipeline().getFirst().invoke(request, response);

}
 
Example 10
Source File: RequestFilterValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Reject the request that was denied by this valve.
 * <p>If <code>invalidAuthenticationWhenDeny</code> is true
 * and the context has <code>preemptiveAuthentication</code>
 * set, set an invalid authorization header to trigger basic auth.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be processed
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
protected void denyRequest(Request request, Response response)
        throws IOException, ServletException {
    if (invalidAuthenticationWhenDeny) {
        Context context = request.getContext();
        if (context != null && context.getPreemptiveAuthentication()) {
            if (request.getCoyoteRequest().getMimeHeaders().getValue("authorization") == null) {
                request.getCoyoteRequest().getMimeHeaders().addValue("authorization").setString("invalid");
            }
            getNext().invoke(request, response);
            return;
        }
    }
    response.sendError(denyStatus);
}
 
Example 11
Source File: ErrorReportValve.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state. If the status code is greater than or equal to 400
 * or an uncaught exception was thrown then the error handling will be
 * triggered.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

    // Perform the request
    getNext().invoke(request, response);

    if (response.isCommitted()) {
        if (response.setErrorReported()) {
            // Error wasn't previously reported but we can't write an error
            // page because the response has already been committed. Attempt
            // to flush any data that is still to be written to the client.
            try {
                response.flushBuffer();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
            }
            // Close immediately to signal to the client that something went
            // wrong
            response.getCoyoteResponse().action(ActionCode.CLOSE_NOW, null);
        }
        return;
    }

    Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

    // If an async request is in progress and is not going to end once this
    // container thread finishes, do not trigger error page handling - it
    // will be triggered later if required.
    if (request.isAsync() && !request.isAsyncCompleting()) {
        return;
    }

    if (throwable != null && !response.isError()) {
        // Make sure that the necessary methods have been called on the
        // response. (It is possible a component may just have set the
        // Throwable. Tomcat won't do that but other components might.)
        // These are safe to call at this point as we know that the response
        // has not been committed.
        response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // One way or another, response.sendError() will have been called before
    // execution reaches this point and suspended the response. Need to
    // reverse that so this valve can write to the response.
    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        ExceptionUtils.handleThrowable(tt);
    }
}
 
Example 12
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString());
    return (false);

}
 
Example 13
Source File: StandardContextValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Select the appropriate child Wrapper to process this request,
 * based on the specified request URI.  If no matching Wrapper can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Disallow any direct access to resources under WEB-INF or META-INF
    MessageBytes requestPathMB = request.getRequestPathMB();
    if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/META-INF"))
            || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Select the Wrapper to be used for this Request
    Wrapper wrapper = request.getWrapper();
    if (wrapper == null || wrapper.isUnavailable()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Acknowledge the request
    try {
        response.sendAcknowledgement();
    } catch (IOException ioe) {
        container.getLogger().error(sm.getString(
                "standardContextValve.acknowledgeException"), ioe);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    if (request.isAsyncSupported()) {
        request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
    }
    /**
     * 委托对应的Wrapper去处理请求。
     * {@link StandardWrapperValve#invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response)}
     */
    wrapper.getPipeline().getFirst().invoke(request, response);
}
 
Example 14
Source File: RealmBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return true;
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return true;
        }
        if (userConstraint.equals(TransportGuarantee.NONE.name())) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return true;
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return true;
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return false;
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString(), transportGuaranteeRedirectStatus);
    return false;

}
 
Example 15
Source File: ErrorReportValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state. If the status code is greater than or equal to 400
 * or an uncaught exception was thrown then the error handling will be
 * triggered.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

    // Perform the request
    getNext().invoke(request, response);

    if (response.isCommitted()) {
        if (response.setErrorReported()) {
            // Error wasn't previously reported but we can't write an error
            // page because the response has already been committed. Attempt
            // to flush any data that is still to be written to the client.
            try {
                response.flushBuffer();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
            }
            // Close immediately to signal to the client that something went
            // wrong
            response.getCoyoteResponse().action(ActionCode.CLOSE_NOW, null);
        }
        return;
    }

    Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

    // If an async request is in progress and is not going to end once this
    // container thread finishes, do not process any error page here.
    if (request.isAsync() && !request.isAsyncCompleting()) {
        return;
    }

    if (throwable != null && !response.isError()) {
        // Make sure that the necessary methods have been called on the
        // response. (It is possible a component may just have set the
        // Throwable. Tomcat won't do that but other components might.)
        // These are safe to call at this point as we know that the response
        // has not been committed.
        response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // One way or another, response.sendError() will have been called before
    // execution reaches this point and suspended the response. Need to
    // reverse that so this valve can write to the response.
    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        ExceptionUtils.handleThrowable(tt);
    }
}
 
Example 16
Source File: RealmBase.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString(), transportGuaranteeRedirectStatus);
    return (false);

}
 
Example 17
Source File: StandardContextValve.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Select the appropriate child Wrapper to process this request,
 * based on the specified request URI.  If no matching Wrapper can
 * be found, return an appropriate HTTP error.
 *
 * @param request Request to be processed
 * @param response Response to be produced
 *
 * @exception IOException if an input/output error occurred
 * @exception ServletException if a servlet error occurred
 */
@Override
public final void invoke(Request request, Response response)
    throws IOException, ServletException {

    // Disallow any direct access to resources under WEB-INF or META-INF
    MessageBytes requestPathMB = request.getRequestPathMB();
    if ((requestPathMB.startsWithIgnoreCase("/META-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/META-INF"))
            || (requestPathMB.startsWithIgnoreCase("/WEB-INF/", 0))
            || (requestPathMB.equalsIgnoreCase("/WEB-INF"))) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Select the Wrapper to be used for this Request
    Wrapper wrapper = request.getWrapper();
    if (wrapper == null || wrapper.isUnavailable()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Acknowledge the request
    try {
        response.sendAcknowledgement();
    } catch (IOException ioe) {
        container.getLogger().error(sm.getString(
                "standardContextValve.acknowledgeException"), ioe);
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    
    if (request.isAsyncSupported()) {
        request.setAsyncSupported(wrapper.getPipeline().isAsyncSupported());
    }

    // 责任链模式:将请求传递给 Wrapper 管道
    // 从请求对象中取出该请求关联的 Wrapper(默认情况下是org.apache.catalina.core.StandardWrapper对象),
    // StandardWrapper对象 初始化的时候会设置基础阀 StandardWrapperValve
    wrapper.getPipeline().getFirst().invoke(request, response);
}
 
Example 18
Source File: ErrorReportValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Invoke the next Valve in the sequence. When the invoke returns, check
 * the response state. If the status code is greater than or equal to 400
 * or an uncaught exception was thrown then the error handling will be
 * triggered.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {

    // Perform the request
    getNext().invoke(request, response);

    if (response.isCommitted()) {
        if (response.setErrorReported()) {
            // Error wasn't previously reported but we can't write an error
            // page because the response has already been committed. Attempt
            // to flush any data that is still to be written to the client.
            try {
                response.flushBuffer();
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
            }
            // Close immediately to signal to the client that something went
            // wrong
            response.getCoyoteResponse().action(ActionCode.CLOSE_NOW,
                    request.getAttribute(RequestDispatcher.ERROR_EXCEPTION));
        }
        return;
    }

    Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);

    // If an async request is in progress and is not going to end once this
    // container thread finishes, do not process any error page here.
    if (request.isAsync() && !request.isAsyncCompleting()) {
        return;
    }

    if (throwable != null && !response.isError()) {
        // Make sure that the necessary methods have been called on the
        // response. (It is possible a component may just have set the
        // Throwable. Tomcat won't do that but other components might.)
        // These are safe to call at this point as we know that the response
        // has not been committed.
        response.reset();
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    // One way or another, response.sendError() will have been called before
    // execution reaches this point and suspended the response. Need to
    // reverse that so this valve can write to the response.
    response.setSuspended(false);

    try {
        report(request, response, throwable);
    } catch (Throwable tt) {
        ExceptionUtils.handleThrowable(tt);
    }
}