Example usage for org.apache.http.client.protocol HttpClientContext HTTP_ROUTE

List of usage examples for org.apache.http.client.protocol HttpClientContext HTTP_ROUTE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext HTTP_ROUTE.

Prototype

String HTTP_ROUTE

To view the source code for org.apache.http.client.protocol HttpClientContext HTTP_ROUTE.

Click Source Link

Document

Attribute name of a org.apache.http.conn.routing.RouteInfo object that represents the actual connection route.

Usage

From source file:org.pentaho.di.trans.ael.websocket.SessionConfigurator.java

private HttpContext getContext(URI uri) {
    HttpClientContext httpClientContext = HttpClientContext.create();
    //used by httpclient version >= 4.3
    httpClientContext.setAttribute(HttpClientContext.HTTP_ROUTE,
            new HttpRoute(new HttpHost(uri.getHost(), uri.getPort())));
    //used by httpclient version 4.2
    httpClientContext.setAttribute(HttpClientContext.HTTP_TARGET_HOST,
            new HttpHost(uri.getHost(), uri.getPort()));
    return httpClientContext;
}

From source file:org.apache.http.impl.auth.GGSSchemeBase.java

@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    Args.notNull(request, "HTTP request");
    switch (state) {
    case UNINITIATED:
        throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
    case FAILED://  ww  w. ja v  a2 s .  c o m
        throw new AuthenticationException(getSchemeName() + " authentication has failed");
    case CHALLENGE_RECEIVED:
        try {
            final HttpRoute route = (HttpRoute) context.getAttribute(HttpClientContext.HTTP_ROUTE);
            if (route == null) {
                throw new AuthenticationException("Connection route is not available");
            }
            HttpHost host;
            if (isProxy()) {
                host = route.getProxyHost();
                if (host == null) {
                    host = route.getTargetHost();
                }
            } else {
                host = route.getTargetHost();
            }
            final String authServer;
            if (!this.stripPort && host.getPort() > 0) {
                authServer = host.toHostString();
            } else {
                authServer = host.getHostName();
            }

            if (log.isDebugEnabled()) {
                log.debug("init " + authServer);
            }
            token = generateToken(token, authServer);
            state = State.TOKEN_GENERATED;
        } catch (final GSSException gsse) {
            state = State.FAILED;
            if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                    || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
                throw new InvalidCredentialsException(gsse.getMessage(), gsse);
            }
            if (gsse.getMajor() == GSSException.NO_CRED) {
                throw new InvalidCredentialsException(gsse.getMessage(), gsse);
            }
            if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
                    || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                    || gsse.getMajor() == GSSException.OLD_TOKEN) {
                throw new AuthenticationException(gsse.getMessage(), gsse);
            }
            // other error
            throw new AuthenticationException(gsse.getMessage());
        }
    case TOKEN_GENERATED:
        final String tokenstr = new String(base64codec.encode(token));
        if (log.isDebugEnabled()) {
            log.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        final CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    default:
        throw new IllegalStateException("Illegal state: " + state);
    }
}

From source file:org.apache.http.impl.client.cache.CachingExec.java

private CloseableHttpResponse handleCacheHit(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware, final HttpCacheEntry entry)
        throws IOException, HttpException {
    final HttpHost target = context.getTargetHost();
    recordCacheHit(target, request);//  w w w  . ja va  2s .  co  m
    CloseableHttpResponse out = null;
    final Date now = getCurrentDate();
    if (suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
        log.debug("Cache hit");
        out = generateCachedResponse(request, context, entry, now);
    } else if (!mayCallBackend(request)) {
        log.debug("Cache entry not suitable but only-if-cached requested");
        out = generateGatewayTimeout(context);
    } else if (!(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED
            && !suitabilityChecker.isConditional(request))) {
        log.debug("Revalidating cache entry");
        return revalidateCacheEntry(route, request, context, execAware, entry, now);
    } else {
        log.debug("Cache entry not usable; calling backend");
        return callBackend(route, request, context, execAware);
    }
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpClientContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_REQUEST, request);
    context.setAttribute(HttpClientContext.HTTP_RESPONSE, out);
    context.setAttribute(HttpClientContext.HTTP_REQ_SENT, Boolean.TRUE);
    return out;
}

From source file:org.apache.http.impl.client.cache.CachingHttpAsyncClient.java

private void handleCacheHit(final BasicFuture<HttpResponse> future, final HttpHost target,
        final HttpRequestWrapper request, final HttpCacheContext clientContext, final HttpCacheEntry entry)
        throws IOException {
    recordCacheHit(target, request);//ww  w. ja v  a  2  s .c om
    final HttpResponse out;
    final Date now = getCurrentDate();
    if (this.suitabilityChecker.canCachedResponseBeUsed(target, request, entry, now)) {
        log.debug("Cache hit");
        out = generateCachedResponse(request, clientContext, entry, now);
    } else if (!mayCallBackend(request)) {
        log.debug("Cache entry not suitable but only-if-cached requested");
        out = generateGatewayTimeout(clientContext);
    } else if (validityPolicy.isRevalidatable(entry) && !(entry.getStatusCode() == HttpStatus.SC_NOT_MODIFIED
            && !suitabilityChecker.isConditional(request))) {
        log.debug("Revalidating cache entry");
        revalidateCacheEntry(future, target, request, clientContext, entry, now);
        return;
    } else {
        log.debug("Cache entry not usable; calling backend");
        callBackend(future, target, request, clientContext);
        return;
    }
    clientContext.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(target));
    clientContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    clientContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    clientContext.setAttribute(HttpCoreContext.HTTP_RESPONSE, out);
    clientContext.setAttribute(HttpCoreContext.HTTP_REQ_SENT, Boolean.TRUE);
    future.completed(out);
}

From source file:org.apache.http.impl.execchain.MinimalClientExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    rewriteRequestURI(request, route);/*from ww w  .ja  va  2s .com*/

    final ConnectionRequest connRequest = connManager.requestConnection(route, null);
    if (execAware != null) {
        if (execAware.isAborted()) {
            connRequest.cancel();
            throw new RequestAbortedException("Request aborted");
        } else {
            execAware.setCancellable(connRequest);
        }
    }

    final RequestConfig config = context.getRequestConfig();

    final HttpClientConnection managedConn;
    try {
        final int timeout = config.getConnectionRequestTimeout();
        managedConn = connRequest.get(timeout > 0 ? timeout : 0, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException interrupted) {
        Thread.currentThread().interrupt();
        throw new RequestAbortedException("Request aborted", interrupted);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        throw new RequestAbortedException("Request execution failed", cause);
    }

    final ConnectionHolder releaseTrigger = new ConnectionHolder(log, connManager, managedConn);
    try {
        if (execAware != null) {
            if (execAware.isAborted()) {
                releaseTrigger.close();
                throw new RequestAbortedException("Request aborted");
            } else {
                execAware.setCancellable(releaseTrigger);
            }
        }

        if (!managedConn.isOpen()) {
            final int timeout = config.getConnectTimeout();
            this.connManager.connect(managedConn, route, timeout > 0 ? timeout : 0, context);
            this.connManager.routeComplete(managedConn, route, context);
        }
        final int timeout = config.getSocketTimeout();
        if (timeout >= 0) {
            managedConn.setSocketTimeout(timeout);
        }

        HttpHost target = null;
        final HttpRequest original = request.getOriginal();
        if (original instanceof HttpUriRequest) {
            final URI uri = ((HttpUriRequest) original).getURI();
            if (uri.isAbsolute()) {
                target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
            }
        }
        if (target == null) {
            target = route.getTargetHost();
        }

        context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
        context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
        context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(HttpClientContext.HTTP_ROUTE, route);

        httpProcessor.process(request, context);
        final HttpResponse response = requestExecutor.execute(request, managedConn, context);
        httpProcessor.process(response, context);

        // The connection is in or can be brought to a re-usable state.
        if (reuseStrategy.keepAlive(response, context)) {
            // Set the idle duration of this connection
            final long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
            releaseTrigger.setValidFor(duration, TimeUnit.MILLISECONDS);
            releaseTrigger.markReusable();
        } else {
            releaseTrigger.markNonReusable();
        }

        // check for entity, release connection if possible
        final HttpEntity entity = response.getEntity();
        if (entity == null || !entity.isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            releaseTrigger.releaseConnection();
            return Proxies.enhanceResponse(response, null);
        } else {
            return Proxies.enhanceResponse(response, releaseTrigger);
        }
    } catch (final ConnectionShutdownException ex) {
        final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down");
        ioex.initCause(ex);
        throw ioex;
    } catch (final HttpException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final IOException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    } catch (final RuntimeException ex) {
        releaseTrigger.abortConnection();
        throw ex;
    }
}

From source file:org.apache.http.impl.execchain.ProtocolExec.java

public CloseableHttpResponse execute(final HttpRoute route, final HttpRequestWrapper request,
        final HttpClientContext context, final HttpExecutionAware execAware) throws IOException, HttpException {
    Args.notNull(route, "HTTP route");
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final HttpRequest original = request.getOriginal();
    URI uri = null;/*  ww w . ja  va  2  s.  c  o  m*/
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    request.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(request, route);

    final HttpParams params = request.getParams();
    HttpHost virtualHost = (HttpHost) params.getParameter(ClientPNames.VIRTUAL_HOST);
    // HTTPCLIENT-1092 - add the port if necessary
    if (virtualHost != null && virtualHost.getPort() == -1) {
        final int port = route.getTargetHost().getPort();
        if (port != -1) {
            virtualHost = new HttpHost(virtualHost.getHostName(), port, virtualHost.getSchemeName());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Using virtual host" + virtualHost);
        }
    }

    HttpHost target = null;
    if (virtualHost != null) {
        target = virtualHost;
    } else {
        if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
            target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        }
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            CredentialsProvider credsProvider = context.getCredentialsProvider();
            if (credsProvider == null) {
                credsProvider = new BasicCredentialsProvider();
                context.setCredentialsProvider(credsProvider);
            }
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    // Run request protocol interceptors
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    context.setAttribute(HttpCoreContext.HTTP_REQUEST, request);

    this.httpProcessor.process(request, context);

    final CloseableHttpResponse response = this.requestExecutor.execute(route, request, context, execAware);
    try {
        // Run response protocol interceptors
        context.setAttribute(HttpCoreContext.HTTP_RESPONSE, response);
        this.httpProcessor.process(response, context);
        return response;
    } catch (final RuntimeException ex) {
        response.close();
        throw ex;
    } catch (final IOException ex) {
        response.close();
        throw ex;
    } catch (final HttpException ex) {
        response.close();
        throw ex;
    }
}

From source file:org.apache.http.impl.nio.client.MainClientExec.java

private void prepareRequest(final InternalState state, final AbstractClientExchangeHandler<?> handler)
        throws IOException, HttpException {
    final HttpClientContext localContext = state.getLocalContext();
    final HttpRequestWrapper currentRequest = handler.getCurrentRequest();
    final HttpRoute route = handler.getRoute();

    final HttpRequest original = currentRequest.getOriginal();
    URI uri = null;//from   ww w . j  a va  2 s. com
    if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
    } else {
        final String uriString = original.getRequestLine().getUri();
        try {
            uri = URI.create(uriString);
        } catch (final IllegalArgumentException ex) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Unable to parse '" + uriString + "' as a valid URI; "
                        + "request URI and Host header may be inconsistent", ex);
            }
        }

    }
    currentRequest.setURI(uri);

    // Re-write request URI if needed
    rewriteRequestURI(currentRequest, route);

    HttpHost target = null;
    if (uri != null && uri.isAbsolute() && uri.getHost() != null) {
        target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    }
    if (target == null) {
        target = route.getTargetHost();
    }

    // Get user info from the URI
    if (uri != null) {
        final String userinfo = uri.getUserInfo();
        if (userinfo != null) {
            final CredentialsProvider credsProvider = localContext.getCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(userinfo));
        }
    }

    localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, currentRequest);
    localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);
    this.httpProcessor.process(currentRequest, localContext);
}

From source file:org.apache.http.impl.nio.client.MinimalClientExchangeHandlerImpl.java

public void start() throws HttpException, IOException {
    final HttpHost target = this.requestProducer.getTarget();
    final HttpRequest original = this.requestProducer.generateRequest();

    if (original instanceof HttpExecutionAware) {
        ((HttpExecutionAware) original).setCancellable(this);
    }/*from   w w w. ja  v  a2  s .c  om*/
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + getId() + "] start execution");
    }

    if (original instanceof Configurable) {
        final RequestConfig config = ((Configurable) original).getConfig();
        if (config != null) {
            this.localContext.setRequestConfig(config);
        }
    }

    final HttpRequestWrapper request = HttpRequestWrapper.wrap(original);
    final HttpRoute route = new HttpRoute(target);
    setCurrentRequest(request);
    setRoute(route);

    this.localContext.setAttribute(HttpCoreContext.HTTP_REQUEST, request);
    this.localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target);
    this.localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);

    this.httpProcessor.process(request, this.localContext);

    requestConnection();
}

From source file:org.apache.http.impl.nio.client.PipeliningClientExchangeHandlerImpl.java

public void start() throws HttpException, IOException {
    if (this.log.isDebugEnabled()) {
        this.log.debug("[exchange: " + getId() + "] start execution");
    }//from  w ww .j  ava  2 s . co  m

    final HttpRoute route = new HttpRoute(this.target);
    setRoute(route);

    this.localContext.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    this.localContext.setAttribute(HttpClientContext.HTTP_ROUTE, route);

    requestConnection();
}