Search in sources :

Example 11 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project lucene-solr by apache.

the class HadoopAuthPlugin method doAuthenticate.

@Override
public boolean doAuthenticate(ServletRequest request, ServletResponse response, FilterChain filterChain) throws Exception {
    final HttpServletResponse frsp = (HttpServletResponse) response;
    if (TRACE_HTTP) {
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("----------HTTP Request---------");
        log.info("{} : {}", req.getMethod(), req.getRequestURI());
        log.info("Query : {}", req.getQueryString());
        log.info("Headers :");
        Enumeration<String> headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String name = headers.nextElement();
            Enumeration<String> hvals = req.getHeaders(name);
            while (hvals.hasMoreElements()) {
                log.info("{} : {}", name, hvals.nextElement());
            }
        }
        log.info("-------------------------------");
    }
    // Workaround until HADOOP-13346 is fixed.
    HttpServletResponse rspCloseShield = new HttpServletResponseWrapper(frsp) {

        @SuppressForbidden(reason = "Hadoop DelegationTokenAuthenticationFilter uses response writer, this" + "is providing a CloseShield on top of that")
        @Override
        public PrintWriter getWriter() throws IOException {
            final PrintWriter pw = new PrintWriterWrapper(frsp.getWriter()) {

                @Override
                public void close() {
                }

                ;
            };
            return pw;
        }
    };
    authFilter.doFilter(request, rspCloseShield, filterChain);
    if (TRACE_HTTP) {
        log.info("----------HTTP Response---------");
        log.info("Status : {}", frsp.getStatus());
        log.info("Headers :");
        for (String name : frsp.getHeaderNames()) {
            for (String value : frsp.getHeaders(name)) {
                log.info("{} : {}", name, value);
            }
        }
        log.info("-------------------------------");
    }
    if (authFilter instanceof HadoopAuthFilter) {
        // delegation token mgmt.
        String requestContinuesAttr = (String) request.getAttribute(REQUEST_CONTINUES_ATTR);
        if (requestContinuesAttr == null) {
            log.warn("Could not find " + REQUEST_CONTINUES_ATTR);
            return false;
        } else {
            return Boolean.parseBoolean(requestContinuesAttr);
        }
    }
    return true;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) PrintWriter(java.io.PrintWriter)

Example 12 with HttpServletResponseWrapper

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

the class Response method setResponse.

/**
     * Set a wrapped HttpServletResponse to pass to the application. Components
     * wishing to wrap the response should obtain the response via
     * {@link #getResponse()}, wrap it and then call this method with the
     * wrapped response.
     *
     * @param applicationResponse The wrapped response to pass to the
     *        application
     */
public void setResponse(HttpServletResponse applicationResponse) {
    // Check the wrapper wraps this request
    ServletResponse r = applicationResponse;
    while (r instanceof HttpServletResponseWrapper) {
        r = ((HttpServletResponseWrapper) r).getResponse();
    }
    if (r != facade) {
        throw new IllegalArgumentException(sm.getString("response.illegalWrap"));
    }
    this.applicationResponse = applicationResponse;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper)

Example 13 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project blueocean-plugin by jenkinsci.

the class ResourceCacheControl method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    // it matches what we're looking for.
    if (request instanceof HttpServletRequest) {
        if (isCacheableResourceRequest((HttpServletRequest) request)) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //
            // Set the expiry to one year.
            //
            // Note that this does NOT mean that the browser will never send a request
            // for these resources. If you click reload in the browser (def in Chrome) it will
            // send an If-Modified-Since request to the server (at a minimum), which means you at
            // least have the request overhead even if it results in a 304 response. Setting the
            // Cache-Control header helps for normal browsing (clicking on links, bookmarks etc),
            // in which case the local cache is fully used (no If-Modified-Since requests for
            // non-stale resources).
            //
            httpServletResponse.setHeader("Cache-Control", "public, max-age=31536000");
            response = new HttpServletResponseWrapper(httpServletResponse) {

                @Override
                public void setHeader(String name, String value) {
                    // Lets eliminate it anyway in case a browser/intermediary doesn't comply.
                    if (!name.equalsIgnoreCase("Expires")) {
                        super.setHeader(name, value);
                    }
                }
            };
        }
    }
    // continue to execute the filer chain as normal
    chain.doFilter(request, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 14 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project jersey by jersey.

the class JspTemplateProcessor method writeTo.

@Override
public void writeTo(final String templateReference, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
    if (!(viewable instanceof ResolvedViewable)) {
        // This should not happen with default MVC message body writer implementation
        throw new IllegalArgumentException(LocalizationMessages.ERROR_VIEWABLE_INCORRECT_INSTANCE());
    }
    // SPI could supply instance of ResolvedViewable but we would like to keep the backward
    // compatibility, so the cast is here.
    final ResolvedViewable resolvedViewable = (ResolvedViewable) viewable;
    final TracingLogger tracingLogger = TracingLogger.getInstance(containerRequestProvider.get().getPropertiesDelegate());
    if (tracingLogger.isLogEnabled(MvcJspEvent.JSP_FORWARD)) {
        tracingLogger.log(MvcJspEvent.JSP_FORWARD, templateReference, resolvedViewable.getModel());
    }
    final RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(templateReference);
    if (dispatcher == null) {
        throw new ContainerException(LocalizationMessages.NO_REQUEST_DISPATCHER_FOR_RESOLVED_PATH(templateReference));
    }
    final RequestDispatcher wrapper = new RequestDispatcherWrapper(dispatcher, getBasePath(), resolvedViewable);
    // OutputStream and Writer for HttpServletResponseWrapper.
    final ServletOutputStream responseStream = new ServletOutputStream() {

        @Override
        public void write(final int b) throws IOException {
            out.write(b);
        }
    };
    final PrintWriter responseWriter = new PrintWriter(new OutputStreamWriter(responseStream, getEncoding()));
    try {
        wrapper.forward(requestProviderRef.get().get(), new HttpServletResponseWrapper(responseProviderRef.get().get()) {

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
                return responseStream;
            }

            @Override
            public PrintWriter getWriter() throws IOException {
                return responseWriter;
            }
        });
    } catch (final Exception e) {
        throw new ContainerException(e);
    } finally {
        responseWriter.flush();
    }
}
Also used : ResolvedViewable(org.glassfish.jersey.server.mvc.spi.ResolvedViewable) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) TracingLogger(org.glassfish.jersey.message.internal.TracingLogger) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) IOException(java.io.IOException) ContainerException(org.glassfish.jersey.server.ContainerException) ContainerException(org.glassfish.jersey.server.ContainerException) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter)

Example 15 with HttpServletResponseWrapper

use of javax.servlet.http.HttpServletResponseWrapper in project jodd by oblac.

the class ByteArrayResponseWrapperTest method testWrite.

@Test
public void testWrite() throws IOException {
    HttpServletResponseWrapper rw = mock(HttpServletResponseWrapper.class);
    ServletOutputStream os = mock(ServletOutputStream.class);
    when(rw.getOutputStream()).thenReturn(os);
    ByteArrayResponseWrapper wrappedResponse = new ByteArrayResponseWrapper(rw);
    wrappedResponse.getWriter().print("first");
    assertEquals(5, wrappedResponse.getBufferSize());
    byte[] bytes = wrappedResponse.toByteArray();
    assertEquals("first", new String(bytes));
    ServletOutputStream sos = wrappedResponse.getOutputStream();
    sos.print(173);
    sos.print("WOW");
    bytes = wrappedResponse.toByteArray();
    assertEquals("first173WOW", new String(bytes));
    PrintWriter pw = wrappedResponse.getWriter();
    pw.write("YYZ");
    pw.flush();
    bytes = wrappedResponse.toByteArray();
    assertEquals("first173WOWYYZ", new String(bytes));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Aggregations

HttpServletResponseWrapper (javax.servlet.http.HttpServletResponseWrapper)34 HttpServletResponse (javax.servlet.http.HttpServletResponse)29 ServletResponse (javax.servlet.ServletResponse)23 IOException (java.io.IOException)22 ServletRequest (javax.servlet.ServletRequest)20 Test (org.junit.Test)20 ServletException (javax.servlet.ServletException)19 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)15 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)15 MockFilterChain (org.springframework.mock.web.MockFilterChain)14 NestedServletException (org.springframework.web.util.NestedServletException)14 ErrorPage (org.springframework.boot.web.server.ErrorPage)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 HttpServletRequestWrapper (javax.servlet.http.HttpServletRequestWrapper)8 PrintWriter (java.io.PrintWriter)6 ServletOutputStream (javax.servlet.ServletOutputStream)5 Provider (com.google.inject.Provider)4 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)4 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)4 Filter (javax.servlet.Filter)4