Search in sources :

Example 6 with ClientResponse

use of org.glassfish.jersey.client.ClientResponse 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 7 with ClientResponse

use of org.glassfish.jersey.client.ClientResponse in project jersey by jersey.

the class JettyConnector method apply.

@Override
public ClientResponse apply(final ClientRequest jerseyRequest) throws ProcessingException {
    final Request jettyRequest = translateRequest(jerseyRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest);
    final ContentProvider entity = getBytesProvider(jerseyRequest);
    if (entity != null) {
        jettyRequest.content(entity);
    }
    try {
        final ContentResponse jettyResponse = jettyRequest.send();
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName());
        final javax.ws.rs.core.Response.StatusType status = jettyResponse.getReason() == null ? Statuses.from(jettyResponse.getStatus()) : Statuses.from(jettyResponse.getStatus(), jettyResponse.getReason());
        final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
        processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse);
        try {
            jerseyResponse.setEntityStream(new HttpClientResponseInputStream(jettyResponse));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }
        return jerseyResponse;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) 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) IOException(java.io.IOException) CancellationException(java.util.concurrent.CancellationException) ProcessingException(javax.ws.rs.ProcessingException) IOException(java.io.IOException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(org.eclipse.jetty.client.api.Response) ProcessingException(javax.ws.rs.ProcessingException)

Example 8 with ClientResponse

use of org.glassfish.jersey.client.ClientResponse in project jersey by jersey.

the class InMemoryConnector method apply.

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    CompletableFuture<ClientResponse> future = new CompletableFuture<>();
    try {
        ClientResponse response = apply(request);
        callback.response(response);
        future.complete(response);
    } catch (ProcessingException ex) {
        future.completeExceptionally(ex);
    } catch (Throwable t) {
        callback.failure(t);
        future.completeExceptionally(t);
    }
    return future;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) CompletableFuture(java.util.concurrent.CompletableFuture) ProcessingException(javax.ws.rs.ProcessingException)

Example 9 with ClientResponse

use of org.glassfish.jersey.client.ClientResponse in project dropwizard by dropwizard.

the class DropwizardApacheConnectorTest method multiple_headers_with_the_same_name_are_processed_successfully.

@Test
public void multiple_headers_with_the_same_name_are_processed_successfully() throws Exception {
    final CloseableHttpClient client = mock(CloseableHttpClient.class);
    final DropwizardApacheConnector dropwizardApacheConnector = new DropwizardApacheConnector(client, null, false);
    final Header[] apacheHeaders = { new BasicHeader("Set-Cookie", "test1"), new BasicHeader("Set-Cookie", "test2") };
    final CloseableHttpResponse apacheResponse = mock(CloseableHttpResponse.class);
    when(apacheResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(apacheResponse.getAllHeaders()).thenReturn(apacheHeaders);
    when(client.execute(Mockito.any())).thenReturn(apacheResponse);
    final ClientRequest jerseyRequest = mock(ClientRequest.class);
    when(jerseyRequest.getUri()).thenReturn(URI.create("http://localhost"));
    when(jerseyRequest.getMethod()).thenReturn("GET");
    when(jerseyRequest.getHeaders()).thenReturn(new MultivaluedHashMap<>());
    final ClientResponse jerseyResponse = dropwizardApacheConnector.apply(jerseyRequest);
    assertThat(jerseyResponse.getStatus()).isEqualTo(apacheResponse.getStatusLine().getStatusCode());
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProtocolVersion(org.apache.http.ProtocolVersion) BasicHeader(org.apache.http.message.BasicHeader) ClientRequest(org.glassfish.jersey.client.ClientRequest) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.Test)

Example 10 with ClientResponse

use of org.glassfish.jersey.client.ClientResponse in project dropwizard by dropwizard.

the class DropwizardApacheConnector method apply.

/**
     * {@inheritDoc}
     */
@Override
public ClientResponse apply(ClientRequest jerseyRequest) {
    try {
        final HttpUriRequest apacheRequest = buildApacheRequest(jerseyRequest);
        final CloseableHttpResponse apacheResponse = client.execute(apacheRequest);
        final StatusLine statusLine = apacheResponse.getStatusLine();
        final Response.StatusType status = Statuses.from(statusLine.getStatusCode(), firstNonNull(statusLine.getReasonPhrase(), ""));
        final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest);
        for (Header header : apacheResponse.getAllHeaders()) {
            final List<String> headerValues = jerseyResponse.getHeaders().get(header.getName());
            if (headerValues == null) {
                jerseyResponse.getHeaders().put(header.getName(), Lists.newArrayList(header.getValue()));
            } else {
                headerValues.add(header.getValue());
            }
        }
        final HttpEntity httpEntity = apacheResponse.getEntity();
        jerseyResponse.setEntityStream(httpEntity != null ? httpEntity.getContent() : new ByteArrayInputStream(new byte[0]));
        return jerseyResponse;
    } catch (Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) ProcessingException(javax.ws.rs.ProcessingException) StatusLine(org.apache.http.StatusLine) ClientResponse(org.glassfish.jersey.client.ClientResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Response(javax.ws.rs.core.Response) Header(org.apache.http.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ClientResponse (org.glassfish.jersey.client.ClientResponse)21 ProcessingException (javax.ws.rs.ProcessingException)10 IOException (java.io.IOException)7 CompletableFuture (java.util.concurrent.CompletableFuture)7 Response (javax.ws.rs.core.Response)7 ClientRequest (org.glassfish.jersey.client.ClientRequest)6 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Map (java.util.Map)3 Header (org.apache.http.Header)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 Test (org.junit.Test)3 URI (java.net.URI)2 List (java.util.List)2 CancellationException (java.util.concurrent.CancellationException)2 ExecutionException (java.util.concurrent.ExecutionException)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Client (javax.ws.rs.client.Client)2 HttpEntity (org.apache.http.HttpEntity)2 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)2