Search in sources :

Example 46 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project tomcat by apache.

the class RequestDumperFilter method doFilter.

/**
     * Log the interesting request parameters, invoke the next Filter in the
     * sequence, and log the interesting response parameters.
     *
     * @param request  The servlet request to be processed
     * @param response The servlet response to be created
     * @param chain    The filter chain being processed
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hRequest = null;
    HttpServletResponse hResponse = null;
    if (request instanceof HttpServletRequest) {
        hRequest = (HttpServletRequest) request;
    }
    if (response instanceof HttpServletResponse) {
        hResponse = (HttpServletResponse) response;
    }
    // Log pre-service information
    doLog("START TIME        ", getTimestamp());
    if (hRequest == null) {
        doLog("        requestURI", NON_HTTP_REQ_MSG);
        doLog("          authType", NON_HTTP_REQ_MSG);
    } else {
        doLog("        requestURI", hRequest.getRequestURI());
        doLog("          authType", hRequest.getAuthType());
    }
    doLog(" characterEncoding", request.getCharacterEncoding());
    doLog("     contentLength", Long.toString(request.getContentLengthLong()));
    doLog("       contentType", request.getContentType());
    if (hRequest == null) {
        doLog("       contextPath", NON_HTTP_REQ_MSG);
        doLog("            cookie", NON_HTTP_REQ_MSG);
        doLog("            header", NON_HTTP_REQ_MSG);
    } else {
        doLog("       contextPath", hRequest.getContextPath());
        Cookie[] cookies = hRequest.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                doLog("            cookie", cookies[i].getName() + "=" + cookies[i].getValue());
            }
        }
        Enumeration<String> hnames = hRequest.getHeaderNames();
        while (hnames.hasMoreElements()) {
            String hname = hnames.nextElement();
            Enumeration<String> hvalues = hRequest.getHeaders(hname);
            while (hvalues.hasMoreElements()) {
                String hvalue = hvalues.nextElement();
                doLog("            header", hname + "=" + hvalue);
            }
        }
    }
    doLog("            locale", request.getLocale().toString());
    if (hRequest == null) {
        doLog("            method", NON_HTTP_REQ_MSG);
    } else {
        doLog("            method", hRequest.getMethod());
    }
    Enumeration<String> pnames = request.getParameterNames();
    while (pnames.hasMoreElements()) {
        String pname = pnames.nextElement();
        String[] pvalues = request.getParameterValues(pname);
        StringBuilder result = new StringBuilder(pname);
        result.append('=');
        for (int i = 0; i < pvalues.length; i++) {
            if (i > 0) {
                result.append(", ");
            }
            result.append(pvalues[i]);
        }
        doLog("         parameter", result.toString());
    }
    if (hRequest == null) {
        doLog("          pathInfo", NON_HTTP_REQ_MSG);
    } else {
        doLog("          pathInfo", hRequest.getPathInfo());
    }
    doLog("          protocol", request.getProtocol());
    if (hRequest == null) {
        doLog("       queryString", NON_HTTP_REQ_MSG);
    } else {
        doLog("       queryString", hRequest.getQueryString());
    }
    doLog("        remoteAddr", request.getRemoteAddr());
    doLog("        remoteHost", request.getRemoteHost());
    if (hRequest == null) {
        doLog("        remoteUser", NON_HTTP_REQ_MSG);
        doLog("requestedSessionId", NON_HTTP_REQ_MSG);
    } else {
        doLog("        remoteUser", hRequest.getRemoteUser());
        doLog("requestedSessionId", hRequest.getRequestedSessionId());
    }
    doLog("            scheme", request.getScheme());
    doLog("        serverName", request.getServerName());
    doLog("        serverPort", Integer.toString(request.getServerPort()));
    if (hRequest == null) {
        doLog("       servletPath", NON_HTTP_REQ_MSG);
    } else {
        doLog("       servletPath", hRequest.getServletPath());
    }
    doLog("          isSecure", Boolean.valueOf(request.isSecure()).toString());
    doLog("------------------", "--------------------------------------------");
    // Perform the request
    chain.doFilter(request, response);
    // Log post-service information
    doLog("------------------", "--------------------------------------------");
    if (hRequest == null) {
        doLog("          authType", NON_HTTP_REQ_MSG);
    } else {
        doLog("          authType", hRequest.getAuthType());
    }
    doLog("       contentType", response.getContentType());
    if (hResponse == null) {
        doLog("            header", NON_HTTP_RES_MSG);
    } else {
        Iterable<String> rhnames = hResponse.getHeaderNames();
        for (String rhname : rhnames) {
            Iterable<String> rhvalues = hResponse.getHeaders(rhname);
            for (String rhvalue : rhvalues) {
                doLog("            header", rhname + "=" + rhvalue);
            }
        }
    }
    if (hRequest == null) {
        doLog("        remoteUser", NON_HTTP_REQ_MSG);
    } else {
        doLog("        remoteUser", hRequest.getRemoteUser());
    }
    if (hResponse == null) {
        doLog("        remoteUser", NON_HTTP_RES_MSG);
    } else {
        doLog("            status", Integer.toString(hResponse.getStatus()));
    }
    doLog("END TIME          ", getTimestamp());
    doLog("==================", "============================================");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 47 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project tomcat by apache.

the class WebdavFixFilter method doFilter.

/**
     * Check for the broken MS WebDAV client and if detected issue a re-direct
     * that hopefully will cause the non-broken client to be used.
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
        chain.doFilter(request, response);
        return;
    }
    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    HttpServletResponse httpResponse = ((HttpServletResponse) response);
    String ua = httpRequest.getHeader("User-Agent");
    if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) {
        // No UA or starts with non MS value
        // Hope everything just works...
        chain.doFilter(request, response);
    } else if (ua.startsWith(UA_MINIDIR_5_1_2600)) {
        // XP 32-bit SP3 - needs redirect with explicit port
        httpResponse.sendRedirect(buildRedirect(httpRequest));
    } else if (ua.startsWith(UA_MINIDIR_5_2_3790)) {
        // XP 64-bit SP2
        if (!"".equals(httpRequest.getContextPath())) {
            log("XP-x64-SP2 clients only work with the root context");
        }
        // Namespace issue maybe
        // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html
        log("XP-x64-SP2 is known not to work with WebDAV Servlet");
        chain.doFilter(request, response);
    } else {
        // Don't know which MS client it is - try the redirect with an
        // explicit port in the hope that it moves the client to a different
        // WebDAV implementation that works
        httpResponse.sendRedirect(buildRedirect(httpRequest));
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 48 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project tomcat by apache.

the class ExpiresFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (response.isCommitted()) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("expiresFilter.responseAlreadyCommited", httpRequest.getRequestURL()));
            }
            chain.doFilter(request, response);
        } else {
            XHttpServletResponse xResponse = new XHttpServletResponse(httpRequest, httpResponse);
            chain.doFilter(request, xResponse);
            if (!xResponse.isWriteResponseBodyStarted()) {
                // Empty response, manually trigger
                // onBeforeWriteResponseBody()
                onBeforeWriteResponseBody(httpRequest, xResponse);
            }
        }
    } else {
        chain.doFilter(request, response);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 49 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project tomcat by apache.

the class WsFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // This filter only needs to handle WebSocket upgrade requests
    if (!sc.areEndpointsRegistered() || !UpgradeUtil.isWebSocketUpgradeRequest(request, response)) {
        chain.doFilter(request, response);
        return;
    }
    // HTTP request with an upgrade header for WebSocket present
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    // Check to see if this WebSocket implementation has a matching mapping
    String path;
    String pathInfo = req.getPathInfo();
    if (pathInfo == null) {
        path = req.getServletPath();
    } else {
        path = req.getServletPath() + pathInfo;
    }
    WsMappingResult mappingResult = sc.findMapping(path);
    if (mappingResult == null) {
        // No endpoint registered for the requested path. Let the
        // application handle it (it might redirect or forward for example)
        chain.doFilter(request, response);
        return;
    }
    UpgradeUtil.doUpgrade(sc, req, resp, mappingResult.getConfig(), mappingResult.getPathParams());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 50 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project tomcat by apache.

the class ApplicationDispatcher method invoke.

// -------------------------------------------------------- Private Methods
/**
     * Ask the resource represented by this RequestDispatcher to process
     * the associated request, and create (or append to) the associated
     * response.
     * <p>
     * <strong>IMPLEMENTATION NOTE</strong>: This implementation assumes
     * that no filters are applied to a forwarded or included resource,
     * because they were already done for the original request.
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
private void invoke(ServletRequest request, ServletResponse response, State state) throws IOException, ServletException {
    // Checking to see if the context classloader is the current context
    // classloader. If it's not, we're saving it, and setting the context
    // classloader to the Context classloader
    ClassLoader oldCCL = context.bind(false, null);
    // Initialize local variables we may need
    HttpServletResponse hresponse = state.hresponse;
    Servlet servlet = null;
    IOException ioException = null;
    ServletException servletException = null;
    RuntimeException runtimeException = null;
    boolean unavailable = false;
    // Check for the servlet being marked unavailable
    if (wrapper.isUnavailable()) {
        wrapper.getLogger().warn(sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        long available = wrapper.getAvailable();
        if ((available > 0L) && (available < Long.MAX_VALUE))
            hresponse.setDateHeader("Retry-After", available);
        hresponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sm.getString("applicationDispatcher.isUnavailable", wrapper.getName()));
        unavailable = true;
    }
    // Allocate a servlet instance to process this request
    try {
        if (!unavailable) {
            servlet = wrapper.allocate();
        }
    } catch (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), StandardWrapper.getRootCause(e));
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.allocateException", wrapper.getName()), e);
        servlet = null;
    }
    // Get the FilterChain Here
    ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
    // Call the service() method for the allocated servlet instance
    try {
        // for includes/forwards
        if ((servlet != null) && (filterChain != null)) {
            filterChain.doFilter(request, response);
        }
    // Servlet Service Method is called by the FilterChain
    } catch (ClientAbortException e) {
        ioException = e;
    } catch (IOException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        ioException = e;
    } catch (UnavailableException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        servletException = e;
        wrapper.unavailable(e);
    } catch (ServletException e) {
        Throwable rootCause = StandardWrapper.getRootCause(e);
        if (!(rootCause instanceof ClientAbortException)) {
            wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), rootCause);
        }
        servletException = e;
    } catch (RuntimeException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.serviceException", wrapper.getName()), e);
        runtimeException = e;
    }
    // Release the filter chain (if any) for this request
    try {
        if (filterChain != null)
            filterChain.release();
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("standardWrapper.releaseFilters", wrapper.getName()), e);
    // FIXME: Exception handling needs to be similar to what is in the StandardWrapperValue
    }
    // Deallocate the allocated servlet instance
    try {
        if (servlet != null) {
            wrapper.deallocate(servlet);
        }
    } catch (ServletException e) {
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = e;
    } catch (Throwable e) {
        ExceptionUtils.handleThrowable(e);
        wrapper.getLogger().error(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
        servletException = new ServletException(sm.getString("applicationDispatcher.deallocateException", wrapper.getName()), e);
    }
    // Reset the old context class loader
    context.unbind(false, oldCCL);
    // Unwrap request/response if needed
    // See Bugzilla 30949
    unwrapRequest(state);
    unwrapResponse(state);
    // Recycle request if necessary (also BZ 30949)
    recycleRequestWrapper(state);
    // Rethrow an exception if one was thrown by the invoked servlet
    if (ioException != null)
        throw ioException;
    if (servletException != null)
        throw servletException;
    if (runtimeException != null)
        throw runtimeException;
}
Also used : ServletException(javax.servlet.ServletException) UnavailableException(javax.servlet.UnavailableException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Servlet(javax.servlet.Servlet) ClientAbortException(org.apache.catalina.connector.ClientAbortException) IOException(java.io.IOException)

Aggregations

HttpServletResponse (javax.servlet.http.HttpServletResponse)1635 HttpServletRequest (javax.servlet.http.HttpServletRequest)1312 Test (org.junit.Test)705 IOException (java.io.IOException)576 ServletException (javax.servlet.ServletException)491 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)223 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)195 Request (org.eclipse.jetty.server.Request)186 HttpServlet (javax.servlet.http.HttpServlet)157 CountDownLatch (java.util.concurrent.CountDownLatch)156 FilterChain (javax.servlet.FilterChain)148 PrintWriter (java.io.PrintWriter)138 Test (org.testng.annotations.Test)127 HashMap (java.util.HashMap)106 ServletOutputStream (javax.servlet.ServletOutputStream)105 InterruptedIOException (java.io.InterruptedIOException)97 InputStream (java.io.InputStream)85 OutputStream (java.io.OutputStream)81 HttpSession (javax.servlet.http.HttpSession)75 ServletResponse (javax.servlet.ServletResponse)74