Search in sources :

Example 41 with Result

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

the class HttpClientContinueTest method test_Expect100Continue_WithInitialAndDeferredContent_Respond100Continue.

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

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            // Send 100-Continue and echo the content
            IO.copy(request.getInputStream(), response.getOutputStream());
        }
    });
    final byte[] chunk1 = new byte[] { 0, 1, 2, 3 };
    final byte[] chunk2 = new byte[] { 4, 5, 6, 7 };
    final byte[] data = new byte[chunk1.length + chunk2.length];
    System.arraycopy(chunk1, 0, data, 0, chunk1.length);
    System.arraycopy(chunk2, 0, data, chunk1.length, chunk2.length);
    final CountDownLatch latch = new CountDownLatch(1);
    DeferredContentProvider content = new DeferredContentProvider(ByteBuffer.wrap(chunk1));
    client.newRequest(newURI()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(content).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertArrayEquals(data, getContent());
            latch.countDown();
        }
    });
    Thread.sleep(1000);
    content.offer(ByteBuffer.wrap(chunk2));
    content.close();
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) 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) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

Example 42 with Result

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

the class HttpClientContinueTest method test_Expect100Continue_WithContent_RespondError.

private void test_Expect100Continue_WithContent_RespondError(final int error) throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            response.sendError(error);
        }
    });
    byte[] content1 = new byte[10240];
    byte[] content2 = new byte[16384];
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest(newURI()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(new BytesContentProvider(content1, content2)).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isFailed());
            Assert.assertNotNull(result.getRequestFailure());
            Assert.assertNull(result.getResponseFailure());
            byte[] content = getContent();
            Assert.assertNotNull(content);
            Assert.assertTrue(content.length > 0);
            Assert.assertEquals(error, result.getResponse().getStatus());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Example 43 with Result

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

the class HttpClientStreamTest method testUploadWithDeferredContentProviderRacingWithIterator.

@Test
public void testUploadWithDeferredContentProviderRacingWithIterator() throws Exception {
    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);
            IO.copy(request.getInputStream(), response.getOutputStream());
        }
    });
    final CountDownLatch latch = new CountDownLatch(1);
    final byte[] data = new byte[512];
    final AtomicReference<DeferredContentProvider> contentRef = new AtomicReference<>();
    final DeferredContentProvider content = new DeferredContentProvider() {

        @Override
        public Iterator<ByteBuffer> iterator() {
            return new Iterator<ByteBuffer>() {

                // Data for the deferred content iterator:
                // [0] => deferred
                // [1] => deferred
                // [2] => data
                private final byte[][] iteratorData = new byte[3][];

                private final AtomicInteger index = new AtomicInteger();

                {
                    iteratorData[0] = null;
                    iteratorData[1] = null;
                    iteratorData[2] = data;
                }

                @Override
                public boolean hasNext() {
                    return index.get() < iteratorData.length;
                }

                @Override
                public ByteBuffer next() {
                    byte[] chunk = iteratorData[index.getAndIncrement()];
                    ByteBuffer result = chunk == null ? null : ByteBuffer.wrap(chunk);
                    if (index.get() < iteratorData.length) {
                        contentRef.get().offer(result == null ? BufferUtil.EMPTY_BUFFER : result);
                        contentRef.get().close();
                    }
                    return result;
                }

                @Override
                public void remove() {
                }
            };
        }
    };
    contentRef.set(content);
    client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).content(content).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded() && result.getResponse().getStatus() == 200 && Arrays.equals(data, getContent()))
                latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) InterruptedIOException(java.io.InterruptedIOException) 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Iterator(java.util.Iterator) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 44 with Result

use of org.eclipse.jetty.client.api.Result in project jersey by jersey.

the class JettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback callback) {
    final Request jettyRequest = translateRequest(jerseyRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest);
    final ContentProvider entity = getStreamProvider(jerseyRequest);
    if (entity != null) {
        jettyRequest.content(entity);
    }
    final AtomicBoolean callbackInvoked = new AtomicBoolean(false);
    final Throwable failure;
    try {
        final CompletableFuture<ClientResponse> responseFuture = new CompletableFuture<ClientResponse>().whenComplete((clientResponse, throwable) -> {
            if (throwable != null && throwable instanceof CancellationException) {
                // take care of future cancellation
                jettyRequest.abort(throwable);
            }
        });
        final AtomicReference<ClientResponse> jerseyResponse = new AtomicReference<>();
        final ByteBufferInputStream entityStream = new ByteBufferInputStream();
        jettyRequest.send(new Response.Listener.Adapter() {

            @Override
            public void onHeaders(final Response jettyResponse) {
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName());
                if (responseFuture.isDone()) {
                    if (!callbackInvoked.compareAndSet(false, true)) {
                        return;
                    }
                }
                final ClientResponse response = translateResponse(jerseyRequest, jettyResponse, entityStream);
                jerseyResponse.set(response);
                callback.response(response);
            }

            @Override
            public void onContent(final Response jettyResponse, final ByteBuffer content) {
                try {
                    entityStream.put(content);
                } catch (final InterruptedException ex) {
                    final ProcessingException pe = new ProcessingException(ex);
                    entityStream.closeQueue(pe);
                    // try to complete the future with an exception
                    responseFuture.completeExceptionally(pe);
                    Thread.currentThread().interrupt();
                }
            }

            @Override
            public void onComplete(final Result result) {
                entityStream.closeQueue();
                // try to complete the future with the response only once truly done
                responseFuture.complete(jerseyResponse.get());
            }

            @Override
            public void onFailure(final Response response, final Throwable t) {
                entityStream.closeQueue(t);
                // try to complete the future with an exception
                responseFuture.completeExceptionally(t);
                if (callbackInvoked.compareAndSet(false, true)) {
                    callback.failure(t);
                }
            }
        });
        processContent(jerseyRequest, entity);
        return responseFuture;
    } catch (final Throwable t) {
        failure = t;
    }
    if (callbackInvoked.compareAndSet(false, true)) {
        callback.failure(failure);
    }
    CompletableFuture<Object> future = new CompletableFuture<>();
    future.completeExceptionally(failure);
    return future;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) OutputStreamContentProvider(org.eclipse.jetty.client.util.OutputStreamContentProvider) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Request(org.eclipse.jetty.client.api.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(org.eclipse.jetty.client.api.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) CancellationException(java.util.concurrent.CancellationException) ProcessingException(javax.ws.rs.ProcessingException)

Example 45 with Result

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

the class ExternalSiteTest method testExternalSite.

@Test
public void testExternalSite() throws Exception {
    String host = "wikipedia.org";
    int port = 80;
    // Verify that we have connectivity
    assumeCanConnectTo(host, port);
    final CountDownLatch latch1 = new CountDownLatch(1);
    client.newRequest(host, port).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            if (!result.isFailed() && result.getResponse().getStatus() == 200)
                latch1.countDown();
        }
    });
    Assert.assertTrue(latch1.await(10, TimeUnit.SECONDS));
    // Try again the same URI, but without specifying the port
    final CountDownLatch latch2 = new CountDownLatch(1);
    client.newRequest("http://" + host).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isSucceeded());
            Assert.assertEquals(200, result.getResponse().getStatus());
            latch2.countDown();
        }
    });
    Assert.assertTrue(latch2.await(10, TimeUnit.SECONDS));
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) CountDownLatch(java.util.concurrent.CountDownLatch) Result(org.eclipse.jetty.client.api.Result) Test(org.junit.Test)

Aggregations

Result (org.eclipse.jetty.client.api.Result)100 Test (org.junit.Test)80 CountDownLatch (java.util.concurrent.CountDownLatch)79 HttpServletResponse (javax.servlet.http.HttpServletResponse)74 HttpServletRequest (javax.servlet.http.HttpServletRequest)66 Response (org.eclipse.jetty.client.api.Response)62 IOException (java.io.IOException)60 ServletException (javax.servlet.ServletException)56 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)44 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)41 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)39 Request (org.eclipse.jetty.client.api.Request)31 ByteBuffer (java.nio.ByteBuffer)29 Request (org.eclipse.jetty.server.Request)27 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)24 InterruptedIOException (java.io.InterruptedIOException)21 ServletOutputStream (javax.servlet.ServletOutputStream)20 Slow (org.eclipse.jetty.toolchain.test.annotation.Slow)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)16 BytesContentProvider (org.eclipse.jetty.client.util.BytesContentProvider)16