Search in sources :

Example 26 with WriteListener

use of javax.servlet.WriteListener in project quickstart by wildfly.

the class JSONPRequestFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Only HttpServletRequest requests are supported");
    }
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;
    // extract the callback method from the request query parameters
    String callback = getCallbackMethod(httpRequest);
    if (!isJSONPRequest(callback)) {
        // Request is not a JSONP request move on
        chain.doFilter(request, response);
    } else {
        // Need to check if the callback method is safe
        if (!SAFE_PRN.matcher(callback).matches()) {
            throw new ServletException("JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
        }
        // Will stream updated response
        final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        // Create a custom response wrapper to adding in the padding
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpResponse) {

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
                return new ServletOutputStream() {

                    @Override
                    public void write(int b) throws IOException {
                        byteStream.write(b);
                    }

                    @Override
                    public boolean isReady() {
                        // The stream is always ready
                        return true;
                    }

                    @Override
                    public void setWriteListener(WriteListener writeListener) {
                    // Nothing to do
                    }
                };
            }

            @Override
            public PrintWriter getWriter() throws IOException {
                return new PrintWriter(byteStream);
            }
        };
        // Process the rest of the filter chain, including the JAX-RS request
        chain.doFilter(request, responseWrapper);
        // Override response content and encoding
        response.setContentType(CONTENT_TYPE);
        response.setCharacterEncoding("UTF-8");
        // Write the padded updates to the output stream.
        response.getOutputStream().write((callback + "(").getBytes());
        response.getOutputStream().write(byteStream.toByteArray());
        response.getOutputStream().write(");".getBytes());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WriteListener(javax.servlet.WriteListener) PrintWriter(java.io.PrintWriter)

Example 27 with WriteListener

use of javax.servlet.WriteListener in project tutorials by eugenp.

the class AsyncServlet method doGet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ByteBuffer content = ByteBuffer.wrap(HEAVY_RESOURCE.getBytes(StandardCharsets.UTF_8));
    AsyncContext async = request.startAsync();
    ServletOutputStream out = response.getOutputStream();
    out.setWriteListener(new WriteListener() {

        @Override
        public void onWritePossible() throws IOException {
            while (out.isReady()) {
                if (!content.hasRemaining()) {
                    response.setStatus(200);
                    async.complete();
                    return;
                }
                out.write(content.get());
            }
        }

        @Override
        public void onError(Throwable t) {
            getServletContext().log("Async Error", t);
            async.complete();
        }
    });
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) WriteListener(javax.servlet.WriteListener)

Example 28 with WriteListener

use of javax.servlet.WriteListener in project zalenium by zalando.

the class DashboardCleanupServletTest method initMocksAndService.

@Before
public void initMocksAndService() throws IOException {
    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        private StringBuilder stringBuilder = new StringBuilder();

        @Override
        public boolean isReady() {
            System.out.println("isReady");
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
            System.out.println("setWriteListener");
        }

        @Override
        public void write(int b) {
            this.stringBuilder.append((char) b);
        }

        public String toString() {
            return stringBuilder.toString();
        }
    });
    dashboardCleanupServlet = new DashboardCleanupServlet();
    // Temporal folder for dashboard files
    TestUtils.ensureRequiredFilesExistForCleanup(temporaryFolder);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) WriteListener(javax.servlet.WriteListener) Before(org.junit.Before)

Example 29 with WriteListener

use of javax.servlet.WriteListener in project zalenium by zalando.

the class DashboardInformationServletTest method initMocksAndService.

@Before
public void initMocksAndService() throws IOException {
    request = mock(HttpServletRequest.class);
    response = mock(HttpServletResponse.class);
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        private StringBuilder stringBuilder = new StringBuilder();

        @Override
        public boolean isReady() {
            System.out.println("isReady");
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
            System.out.println("setWriteListener");
        }

        @Override
        public void write(int b) {
            this.stringBuilder.append((char) b);
        }

        public String toString() {
            return stringBuilder.toString();
        }
    });
    dashboardInformationServlet = new DashboardInformationServlet();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) WriteListener(javax.servlet.WriteListener) Before(org.junit.Before)

Example 30 with WriteListener

use of javax.servlet.WriteListener in project killbill by killbill.

the class PluginResource method serviceViaOSGIPlugin.

private Response serviceViaOSGIPlugin(final HttpServletRequest request, final InputStream inputStream, @Nullable final MultivaluedMap<String, String> formData, final HttpServletResponse response, final ServletContext servletContext, final ServletConfig servletConfig, final UriInfo uriInfo) throws ServletException, IOException {
    prepareOSGIRequest(request, servletContext, servletConfig);
    final ServletRequest req = new OSGIServletRequestWrapper(request, inputStream, formData, uriInfo.getQueryParameters());
    // The real ServletOutputStream is a HttpOutput, which we don't want to give to plugins.
    // Jooby for instance would commit the underlying HTTP channel (via ServletServletResponse#send),
    // meaning that any further headers (e.g. Profiling) that we would add would not be returned.
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final OSGIServletResponseWrapper res = new OSGIServletResponseWrapper(response, new ServletOutputStream() {

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(final WriteListener writeListener) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void write(final int b) throws IOException {
            byteArrayOutputStream.write(b);
        }
    });
    osgiServlet.service(req, res);
    if (response.getStatus() >= 400) {
        log.warn("{} responded {}", request.getPathInfo(), response.getStatus());
    }
    return Response.status(response.getStatus()).entity(new String(byteArrayOutputStream.toByteArray(), "UTF-8")).build();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener)

Aggregations

WriteListener (javax.servlet.WriteListener)31 ServletOutputStream (javax.servlet.ServletOutputStream)27 IOException (java.io.IOException)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 AsyncContext (javax.servlet.AsyncContext)12 Test (org.junit.Test)11 ServletException (javax.servlet.ServletException)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HttpServlet (javax.servlet.http.HttpServlet)6 InterruptedIOException (java.io.InterruptedIOException)5 ByteBuffer (java.nio.ByteBuffer)5 ReadListener (javax.servlet.ReadListener)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Request (org.eclipse.jetty.server.Request)4 Before (org.junit.Before)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UncheckedIOException (java.io.UncheckedIOException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3