Search in sources :

Example 21 with HttpServletResponse

use of jakarta.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 (Cookie cookie : cookies) {
                doLog("            cookie", cookie.getName() + "=" + cookie.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("            status", NON_HTTP_RES_MSG);
    } else {
        doLog("            status", Integer.toString(hResponse.getStatus()));
    }
    doLog("END TIME          ", getTimestamp());
    doLog("==================", "============================================");
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Cookie(jakarta.servlet.http.Cookie) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 22 with HttpServletResponse

use of jakarta.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 (!httpRequest.getContextPath().isEmpty()) {
            getServletContext().log(sm.getString("webDavFilter.xpRootContext"));
        }
        // Namespace issue maybe
        // see http://greenbytes.de/tech/webdav/webdav-redirector-list.html
        getServletContext().log(sm.getString("webDavFilter.xpProblem"));
        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(jakarta.servlet.http.HttpServletRequest) HttpServletResponse(jakarta.servlet.http.HttpServletResponse)

Example 23 with HttpServletResponse

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

the class SSIFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // cast once
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // setup to capture output
    ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
    ResponseIncludeWrapper responseIncludeWrapper = new ResponseIncludeWrapper(res, basos);
    // process remainder of filter chain
    chain.doFilter(req, responseIncludeWrapper);
    // we can't assume the chain flushed its output
    responseIncludeWrapper.flushOutputStreamOrWriter();
    byte[] bytes = basos.toByteArray();
    // get content type
    String contentType = responseIncludeWrapper.getContentType();
    // is this an allowed type for SSI processing?
    if (contentType != null && contentTypeRegEx.matcher(contentType).matches()) {
        String encoding = res.getCharacterEncoding();
        // set up SSI processing
        SSIExternalResolver ssiExternalResolver = new SSIServletExternalResolver(getServletContext(), req, res, isVirtualWebappRelative, debug, encoding);
        SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver, debug, allowExec);
        // prepare readers/writers
        Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), encoding);
        ByteArrayOutputStream ssiout = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(ssiout, encoding));
        // do SSI processing
        long lastModified = ssiProcessor.process(reader, responseIncludeWrapper.getLastModified(), writer);
        // set output bytes
        writer.flush();
        bytes = ssiout.toByteArray();
        // override headers
        if (expires != null) {
            res.setDateHeader("expires", (new java.util.Date()).getTime() + expires.longValue() * 1000);
        }
        if (lastModified > 0) {
            res.setDateHeader("last-modified", lastModified);
        }
        res.setContentLength(bytes.length);
        Matcher shtmlMatcher = shtmlRegEx.matcher(responseIncludeWrapper.getContentType());
        if (shtmlMatcher.matches()) {
            // Convert SHTML mime type to ordinary HTML mime type but preserve
            // encoding, if any.
            String enc = shtmlMatcher.group(1);
            res.setContentType("text/html" + ((enc != null) ? enc : ""));
        }
    }
    // write output
    OutputStream out = null;
    try {
        out = res.getOutputStream();
    } catch (IllegalStateException e) {
    // Ignore, will try to use a writer
    }
    if (out == null) {
        res.getWriter().write(new String(bytes));
    } else {
        out.write(bytes);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 24 with HttpServletResponse

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

the class TestExpiresFilter method testUseContentTypeExpiresConfiguration.

@Test
public void testUseContentTypeExpiresConfiguration() throws Exception {
    HttpServlet servlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/xml; charset=utf-8");
            response.getWriter().print("Hello world");
        }
    };
    validate(servlet, Integer.valueOf(3 * 60));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpServlet(jakarta.servlet.http.HttpServlet) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 25 with HttpServletResponse

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

the class TestExpiresFilter method testUseContentTypeWithoutCharsetExpiresConfiguration.

@Test
public void testUseContentTypeWithoutCharsetExpiresConfiguration() throws Exception {
    HttpServlet servlet = new HttpServlet() {

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/xml; charset=iso-8859-1");
            response.getWriter().print("Hello world");
        }
    };
    validate(servlet, Integer.valueOf(5 * 60));
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpServlet(jakarta.servlet.http.HttpServlet) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

HttpServletResponse (jakarta.servlet.http.HttpServletResponse)118 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)76 Test (org.junit.jupiter.api.Test)47 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)34 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)31 FilterChain (jakarta.servlet.FilterChain)22 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)18 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)16 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)15 ServletException (jakarta.servlet.ServletException)14 StandardCharsets (java.nio.charset.StandardCharsets)14 HttpServlet (jakarta.servlet.http.HttpServlet)13 IOException (java.io.IOException)12 HashMap (java.util.HashMap)12 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)10 Test (org.junit.Test)10 Authentication (org.springframework.security.core.Authentication)10 FileCopyUtils (org.springframework.util.FileCopyUtils)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 Collections (java.util.Collections)7