Search in sources :

Example 91 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientTest method testSmallAsyncContent.

@Test
public void testSmallAsyncContent() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            ServletOutputStream output = response.getOutputStream();
            output.write(65);
            output.flush();
            output.write(66);
        }
    });
    final AtomicInteger contentCount = new AtomicInteger();
    final AtomicReference<Callback> callbackRef = new AtomicReference<>();
    final AtomicReference<CountDownLatch> contentLatch = new AtomicReference<>(new CountDownLatch(1));
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseContentAsync(new Response.AsyncContentListener() {

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            contentCount.incrementAndGet();
            callbackRef.set(callback);
            contentLatch.get().countDown();
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            completeLatch.countDown();
        }
    });
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    Callback callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(1, contentCount.get());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(contentLatch.get().await(5, TimeUnit.SECONDS));
    callback = callbackRef.get();
    // Wait a while to be sure that the parsing does not proceed.
    TimeUnit.MILLISECONDS.sleep(1000);
    Assert.assertEquals(2, contentCount.get());
    Assert.assertEquals(1, completeLatch.getCount());
    // Succeed the content callback to proceed with parsing.
    callbackRef.set(null);
    contentLatch.set(new CountDownLatch(1));
    callback.succeeded();
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(2, contentCount.get());
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) 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) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 92 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientTest method testLongPollIsAbortedWhenClientIsStopped.

@Test
public void testLongPollIsAbortedWhenClientIsStopped() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            request.startAsync();
            latch.countDown();
        }
    });
    final CountDownLatch completeLatch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isFailed())
                completeLatch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    // Stop the client, the complete listener must be invoked.
    client.stop();
    Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) 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) Test(org.junit.Test)

Example 93 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class HttpClientTest method testGETResponseWithoutContent.

@Test
public void testGETResponseWithoutContent() throws Exception {
    start(new EmptyServerHandler());
    for (int i = 0; i < 2; ++i) {
        Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort());
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatus());
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 94 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testAfterContentTransformerOverflowingToDisk.

@Test
public void testAfterContentTransformerOverflowingToDisk() throws Exception {
    // Make sure the temporary directory we use exists and it's empty.
    final Path targetTestsDir = prepareTargetTestsDir();
    final String key0 = "id";
    long value0 = 1;
    final String key1 = "channel";
    String value1 = "foo";
    final String json = "{ \"" + key0 + "\":" + value0 + ", \"" + key1 + "\":\"" + value1 + "\" }";
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
        }
    });
    final String inputPrefix = "in_";
    final String outputPrefix = "out_";
    final String key2 = "c";
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            AfterContentTransformer transformer = new AfterContentTransformer() {

                @Override
                public boolean transform(Source source, Sink sink) throws IOException {
                    InputStream input = source.getInputStream();
                    @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) JSON.parse(new InputStreamReader(input, "UTF-8"));
                    // Transform the object.
                    obj.put(key2, obj.remove(key1));
                    try (OutputStream output = sink.getOutputStream()) {
                        output.write(JSON.toString(obj).getBytes(StandardCharsets.UTF_8));
                        return true;
                    }
                }
            };
            transformer.setOverflowDirectory(targetTestsDir);
            int maxBufferSize = json.length() / 4;
            transformer.setMaxInputBufferSize(maxBufferSize);
            transformer.setInputFilePrefix(inputPrefix);
            transformer.setMaxOutputBufferSize(maxBufferSize);
            transformer.setOutputFilePrefix(outputPrefix);
            return transformer;
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) JSON.parse(response.getContentAsString());
    Assert.assertNotNull(obj);
    Assert.assertEquals(2, obj.size());
    Assert.assertEquals(value0, obj.get(key0));
    Assert.assertEquals(value1, obj.get(key2));
    // Make sure the files do not exist.
    try (DirectoryStream<Path> paths = Files.newDirectoryStream(targetTestsDir, inputPrefix + "*.*")) {
        Assert.assertFalse(paths.iterator().hasNext());
    }
    // File deletion is delayed on windows, testing for deletion is not going to work
    if (!OS.IS_WINDOWS) {
        try (DirectoryStream<Path> paths = Files.newDirectoryStream(targetTestsDir, outputPrefix + "*.*")) {
            Assert.assertFalse(paths.iterator().hasNext());
        }
    }
}
Also used : Path(java.nio.file.Path) InputStreamReader(java.io.InputStreamReader) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) 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) 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) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 95 with Response

use of org.eclipse.jetty.client.api.Response in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testTransformUpstreamAndDownstreamKnownContentLengthGzipped.

@Test
public void testTransformUpstreamAndDownstreamKnownContentLengthGzipped() throws Exception {
    String data = "<a href=\"http://google.com\">Google</a>";
    byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
    startServer(new EchoHttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
            super.service(request, response);
        }
    });
    startProxy(new AsyncMiddleManServlet() {

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

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new GZIPContentTransformer(new HrefTransformer.Server());
        }
    });
    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.assertArrayEquals(bytes, response.getContent());
}
Also used : Server(org.eclipse.jetty.server.Server) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) 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) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) 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) HttpClient(org.eclipse.jetty.client.HttpClient) Test(org.junit.Test)

Aggregations

Response (org.eclipse.jetty.client.api.Response)113 Test (org.junit.Test)90 HttpServletResponse (javax.servlet.http.HttpServletResponse)89 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)84 IOException (java.io.IOException)77 HttpServletRequest (javax.servlet.http.HttpServletRequest)70 ServletException (javax.servlet.ServletException)68 CountDownLatch (java.util.concurrent.CountDownLatch)54 Result (org.eclipse.jetty.client.api.Result)51 InputStream (java.io.InputStream)36 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)36 ByteBuffer (java.nio.ByteBuffer)34 ServletOutputStream (javax.servlet.ServletOutputStream)34 Request (org.eclipse.jetty.client.api.Request)31 InterruptedIOException (java.io.InterruptedIOException)29 HttpServlet (javax.servlet.http.HttpServlet)29 InputStreamResponseListener (org.eclipse.jetty.client.util.InputStreamResponseListener)29 Request (org.eclipse.jetty.server.Request)26 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)23 Callback (org.eclipse.jetty.util.Callback)22