Search in sources :

Example 46 with Response

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

the class HttpClientStreamTest method testInputStreamResponseListenerClosedBeforeReading.

@Test(expected = AsynchronousCloseException.class)
public void testInputStreamResponseListenerClosedBeforeReading() 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());
        }
    });
    InputStreamResponseListener listener = new InputStreamResponseListener();
    InputStream stream = listener.getInputStream();
    // Close the stream immediately.
    stream.close();
    client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).content(new BytesContentProvider(new byte[] { 0, 1, 2, 3 })).send(listener);
    Response response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(200, response.getStatus());
    // Throws
    stream.read();
}
Also used : Request(org.eclipse.jetty.server.Request) InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) 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 47 with Response

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

the class HttpClientStreamTest method testDownloadWithCloseBeforeContent.

@Test(expected = AsynchronousCloseException.class)
public void testDownloadWithCloseBeforeContent() throws Exception {
    final byte[] data = new byte[128 * 1024];
    byte value = 3;
    Arrays.fill(data, value);
    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);
            response.flushBuffer();
            try {
                Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
            } catch (InterruptedException e) {
                throw new InterruptedIOException();
            }
            response.getOutputStream().write(data);
        }
    });
    InputStreamResponseListener listener = new InputStreamResponseListener();
    client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).send(listener);
    Response response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertNotNull(response);
    Assert.assertEquals(200, response.getStatus());
    InputStream input = listener.getInputStream();
    Assert.assertNotNull(input);
    input.close();
    latch.countDown();
    // Throws
    input.read();
}
Also used : Request(org.eclipse.jetty.server.Request) InterruptedIOException(java.io.InterruptedIOException) InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) 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 48 with Response

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

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

the class JettyContentExchange9 method send.

public void send(HttpClient client) throws IOException {
    org.eclipse.jetty.client.api.Request.Listener listener = new Request.Listener.Adapter() {

        @Override
        public void onSuccess(Request request) {
            onRequestComplete();
        }

        @Override
        public void onFailure(Request request, Throwable failure) {
            onConnectionFailed(failure);
        }
    };
    InputStreamResponseListener responseListener = new InputStreamResponseListener() {

        OutputStreamBuilder osb = OutputStreamBuilder.withExchange(exchange);

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            byte[] buffer = new byte[content.limit()];
            content.get(buffer);
            try {
                osb.write(buffer);
                callback.succeeded();
            } catch (IOException e) {
                callback.failed(e);
            }
        }

        @Override
        public void onComplete(Result result) {
            if (result.isFailed()) {
                doTaskCompleted(result.getFailure());
            } else {
                try {
                    Object content = osb.build();
                    if (content instanceof byte[]) {
                        onResponseComplete(result, (byte[]) content);
                    } else {
                        StreamCache cos = (StreamCache) content;
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        cos.writeTo(baos);
                        onResponseComplete(result, baos.toByteArray());
                    }
                } catch (IOException e) {
                    doTaskCompleted(e);
                }
            }
        }
    };
    request.followRedirects(supportRedirect).listener(listener).send(responseListener);
}
Also used : InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer) Result(org.eclipse.jetty.client.api.Result) Response(org.eclipse.jetty.client.api.Response) Callback(org.eclipse.jetty.util.Callback) AsyncCallback(org.apache.camel.AsyncCallback) StreamCache(org.apache.camel.StreamCache) OutputStreamBuilder(org.apache.camel.converter.stream.OutputStreamBuilder)

Example 50 with Response

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

the class HttpRequestEvent method createHttpRequestEvent.

static HttpRequestEvent createHttpRequestEvent(RequestInfo requestInfo, ResponseInfo responseInfo) {
    requireNonNull(requestInfo, "requestInfo is null");
    requireNonNull(responseInfo, "responseInfo is null");
    Request request = requestInfo.getRequest();
    Optional<Response> response = responseInfo.getResponse();
    String requestUri = null;
    if (request.getURI() != null) {
        requestUri = request.getURI().toString();
    }
    String method = request.getMethod();
    if (method != null) {
        method = method.toUpperCase(Locale.US);
    }
    long responseSize = NO_RESPONSE;
    int responseCode = NO_RESPONSE;
    if (response.isPresent()) {
        responseSize = responseInfo.getResponseSize();
        responseCode = response.get().getStatus();
    }
    long timeToLastByte = max(responseInfo.getResponseTimestampMillis() - requestInfo.getRequestTimestampMillis(), 0L);
    return new HttpRequestEvent(Instant.ofEpochMilli(requestInfo.getRequestTimestampMillis()), request.getVersion().toString(), method, requestUri, getHeader(request, TRACETOKEN_HEADER), responseSize, responseCode, timeToLastByte, getFailureReason(responseInfo));
}
Also used : Response(org.eclipse.jetty.client.api.Response) Request(org.eclipse.jetty.client.api.Request)

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