Search in sources :

Example 11 with ClientResponse

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

the class ApacheConnector method apply.

@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
    final HttpUriRequest request = getUriHttpRequest(clientRequest);
    final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);
    try {
        final CloseableHttpResponse response;
        final HttpClientContext context = HttpClientContext.create();
        if (preemptiveBasicAuth) {
            final AuthCache authCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme();
            authCache.put(getHost(request), basicScheme);
            context.setAuthCache(authCache);
        }
        response = client.execute(getHost(request), request, context);
        HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());
        final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        final ClientResponse responseContext = new ClientResponse(status, clientRequest);
        final List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations != null && !redirectLocations.isEmpty()) {
            responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
        }
        final Header[] respHeaders = response.getAllHeaders();
        final MultivaluedMap<String, String> headers = responseContext.getHeaders();
        for (final Header header : respHeaders) {
            final String headerName = header.getName();
            List<String> list = headers.get(headerName);
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(header.getValue());
            headers.put(headerName, list);
        }
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
                headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
            }
            final Header contentEncoding = entity.getContentEncoding();
            if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
                headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
            }
        }
        try {
            responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, null, e);
        }
        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) ClientResponse(org.glassfish.jersey.client.ClientResponse) BasicScheme(org.apache.http.impl.auth.BasicScheme) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AbstractHttpEntity(org.apache.http.entity.AbstractHttpEntity) AuthCache(org.apache.http.client.AuthCache) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicAuthCache(org.apache.http.impl.client.BasicAuthCache) IOException(java.io.IOException) URI(java.net.URI) ProcessingException(javax.ws.rs.ProcessingException) IOException(java.io.IOException) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Header(org.apache.http.Header) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ProcessingException(javax.ws.rs.ProcessingException)

Example 12 with ClientResponse

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

the class JdkConnector method send.

private void send(final ClientRequest request, final HttpRequest httpRequest, final AsyncConnectorCallback callback) {
    translateHeaders(request, httpRequest);
    final RedirectHandler redirectHandler = new RedirectHandler(httpConnectionPool, httpRequest, connectorConfiguration);
    httpConnectionPool.send(httpRequest, new CompletionHandler<HttpResponse>() {

        @Override
        public void failed(Throwable throwable) {
            callback.failure(throwable);
        }

        @Override
        public void completed(HttpResponse result) {
            redirectHandler.handleRedirects(result, new CompletionHandler<HttpResponse>() {

                @Override
                public void failed(Throwable throwable) {
                    callback.failure(throwable);
                }

                @Override
                public void completed(HttpResponse result) {
                    ClientResponse response = translateResponse(request, result, redirectHandler.getLastRequestUri());
                    callback.response(response);
                }
            });
        }
    });
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse)

Example 13 with ClientResponse

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

the class GrizzlyConnector method translate.

private ClientResponse translate(final ClientRequest requestContext, final HttpResponseStatus status, final HttpResponseHeaders headers, final NonBlockingInputStream entityStream) {
    final ClientResponse responseContext = new ClientResponse(new Response.StatusType() {

        @Override
        public int getStatusCode() {
            return status.getStatusCode();
        }

        @Override
        public Response.Status.Family getFamily() {
            return Response.Status.Family.familyOf(status.getStatusCode());
        }

        @Override
        public String getReasonPhrase() {
            return status.getStatusText();
        }
    }, requestContext);
    for (Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) {
        for (String value : entry.getValue()) {
            responseContext.getHeaders().add(entry.getKey(), value);
        }
    }
    responseContext.setEntityStream(entityStream);
    return responseContext;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) List(java.util.List) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 14 with ClientResponse

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

Example 15 with ClientResponse

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

the class JettyConnector method translateResponse.

private static ClientResponse translateResponse(final ClientRequest jerseyRequest, final org.eclipse.jetty.client.api.Response jettyResponse, final NonBlockingInputStream entityStream) {
    final ClientResponse jerseyResponse = new ClientResponse(Statuses.from(jettyResponse.getStatus()), jerseyRequest);
    processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse);
    jerseyResponse.setEntityStream(entityStream);
    return jerseyResponse;
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse)

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