Search in sources :

Example 11 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testLargeChunkedBufferedDownstreamTransformation.

private void testLargeChunkedBufferedDownstreamTransformation(final boolean gzipped) throws Exception {
    // Tests the race between a incomplete write performed from ProxyResponseListener.onSuccess()
    // and ProxyResponseListener.onComplete() being called before the write has completed.
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            OutputStream output = response.getOutputStream();
            if (gzipped) {
                output = new GZIPOutputStream(output);
                response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
            }
            Random random = new Random();
            byte[] chunk = new byte[1024 * 1024];
            for (int i = 0; i < 16; ++i) {
                random.nextBytes(chunk);
                output.write(chunk);
                output.flush();
            }
        }
    });
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            ContentTransformer transformer = new BufferingContentTransformer();
            if (gzipped)
                transformer = new GZIPContentTransformer(transformer);
            return transformer;
        }
    });
    startClient();
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest("localhost", serverConnector.getLocalPort()).onResponseContent(new Response.ContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content) {
            // Slow down the reader so that the
            // write from the proxy gets congested.
            sleep(1);
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isSucceeded());
            Assert.assertEquals(200, result.getResponse().getStatus());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(15, TimeUnit.SECONDS));
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Random(java.util.Random) GZIPOutputStream(java.util.zip.GZIPOutputStream)

Example 12 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testDiscardUpstreamAndDownstreamKnownContentLengthGzipped.

@Test
public void testDiscardUpstreamAndDownstreamKnownContentLengthGzipped() throws Exception {
    final byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8);
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // decode input stream thru gzip
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IO.copy(new GZIPInputStream(request.getInputStream()), bos);
            // ensure decompressed is 0 length
            Assert.assertEquals(0, bos.toByteArray().length);
            response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
            response.getOutputStream().write(gzip(bytes));
        }
    });
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
            return new GZIPContentTransformer(new DiscardContentTransformer());
        }

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new GZIPContentTransformer(new DiscardContentTransformer());
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.CONTENT_ENCODING, "gzip").content(new BytesContentProvider(gzip(bytes))).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(0, response.getContent().length);
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) GZIPInputStream(java.util.zip.GZIPInputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 13 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testAfterContentTransformerClosingFilesOnClientRequestException.

@Test
public void testAfterContentTransformerClosingFilesOnClientRequestException() throws Exception {
    final Path targetTestsDir = prepareTargetTestsDir();
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            IO.copy(request.getInputStream(), IO.getNullStream());
        }
    });
    final CountDownLatch destroyLatch = new CountDownLatch(1);
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
            return new AfterContentTransformer() {

                {
                    setOverflowDirectory(targetTestsDir);
                    setMaxInputBufferSize(0);
                    setMaxOutputBufferSize(0);
                }

                @Override
                public boolean transform(Source source, Sink sink) throws IOException {
                    IO.copy(source.getInputStream(), sink.getOutputStream());
                    return true;
                }

                @Override
                public void destroy() {
                    super.destroy();
                    destroyLatch.countDown();
                }
            };
        }
    });
    long idleTimeout = 1000;
    proxyConnector.setIdleTimeout(idleTimeout);
    startClient();
    // Send only part of the content; the proxy will idle timeout.
    final byte[] data = new byte[] { 'c', 'a', 'f', 'e' };
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).content(new BytesContentProvider(data) {

        @Override
        public long getLength() {
            return data.length + 1;
        }
    }).timeout(5 * idleTimeout, TimeUnit.MILLISECONDS).send();
    Assert.assertTrue(destroyLatch.await(5 * idleTimeout, TimeUnit.MILLISECONDS));
    Assert.assertEquals(HttpStatus.REQUEST_TIMEOUT_408, response.getStatus());
}
Also used : Path(java.nio.file.Path) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Test(org.junit.Test)

Example 14 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class ConnectHandlerTest method testCONNECTAndPOSTWithContext.

@Test
public void testCONNECTAndPOSTWithContext() throws Exception {
    final String contextKey = "contextKey";
    final String contextValue = "contextValue";
    // Replace the default ProxyHandler with a subclass to test context information passing
    disposeProxy();
    proxy.setHandler(new ConnectHandler() {

        @Override
        protected boolean handleAuthentication(HttpServletRequest request, HttpServletResponse response, String address) {
            request.setAttribute(contextKey, contextValue);
            return super.handleAuthentication(request, response, address);
        }

        @Override
        protected void connectToServer(HttpServletRequest request, String host, int port, Promise<SocketChannel> promise) {
            Assert.assertEquals(contextValue, request.getAttribute(contextKey));
            super.connectToServer(request, host, port, promise);
        }

        @Override
        protected void prepareContext(HttpServletRequest request, ConcurrentMap<String, Object> context) {
            // Transfer data from the HTTP request to the connection context
            Assert.assertEquals(contextValue, request.getAttribute(contextKey));
            context.put(contextKey, request.getAttribute(contextKey));
        }

        @Override
        protected int read(EndPoint endPoint, ByteBuffer buffer, ConcurrentMap<String, Object> context) throws IOException {
            Assert.assertEquals(contextValue, context.get(contextKey));
            return super.read(endPoint, buffer, context);
        }

        @Override
        protected void write(EndPoint endPoint, ByteBuffer buffer, Callback callback, ConcurrentMap<String, Object> context) {
            Assert.assertEquals(contextValue, context.get(contextKey));
            super.write(endPoint, buffer, callback, context);
        }
    });
    proxy.start();
    String hostPort = "localhost:" + serverConnector.getLocalPort();
    String request = "" + "CONNECT " + hostPort + " HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "\r\n";
    try (Socket socket = newSocket()) {
        OutputStream output = socket.getOutputStream();
        InputStream input = socket.getInputStream();
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        // Expect 200 OK from the CONNECT request
        HttpTester.Response response = readResponse(input);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        String body = "0123456789ABCDEF";
        request = "" + "POST /echo HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "Content-Length: " + body.length() + "\r\n" + "\r\n" + body;
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = readResponse(input);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        Assert.assertEquals("POST /echo\r\n" + body, response.getContent());
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) EndPoint(org.eclipse.jetty.io.EndPoint) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) Callback(org.eclipse.jetty.util.Callback) Socket(java.net.Socket) Test(org.junit.Test)

Example 15 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class ProxyServletFailureTest method testProxyRequestExpired.

@Test
public void testProxyRequestExpired() throws Exception {
    prepareProxy();
    final long timeout = 1000;
    proxyServlet.setTimeout(timeout);
    prepareServer(new HttpServlet() {

        @Override
        protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
            if (request.getHeader("Via") != null)
                response.addHeader(PROXIED_HEADER, "true");
            try {
                TimeUnit.MILLISECONDS.sleep(2 * timeout);
            } catch (InterruptedException x) {
                throw new ServletException(x);
            }
        }
    });
    Response response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(3 * timeout, TimeUnit.MILLISECONDS).send();
    Assert.assertEquals(504, response.getStatus());
    Assert.assertFalse(response.getHeaders().containsKey(PROXIED_HEADER));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

HttpServletResponse (javax.servlet.http.HttpServletResponse)3285 HttpServletRequest (javax.servlet.http.HttpServletRequest)2624 Test (org.junit.Test)1229 IOException (java.io.IOException)873 ServletException (javax.servlet.ServletException)671 PrintWriter (java.io.PrintWriter)286 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)250 FilterChain (javax.servlet.FilterChain)243 Request (org.eclipse.jetty.server.Request)223 HashMap (java.util.HashMap)204 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)195 HttpServlet (javax.servlet.http.HttpServlet)188 CountDownLatch (java.util.concurrent.CountDownLatch)183 ServletOutputStream (javax.servlet.ServletOutputStream)183 StringWriter (java.io.StringWriter)180 Test (org.testng.annotations.Test)176 HttpSession (javax.servlet.http.HttpSession)175 ServletContext (javax.servlet.ServletContext)173 InputStream (java.io.InputStream)141 Map (java.util.Map)137