Search in sources :

Example 1 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class ProxyServlet method service.

@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final int requestId = getRequestId(request);
    String rewrittenTarget = rewriteTarget(request);
    if (_log.isDebugEnabled()) {
        StringBuffer uri = request.getRequestURL();
        if (request.getQueryString() != null)
            uri.append("?").append(request.getQueryString());
        if (_log.isDebugEnabled())
            _log.debug("{} rewriting: {} -> {}", requestId, uri, rewrittenTarget);
    }
    if (rewrittenTarget == null) {
        onProxyRewriteFailed(request, response);
        return;
    }
    final Request proxyRequest = getHttpClient().newRequest(rewrittenTarget).method(request.getMethod()).version(HttpVersion.fromString(request.getProtocol()));
    copyRequestHeaders(request, proxyRequest);
    addProxyHeaders(request, proxyRequest);
    final AsyncContext asyncContext = request.startAsync();
    // We do not timeout the continuation, but the proxy request
    asyncContext.setTimeout(0);
    proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
    if (hasContent(request)) {
        if (expects100Continue(request)) {
            DeferredContentProvider deferred = new DeferredContentProvider();
            proxyRequest.content(deferred);
            proxyRequest.attribute(CLIENT_REQUEST_ATTRIBUTE, request);
            proxyRequest.attribute(CONTINUE_ACTION_ATTRIBUTE, (Runnable) () -> {
                try {
                    ContentProvider provider = proxyRequestContent(request, response, proxyRequest);
                    new DelegatingContentProvider(request, proxyRequest, response, provider, deferred).iterate();
                } catch (Throwable failure) {
                    onClientRequestFailure(request, proxyRequest, response, failure);
                }
            });
        } else {
            proxyRequest.content(proxyRequestContent(request, response, proxyRequest));
        }
    }
    sendProxyRequest(request, response, proxyRequest);
}
Also used : DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) AsyncContentProvider(org.eclipse.jetty.client.AsyncContentProvider) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncContext(javax.servlet.AsyncContext)

Example 2 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class ProxyServletTest method testExpect100ContinueRespond100ContinueDelayedRequestContent.

@Test
public void testExpect100ContinueRespond100ContinueDelayedRequestContent() throws Exception {
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Send the 100 Continue.
            ServletInputStream input = request.getInputStream();
            // Echo the content.
            IO.copy(input, response.getOutputStream());
        }
    });
    startProxy();
    startClient();
    byte[] content = new byte[1024];
    new Random().nextBytes(content);
    int chunk1 = content.length / 2;
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content, 0, chunk1));
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.EXPECT, HttpHeaderValue.CONTINUE.asString()).content(contentProvider).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                if (result.getResponse().getStatus() == HttpStatus.OK_200) {
                    if (Arrays.equals(content, getContent()))
                        clientLatch.countDown();
                }
            }
        }
    });
    // Wait a while and then offer more content.
    Thread.sleep(1000);
    contentProvider.offer(ByteBuffer.wrap(content, chunk1, content.length - chunk1));
    contentProvider.close();
    Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) Random(java.util.Random) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 3 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testProxyRequestHeadersNotSentUntilContent.

@Test
public void testProxyRequestHeadersNotSentUntilContent() throws Exception {
    startServer(new EchoHttpServlet());
    final CountDownLatch proxyRequestLatch = new CountDownLatch(1);
    startProxy(new AsyncMiddleManServlet() {

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

        @Override
        protected void sendProxyRequest(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest) {
            proxyRequestLatch.countDown();
            super.sendProxyRequest(clientRequest, proxyResponse, proxyRequest);
        }
    });
    startClient();
    DeferredContentProvider content = new DeferredContentProvider();
    Request request = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).content(content);
    FutureResponseListener listener = new FutureResponseListener(request);
    request.send(listener);
    // Send one chunk of content, the proxy request must not be sent.
    ByteBuffer chunk1 = ByteBuffer.allocate(1024);
    content.offer(chunk1);
    Assert.assertFalse(proxyRequestLatch.await(1, TimeUnit.SECONDS));
    // Send another chunk of content, the proxy request must not be sent.
    ByteBuffer chunk2 = ByteBuffer.allocate(512);
    content.offer(chunk2);
    Assert.assertFalse(proxyRequestLatch.await(1, TimeUnit.SECONDS));
    // Finish the content, request must be sent.
    content.close();
    Assert.assertTrue(proxyRequestLatch.await(1, TimeUnit.SECONDS));
    ContentResponse response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertEquals(chunk1.capacity() + chunk2.capacity(), response.getContent().length);
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) HttpServletRequest(javax.servlet.http.HttpServletRequest) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) FutureResponseListener(org.eclipse.jetty.client.util.FutureResponseListener) Test(org.junit.Test)

Example 4 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class AsyncMiddleManServletTest method testClientRequestReadFailsOnSecondRead.

@Test
public void testClientRequestReadFailsOnSecondRead() throws Exception {
    try (StacklessLogging scope = new StacklessLogging(HttpChannel.class)) {
        startServer(new EchoHttpServlet());
        startProxy(new AsyncMiddleManServlet() {

            private int count;

            @Override
            protected int readClientRequestContent(ServletInputStream input, byte[] buffer) throws IOException {
                if (++count < 2)
                    return super.readClientRequestContent(input, buffer);
                else
                    throw new IOException("explicitly_thrown_by_test");
            }
        });
        startClient();
        final CountDownLatch latch = new CountDownLatch(1);
        DeferredContentProvider content = new DeferredContentProvider();
        client.newRequest("localhost", serverConnector.getLocalPort()).content(content).send(new Response.CompleteListener() {

            @Override
            public void onComplete(Result result) {
                if (result.getResponse().getStatus() == 502)
                    latch.countDown();
            }
        });
        content.offer(ByteBuffer.allocate(512));
        sleep(1000);
        content.offer(ByteBuffer.allocate(512));
        content.close();
        Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    }
}
Also used : RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Result(org.eclipse.jetty.client.api.Result) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Test(org.junit.Test)

Example 5 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class HttpClientAuthenticationTest method test_RequestFailsAfterResponse.

@Test
public void test_RequestFailsAfterResponse() throws Exception {
    startBasic(new EmptyServerHandler());
    AuthenticationStore authenticationStore = client.getAuthenticationStore();
    URI uri = URI.create(scheme + "://localhost:" + connector.getLocalPort());
    BasicAuthentication authentication = new BasicAuthentication(uri, realm, "basic", "basic");
    authenticationStore.addAuthentication(authentication);
    CountDownLatch successLatch = new CountDownLatch(1);
    CountDownLatch resultLatch = new CountDownLatch(1);
    DeferredContentProvider content = new DeferredContentProvider();
    Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure").content(content).onResponseSuccess(response -> successLatch.countDown());
    request.send(result -> {
        if (result.isFailed() && result.getResponseFailure() == null)
            resultLatch.countDown();
    });
    // Send some content to make sure the request is dispatched on the server.
    content.offer(ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8)));
    // Wait for the response to arrive to
    // the authentication protocol handler.
    Thread.sleep(1000);
    // Trigger request failure.
    request.abort(new Exception());
    // Verify that the response was successful, it's the request that failed.
    Assert.assertTrue(successLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) BasicAuthentication(org.eclipse.jetty.client.util.BasicAuthentication) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AuthenticationStore(org.eclipse.jetty.client.api.AuthenticationStore) Test(org.junit.Test)

Aggregations

DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)46 Test (org.junit.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)35 HttpServletResponse (javax.servlet.http.HttpServletResponse)34 IOException (java.io.IOException)33 ServletException (javax.servlet.ServletException)28 ServletInputStream (javax.servlet.ServletInputStream)18 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)18 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)17 Request (org.eclipse.jetty.server.Request)16 Result (org.eclipse.jetty.client.api.Result)15 InterruptedIOException (java.io.InterruptedIOException)14 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)12 AsyncContext (javax.servlet.AsyncContext)11 Request (org.eclipse.jetty.client.api.Request)11 ByteBuffer (java.nio.ByteBuffer)10 Response (org.eclipse.jetty.client.api.Response)9 StacklessLogging (org.eclipse.jetty.util.log.StacklessLogging)8 ReadListener (javax.servlet.ReadListener)7