Search in sources :

Example 1 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 2 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)

Example 3 with ClientResponse

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

the class HttpUrlConnector method _apply.

private ClientResponse _apply(final ClientRequest request) throws IOException {
    final HttpURLConnection uc;
    uc = this.connectionFactory.getConnection(request.getUri().toURL());
    uc.setDoInput(true);
    final String httpMethod = request.getMethod();
    if (request.resolveProperty(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, setMethodWorkaround)) {
        setRequestMethodViaJreBugWorkaround(uc, httpMethod);
    } else {
        uc.setRequestMethod(httpMethod);
    }
    uc.setInstanceFollowRedirects(request.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, true));
    uc.setConnectTimeout(request.resolveProperty(ClientProperties.CONNECT_TIMEOUT, uc.getConnectTimeout()));
    uc.setReadTimeout(request.resolveProperty(ClientProperties.READ_TIMEOUT, uc.getReadTimeout()));
    secureConnection(request.getClient(), uc);
    final Object entity = request.getEntity();
    if (entity != null) {
        RequestEntityProcessing entityProcessing = request.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class);
        if (entityProcessing == null || entityProcessing != RequestEntityProcessing.BUFFERED) {
            final long length = request.getLengthLong();
            if (fixLengthStreaming && length > 0) {
                // uc.setFixedLengthStreamingMode(long) was introduced in JDK 1.7 and Jersey client supports 1.6+
                if ("1.6".equals(Runtime.class.getPackage().getSpecificationVersion())) {
                    uc.setFixedLengthStreamingMode(request.getLength());
                } else {
                    uc.setFixedLengthStreamingMode(length);
                }
            } else if (entityProcessing == RequestEntityProcessing.CHUNKED) {
                uc.setChunkedStreamingMode(chunkSize);
            }
        }
        uc.setDoOutput(true);
        if ("GET".equalsIgnoreCase(httpMethod)) {
            final Logger logger = Logger.getLogger(HttpUrlConnector.class.getName());
            if (logger.isLoggable(Level.INFO)) {
                logger.log(Level.INFO, LocalizationMessages.HTTPURLCONNECTION_REPLACES_GET_WITH_ENTITY());
            }
        }
        request.setStreamProvider(contentLength -> {
            setOutboundHeaders(request.getStringHeaders(), uc);
            return uc.getOutputStream();
        });
        request.writeEntity();
    } else {
        setOutboundHeaders(request.getStringHeaders(), uc);
    }
    final int code = uc.getResponseCode();
    final String reasonPhrase = uc.getResponseMessage();
    final Response.StatusType status = reasonPhrase == null ? Statuses.from(code) : Statuses.from(code, reasonPhrase);
    final URI resolvedRequestUri;
    try {
        resolvedRequestUri = uc.getURL().toURI();
    } catch (URISyntaxException e) {
        throw new ProcessingException(e);
    }
    ClientResponse responseContext = new ClientResponse(status, request, resolvedRequestUri);
    responseContext.headers(uc.getHeaderFields().entrySet().stream().filter(stringListEntry -> stringListEntry.getKey() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    responseContext.setEntityStream(getInputStream(uc));
    return responseContext;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) RequestEntityProcessing(org.glassfish.jersey.client.RequestEntityProcessing) URISyntaxException(java.net.URISyntaxException) Logger(java.util.logging.Logger) URI(java.net.URI) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) HttpURLConnection(java.net.HttpURLConnection) ProcessingException(javax.ws.rs.ProcessingException)

Example 4 with ClientResponse

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

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