Search in sources :

Example 1 with Request

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

the class HttpRedirector method redirect.

/**
     * Redirects the given {@code response}, blocking until the redirect is complete.
     *
     * @param request the original request that triggered the redirect
     * @param response the response to the original request
     * @return a {@link Result} object containing the request to the redirected location and its response
     * @throws InterruptedException if the thread is interrupted while waiting for the redirect to complete
     * @throws ExecutionException if the redirect failed
     * @see #redirect(Request, Response, Response.CompleteListener)
     */
public Result redirect(Request request, Response response) throws InterruptedException, ExecutionException {
    final AtomicReference<Result> resultRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);
    Request redirect = redirect(request, response, new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            resultRef.set(new Result(result.getRequest(), result.getRequestFailure(), new HttpContentResponse(result.getResponse(), getContent(), getMediaType(), getEncoding()), result.getResponseFailure()));
            latch.countDown();
        }
    });
    try {
        latch.await();
        Result result = resultRef.get();
        if (result.isFailed())
            throw new ExecutionException(result.getFailure());
        return result;
    } catch (InterruptedException x) {
        // If the application interrupts, we need to abort the redirect
        redirect.abort(x);
        throw x;
    }
}
Also used : Request(org.eclipse.jetty.client.api.Request) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutionException(java.util.concurrent.ExecutionException) Result(org.eclipse.jetty.client.api.Result) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Example 2 with Request

use of org.eclipse.jetty.client.api.Request 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 3 with Request

use of org.eclipse.jetty.client.api.Request 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 4 with Request

use of org.eclipse.jetty.client.api.Request 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 5 with Request

use of org.eclipse.jetty.client.api.Request 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)

Aggregations

Request (org.eclipse.jetty.client.api.Request)259 Test (org.junit.Test)145 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)132 HttpServletRequest (javax.servlet.http.HttpServletRequest)123 IOException (java.io.IOException)71 HttpServletResponse (javax.servlet.http.HttpServletResponse)65 CountDownLatch (java.util.concurrent.CountDownLatch)58 HttpClient (org.eclipse.jetty.client.HttpClient)58 ServletException (javax.servlet.ServletException)55 Response (org.eclipse.jetty.client.api.Response)45 InputStream (java.io.InputStream)39 Result (org.eclipse.jetty.client.api.Result)38 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)35 URI (java.net.URI)34 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)30 ExecutionException (java.util.concurrent.ExecutionException)28 FutureResponseListener (org.eclipse.jetty.client.util.FutureResponseListener)28 ByteBuffer (java.nio.ByteBuffer)27 SalesforceException (org.apache.camel.component.salesforce.api.SalesforceException)26 Connection (org.eclipse.jetty.client.api.Connection)26