Search in sources :

Example 1 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 2 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 3 with ClientRequest

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

the class InMemoryConnector method apply.

/**
     * {@inheritDoc}
     * <p/>
     * Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
     * instance).
     *
     * @param clientRequest client side request to be invoked.
     */
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
    PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
    final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
    containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
    final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
    if (clientRequest.getEntity() != null) {
        clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

            @Override
            public OutputStream getOutputStream(int contentLength) throws IOException {
                final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
                if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
                    containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
                }
                return clientOutput;
            }
        });
        clientRequest.enableBuffering();
        try {
            clientRequest.writeEntity();
        } catch (IOException e) {
            final String msg = "Error while writing entity to the output stream.";
            LOGGER.log(Level.SEVERE, msg, e);
            throw new ProcessingException(msg, e);
        }
    }
    containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
    boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
    final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
    containerRequest.setWriter(inMemoryResponseWriter);
    containerRequest.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return null;
        }

        @Override
        public boolean isUserInRole(String role) {
            return false;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public String getAuthenticationScheme() {
            return null;
        }
    });
    appHandler.handle(containerRequest);
    return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ByteArrayInputStream(java.io.ByteArrayInputStream) SecurityContext(javax.ws.rs.core.SecurityContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate) Principal(java.security.Principal) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException)

Example 4 with ClientRequest

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

the class InMemoryConnector method tryFollowRedirects.

@SuppressWarnings("MagicNumber")
private ClientResponse tryFollowRedirects(boolean followRedirects, ClientResponse response, ClientRequest request) {
    if (!followRedirects) {
        return response;
    }
    while (true) {
        switch(response.getStatus()) {
            case 303:
            case 302:
            case 307:
                request = new ClientRequest(request);
                request.setUri(response.getLocation());
                if (response.getStatus() == 303) {
                    request.setMethod("GET");
                }
                response = apply(request);
                break;
            default:
                return response;
        }
    }
}
Also used : ClientRequest(org.glassfish.jersey.client.ClientRequest)

Example 5 with ClientRequest

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

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