Search in sources :

Example 1 with ContentProvider

use of org.eclipse.jetty.client.api.ContentProvider in project jetty.project by eclipse.

the class HttpSender method send.

public void send(HttpExchange exchange) {
    if (!queuedToBegin(exchange))
        return;
    Request request = exchange.getRequest();
    ContentProvider contentProvider = request.getContent();
    HttpContent content = this.content = new HttpContent(contentProvider);
    SenderState newSenderState = SenderState.SENDING;
    if (expects100Continue(request))
        newSenderState = content.hasContent() ? SenderState.EXPECTING_WITH_CONTENT : SenderState.EXPECTING;
    out: while (true) {
        SenderState current = senderState.get();
        switch(current) {
            case IDLE:
            case COMPLETED:
                {
                    if (updateSenderState(current, newSenderState))
                        break out;
                    break;
                }
            default:
                {
                    illegalSenderState(current);
                    return;
                }
        }
    }
    // threads so we must set it only after the sender state has been updated
    if (contentProvider instanceof AsyncContentProvider)
        ((AsyncContentProvider) contentProvider).setListener(this);
    if (!beginToHeaders(exchange))
        return;
    sendHeaders(exchange, content, commitCallback);
}
Also used : ContentProvider(org.eclipse.jetty.client.api.ContentProvider) Request(org.eclipse.jetty.client.api.Request)

Example 2 with ContentProvider

use of org.eclipse.jetty.client.api.ContentProvider in project jetty.project by eclipse.

the class HttpConnection method normalizeRequest.

protected void normalizeRequest(Request request) {
    HttpVersion version = request.getVersion();
    HttpFields headers = request.getHeaders();
    ContentProvider content = request.getContent();
    ProxyConfiguration.Proxy proxy = destination.getProxy();
    // Make sure the path is there
    String path = request.getPath();
    if (path.trim().length() == 0) {
        path = "/";
        request.path(path);
    }
    URI uri = request.getURI();
    if (proxy instanceof HttpProxy && !HttpClient.isSchemeSecure(request.getScheme()) && uri != null) {
        path = uri.toString();
        request.path(path);
    }
    // If we are HTTP 1.1, add the Host header
    if (version.getVersion() <= 11) {
        if (!headers.containsKey(HttpHeader.HOST.asString()))
            headers.put(getHttpDestination().getHostField());
    }
    // Add content headers
    if (content != null) {
        if (!headers.containsKey(HttpHeader.CONTENT_TYPE.asString())) {
            String contentType = null;
            if (content instanceof ContentProvider.Typed)
                contentType = ((ContentProvider.Typed) content).getContentType();
            if (contentType != null)
                headers.put(HttpHeader.CONTENT_TYPE, contentType);
            else
                headers.put(HttpHeader.CONTENT_TYPE, "application/octet-stream");
        }
        long contentLength = content.getLength();
        if (contentLength >= 0) {
            if (!headers.containsKey(HttpHeader.CONTENT_LENGTH.asString()))
                headers.put(HttpHeader.CONTENT_LENGTH, String.valueOf(contentLength));
        }
    }
    // Cookies
    CookieStore cookieStore = getHttpClient().getCookieStore();
    if (cookieStore != null) {
        StringBuilder cookies = null;
        if (uri != null)
            cookies = convertCookies(cookieStore.get(uri), null);
        cookies = convertCookies(request.getCookies(), cookies);
        if (cookies != null)
            request.header(HttpHeader.COOKIE.asString(), cookies.toString());
    }
    // Authentication
    applyAuthentication(request, proxy != null ? proxy.getURI() : null);
    applyAuthentication(request, uri);
}
Also used : CookieStore(java.net.CookieStore) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) HttpFields(org.eclipse.jetty.http.HttpFields) HttpVersion(org.eclipse.jetty.http.HttpVersion) URI(java.net.URI)

Example 3 with ContentProvider

use of org.eclipse.jetty.client.api.ContentProvider in project jetty.project by eclipse.

the class ProxyServlet method service.

@Override
protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    final int requestId = getRequestId(request);
    String rewrittenTarget = rewriteTarget(request);
    if (_log.isDebugEnabled()) {
        StringBuffer uri = request.getRequestURL();
        if (request.getQueryString() != null)
            uri.append("?").append(request.getQueryString());
        if (_log.isDebugEnabled())
            _log.debug("{} rewriting: {} -> {}", requestId, uri, rewrittenTarget);
    }
    if (rewrittenTarget == null) {
        onProxyRewriteFailed(request, response);
        return;
    }
    final Request proxyRequest = getHttpClient().newRequest(rewrittenTarget).method(request.getMethod()).version(HttpVersion.fromString(request.getProtocol()));
    copyRequestHeaders(request, proxyRequest);
    addProxyHeaders(request, proxyRequest);
    final AsyncContext asyncContext = request.startAsync();
    // We do not timeout the continuation, but the proxy request
    asyncContext.setTimeout(0);
    proxyRequest.timeout(getTimeout(), TimeUnit.MILLISECONDS);
    if (hasContent(request)) {
        if (expects100Continue(request)) {
            DeferredContentProvider deferred = new DeferredContentProvider();
            proxyRequest.content(deferred);
            proxyRequest.attribute(CLIENT_REQUEST_ATTRIBUTE, request);
            proxyRequest.attribute(CONTINUE_ACTION_ATTRIBUTE, (Runnable) () -> {
                try {
                    ContentProvider provider = proxyRequestContent(request, response, proxyRequest);
                    new DelegatingContentProvider(request, proxyRequest, response, provider, deferred).iterate();
                } catch (Throwable failure) {
                    onClientRequestFailure(request, proxyRequest, response, failure);
                }
            });
        } else {
            proxyRequest.content(proxyRequestContent(request, response, proxyRequest));
        }
    }
    sendProxyRequest(request, response, proxyRequest);
}
Also used : DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) AsyncContentProvider(org.eclipse.jetty.client.AsyncContentProvider) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) ContentProvider(org.eclipse.jetty.client.api.ContentProvider) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsyncContext(javax.servlet.AsyncContext)

Example 4 with ContentProvider

use of org.eclipse.jetty.client.api.ContentProvider 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 5 with ContentProvider

use of org.eclipse.jetty.client.api.ContentProvider 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)

Aggregations

ContentProvider (org.eclipse.jetty.client.api.ContentProvider)11 Request (org.eclipse.jetty.client.api.Request)8 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)5 BytesContentProvider (org.eclipse.jetty.client.util.BytesContentProvider)5 IOException (java.io.IOException)4 ByteBuffer (java.nio.ByteBuffer)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)4 InputStreamContentProvider (org.eclipse.jetty.client.util.InputStreamContentProvider)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Response (org.eclipse.jetty.client.api.Response)3 Result (org.eclipse.jetty.client.api.Result)3 CancellationException (java.util.concurrent.CancellationException)2 ServletException (javax.servlet.ServletException)2 ProcessingException (javax.ws.rs.ProcessingException)2 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)2 OutputStreamContentProvider (org.eclipse.jetty.client.util.OutputStreamContentProvider)2 ClientRequest (org.glassfish.jersey.client.ClientRequest)2 ClientResponse (org.glassfish.jersey.client.ClientResponse)2 Test (org.junit.Test)2