Search in sources :

Example 6 with ClientRequest

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

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

the class EncodingFilterTest method testClosingClientResponseStreamRetrievedByResponseOnError.

/**
     * Reproducer for JERSEY-2028.
     *
     * @see #testClosingClientResponseStreamRetrievedByValueOnError
     */
@Test
public void testClosingClientResponseStreamRetrievedByResponseOnError() {
    final TestInputStream responseStream = new TestInputStream();
    Client client = ClientBuilder.newClient(new ClientConfig().connectorProvider(new TestConnector() {

        @Override
        public ClientResponse apply(ClientRequest requestContext) throws ProcessingException {
            final ClientResponse responseContext = new ClientResponse(Response.Status.OK, requestContext);
            responseContext.header(CONTENT_ENCODING, "gzip");
            responseContext.setEntityStream(responseStream);
            return responseContext;
        }
    }).register(new EncodingFeature(GZipEncoder.class, DeflateEncoder.class)));
    final Response response = client.target(UriBuilder.fromUri("/").build()).request().get();
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    assertEquals("gzip", response.getHeaderString(CONTENT_ENCODING));
    try {
        response.readEntity(String.class);
        fail("Exception caused by invalid gzip stream expected.");
    } catch (ProcessingException ex) {
        assertTrue("Response input stream not closed when exception is thrown.", responseStream.isClosed);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) Client(javax.ws.rs.client.Client) ClientConfig(org.glassfish.jersey.client.ClientConfig) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 8 with ClientRequest

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

the class EncodingFilterTest method testClosingClientResponseStreamRetrievedByValueOnError.

/**
     * Reproducer for JERSEY-2028.
     *
     * @see #testClosingClientResponseStreamRetrievedByResponseOnError
     */
@Test
public void testClosingClientResponseStreamRetrievedByValueOnError() {
    final TestInputStream responseStream = new TestInputStream();
    Client client = ClientBuilder.newClient(new ClientConfig().connectorProvider(new TestConnector() {

        @Override
        public ClientResponse apply(ClientRequest requestContext) throws ProcessingException {
            final ClientResponse responseContext = new ClientResponse(Response.Status.OK, requestContext);
            responseContext.header(CONTENT_ENCODING, "gzip");
            responseContext.setEntityStream(responseStream);
            return responseContext;
        }
    }).register(new EncodingFeature(GZipEncoder.class, DeflateEncoder.class)));
    try {
        client.target(UriBuilder.fromUri("/").build()).request().get(String.class);
        fail("Exception caused by invalid gzip stream expected.");
    } catch (ProcessingException ex) {
        assertTrue("Response input stream not closed when exception is thrown.", responseStream.isClosed);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) Client(javax.ws.rs.client.Client) ClientConfig(org.glassfish.jersey.client.ClientConfig) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 9 with ClientRequest

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

the class GrizzlyConnector method apply.

@Override
public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) {
    final Request connectorRequest = translate(request);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(request.getHeaders(), connectorRequest);
    final ByteBufferInputStream entityStream = new ByteBufferInputStream();
    final AtomicBoolean callbackInvoked = new AtomicBoolean(false);
    Throwable failure;
    try {
        return grizzlyClient.executeRequest(connectorRequest, new AsyncHandler<Void>() {

            private volatile HttpResponseStatus status = null;

            @Override
            public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
                status = responseStatus;
                return STATE.CONTINUE;
            }

            @Override
            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                if (!callbackInvoked.compareAndSet(false, true)) {
                    return STATE.ABORT;
                }
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, request.getHeaders(), GrizzlyConnector.this.getClass().getName());
                // hand-off to grizzly's application thread pool for response processing
                processResponse(new Runnable() {

                    @Override
                    public void run() {
                        callback.response(translate(request, status, headers, entityStream));
                    }
                });
                return STATE.CONTINUE;
            }

            @Override
            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                entityStream.put(bodyPart.getBodyByteBuffer());
                return STATE.CONTINUE;
            }

            @Override
            public Void onCompleted() throws Exception {
                entityStream.closeQueue();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                entityStream.closeQueue(t);
                if (callbackInvoked.compareAndSet(false, true)) {
                    t = t instanceof IOException ? new ProcessingException(t.getMessage(), t) : t;
                    callback.failure(t);
                }
            }
        });
    } catch (Throwable t) {
        failure = t;
    }
    if (callbackInvoked.compareAndSet(false, true)) {
        callback.failure(failure);
    }
    CompletableFuture<Object> future = new CompletableFuture<>();
    future.completeExceptionally(failure);
    return future;
}
Also used : HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) Request(com.ning.http.client.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) HttpResponseBodyPart(com.ning.http.client.HttpResponseBodyPart) ProcessingException(javax.ws.rs.ProcessingException)

Example 10 with ClientRequest

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

the class GrizzlyConnector method apply.

/**
     * Sends the {@link javax.ws.rs.core.Request} via Grizzly transport and returns the {@link javax.ws.rs.core.Response}.
     *
     * @param request Jersey client request to be sent.
     * @return received response.
     */
@Override
public ClientResponse apply(final ClientRequest request) {
    final Request connectorRequest = translate(request);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(request.getHeaders(), connectorRequest);
    final CompletableFuture<ClientResponse> responseFuture = new CompletableFuture<>();
    final ByteBufferInputStream entityStream = new ByteBufferInputStream();
    final AtomicBoolean futureSet = new AtomicBoolean(false);
    try {
        grizzlyClient.executeRequest(connectorRequest, new AsyncHandler<Void>() {

            private volatile HttpResponseStatus status = null;

            @Override
            public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {
                status = responseStatus;
                return STATE.CONTINUE;
            }

            @Override
            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                if (!futureSet.compareAndSet(false, true)) {
                    return STATE.ABORT;
                }
                HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, request.getHeaders(), GrizzlyConnector.this.getClass().getName());
                responseFuture.complete(translate(request, this.status, headers, entityStream));
                return STATE.CONTINUE;
            }

            @Override
            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                entityStream.put(bodyPart.getBodyByteBuffer());
                return STATE.CONTINUE;
            }

            @Override
            public Void onCompleted() throws Exception {
                entityStream.closeQueue();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                entityStream.closeQueue(t);
                if (futureSet.compareAndSet(false, true)) {
                    t = t instanceof IOException ? new ProcessingException(t.getMessage(), t) : t;
                    responseFuture.completeExceptionally(t);
                }
            }
        });
        return responseFuture.get();
    } catch (ExecutionException ex) {
        Throwable e = ex.getCause() == null ? ex : ex.getCause();
        throw new ProcessingException(e.getMessage(), e);
    } catch (InterruptedException ex) {
        throw new ProcessingException(ex.getMessage(), ex);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) HttpResponseHeaders(com.ning.http.client.HttpResponseHeaders) HttpResponseStatus(com.ning.http.client.HttpResponseStatus) Request(com.ning.http.client.Request) ClientRequest(org.glassfish.jersey.client.ClientRequest) ByteBufferInputStream(org.glassfish.jersey.internal.util.collection.ByteBufferInputStream) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) HttpResponseBodyPart(com.ning.http.client.HttpResponseBodyPart) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ClientRequest (org.glassfish.jersey.client.ClientRequest)11 ProcessingException (javax.ws.rs.ProcessingException)8 ClientResponse (org.glassfish.jersey.client.ClientResponse)6 IOException (java.io.IOException)4 Test (org.junit.Test)4 CompletableFuture (java.util.concurrent.CompletableFuture)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 Request (org.eclipse.jetty.client.api.Request)3 ByteBufferInputStream (org.glassfish.jersey.internal.util.collection.ByteBufferInputStream)3 HttpResponseBodyPart (com.ning.http.client.HttpResponseBodyPart)2 HttpResponseHeaders (com.ning.http.client.HttpResponseHeaders)2 HttpResponseStatus (com.ning.http.client.HttpResponseStatus)2 Request (com.ning.http.client.Request)2 CancellationException (java.util.concurrent.CancellationException)2 ExecutionException (java.util.concurrent.ExecutionException)2 Client (javax.ws.rs.client.Client)2 Response (javax.ws.rs.core.Response)2 ContentProvider (org.eclipse.jetty.client.api.ContentProvider)2 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)2 Response (org.eclipse.jetty.client.api.Response)2