Example usage for org.apache.http.util Args notNull

List of usage examples for org.apache.http.util Args notNull

Introduction

In this page you can find the example usage for org.apache.http.util Args notNull.

Prototype

public static <T> T notNull(T t, String str) 

Source Link

Usage

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

public ProtocolExec(final ClientExecChain requestExecutor, final HttpProcessor httpProcessor) {
    Args.notNull(requestExecutor, "HTTP client request executor");
    Args.notNull(httpProcessor, "HTTP protocol processor");
    this.requestExecutor = requestExecutor;
    this.httpProcessor = httpProcessor;
}

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;//w w w.java 2  s.c om
    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.execchain.RedirectExec.java

public RedirectExec(final ClientExecChain requestExecutor, final HttpRoutePlanner routePlanner,
        final RedirectStrategy redirectStrategy) {
    super();//from  ww  w .  j a va 2  s  . c o  m
    Args.notNull(requestExecutor, "HTTP client request executor");
    Args.notNull(routePlanner, "HTTP route planner");
    Args.notNull(redirectStrategy, "HTTP redirect strategy");
    this.requestExecutor = requestExecutor;
    this.routePlanner = routePlanner;
    this.redirectStrategy = redirectStrategy;
}

From source file:org.apache.http.impl.execchain.RedirectExec.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 List<URI> redirectLocations = context.getRedirectLocations();
    if (redirectLocations != null) {
        redirectLocations.clear();//from w  w  w. j av a2  s .c  o  m
    }

    final RequestConfig config = context.getRequestConfig();
    final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
    HttpRoute currentRoute = route;
    HttpRequestWrapper currentRequest = request;
    for (int redirectCount = 0;;) {
        final CloseableHttpResponse response = requestExecutor.execute(currentRoute, currentRequest, context,
                execAware);
        try {
            if (config.isRedirectsEnabled()
                    && this.redirectStrategy.isRedirected(currentRequest, response, context)) {

                if (redirectCount >= maxRedirects) {
                    throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
                }
                redirectCount++;

                final HttpRequest redirect = this.redirectStrategy.getRedirect(currentRequest, response,
                        context);
                if (!redirect.headerIterator().hasNext()) {
                    final HttpRequest original = request.getOriginal();
                    redirect.setHeaders(original.getAllHeaders());
                }
                currentRequest = HttpRequestWrapper.wrap(redirect);

                if (currentRequest instanceof HttpEntityEnclosingRequest) {
                    Proxies.enhanceEntity((HttpEntityEnclosingRequest) currentRequest);
                }

                final URI uri = currentRequest.getURI();
                final HttpHost newTarget = URIUtils.extractHost(uri);
                if (newTarget == null) {
                    throw new ProtocolException("Redirect URI does not specify a valid host name: " + uri);
                }

                // Reset virtual host and auth states if redirecting to another host
                if (!currentRoute.getTargetHost().equals(newTarget)) {
                    final AuthState targetAuthState = context.getTargetAuthState();
                    if (targetAuthState != null) {
                        this.log.debug("Resetting target auth state");
                        targetAuthState.reset();
                    }
                    final AuthState proxyAuthState = context.getProxyAuthState();
                    if (proxyAuthState != null) {
                        final AuthScheme authScheme = proxyAuthState.getAuthScheme();
                        if (authScheme != null && authScheme.isConnectionBased()) {
                            this.log.debug("Resetting proxy auth state");
                            proxyAuthState.reset();
                        }
                    }
                }

                currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Redirecting to '" + uri + "' via " + currentRoute);
                }
                EntityUtils.consume(response.getEntity());
                response.close();
            } else {
                return response;
            }
        } catch (final RuntimeException ex) {
            response.close();
            throw ex;
        } catch (final IOException ex) {
            response.close();
            throw ex;
        } catch (final HttpException ex) {
            // Protocol exception related to a direct.
            // The underlying connection may still be salvaged.
            try {
                EntityUtils.consume(response.getEntity());
            } catch (final IOException ioex) {
                this.log.debug("I/O error while releasing connection", ioex);
            } finally {
                response.close();
            }
            throw ex;
        }
    }
}

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

public RetryExec(final ClientExecChain requestExecutor, final HttpRequestRetryHandler retryHandler) {
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(retryHandler, "HTTP request retry handler");
    this.requestExecutor = requestExecutor;
    this.retryHandler = retryHandler;
}

From source file:org.apache.http.impl.execchain.RetryExec.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 Header[] origheaders = request.getAllHeaders();
    for (int execCount = 1;; execCount++) {
        try {// w  w w.  j  av  a2s.  c  o m
            return this.requestExecutor.execute(route, request, context, execAware);
        } catch (final IOException ex) {
            if (execAware != null && execAware.isAborted()) {
                this.log.debug("Request has been aborted");
                throw ex;
            }
            if (retryHandler.retryRequest(ex, execCount, context)) {
                if (this.log.isInfoEnabled()) {
                    this.log.info("I/O exception (" + ex.getClass().getName()
                            + ") caught when processing request to " + route + ": " + ex.getMessage());
                }
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage(), ex);
                }
                if (!Proxies.isRepeatable(request)) {
                    this.log.debug("Cannot retry non-repeatable request");
                    throw new NonRepeatableRequestException(
                            "Cannot retry request " + "with a non-repeatable request entity", ex);
                }
                request.setHeaders(origheaders);
                if (this.log.isInfoEnabled()) {
                    this.log.info("Retrying request to " + route);
                }
            } else {
                if (ex instanceof NoHttpResponseException) {
                    final NoHttpResponseException updatedex = new NoHttpResponseException(
                            route.getTargetHost().toHostString() + " failed to respond");
                    updatedex.setStackTrace(ex.getStackTrace());
                    throw updatedex;
                } else {
                    throw ex;
                }
            }
        }
    }
}

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

public ServiceUnavailableRetryExec(final ClientExecChain requestExecutor,
        final ServiceUnavailableRetryStrategy retryStrategy) {
    super();//from w w w. j  a  va 2s  .c  o  m
    Args.notNull(requestExecutor, "HTTP request executor");
    Args.notNull(retryStrategy, "Retry strategy");
    this.requestExecutor = requestExecutor;
    this.retryStrategy = retryStrategy;
}

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

public PipeliningClientExchangeHandlerImpl(final Log log, final HttpHost target,
        final List<? extends HttpAsyncRequestProducer> requestProducers,
        final List<? extends HttpAsyncResponseConsumer<T>> responseConsumers,
        final HttpClientContext localContext, final BasicFuture<List<T>> resultFuture,
        final NHttpClientConnectionManager connmgr, final HttpProcessor httpProcessor,
        final ConnectionReuseStrategy connReuseStrategy, final ConnectionKeepAliveStrategy keepaliveStrategy) {
    super(log, localContext, resultFuture, connmgr, connReuseStrategy, keepaliveStrategy);
    Args.notNull(target, "HTTP target");
    Args.notEmpty(requestProducers, "Request producer list");
    Args.notEmpty(responseConsumers, "Response consumer list");
    Args.check(requestProducers.size() == responseConsumers.size(),
            "Number of request producers does not match that of response consumers");
    this.target = target;
    this.requestProducerQueue = new ConcurrentLinkedQueue<HttpAsyncRequestProducer>(requestProducers);
    this.responseConsumerQueue = new ConcurrentLinkedQueue<HttpAsyncResponseConsumer<T>>(responseConsumers);
    this.requestQueue = new ConcurrentLinkedQueue<HttpRequest>();
    this.resultQueue = new ConcurrentLinkedQueue<T>();
    this.localContext = localContext;
    this.resultFuture = resultFuture;
    this.httpProcessor = httpProcessor;
    this.requestProducerRef = new AtomicReference<HttpAsyncRequestProducer>(null);
    this.responseConsumerRef = new AtomicReference<HttpAsyncResponseConsumer<T>>(null);
}

From source file:org.apache.http.impl.nio.conn.ManagedNHttpClientConnectionImpl.java

@Override
public void bind(final IOSession iosession) {
    Args.notNull(iosession, "I/O session");
    Asserts.check(!iosession.isClosed(), "I/O session is closed");
    this.status = ACTIVE;
    this.original = iosession;
    if (this.log.isDebugEnabled() || this.wirelog.isDebugEnabled()) {
        this.log.debug(this.id + " Upgrade session " + iosession);
        super.bind(new LoggingIOSession(iosession, this.id, this.log, this.wirelog));
    } else {/*from w  w  w.j a  v a  2 s  . c  o  m*/
        super.bind(iosession);
    }
}

From source file:org.apache.http.impl.nio.conn.PoolingClientAsyncConnectionManager.java

public PoolingClientAsyncConnectionManager(final ConnectingIOReactor ioreactor,
        final AsyncSchemeRegistry schemeRegistry, final long timeToLive, final TimeUnit tunit) {
    super();/*from   w w  w. j a v a 2  s . c o m*/
    Args.notNull(ioreactor, "I/O reactor");
    Args.notNull(schemeRegistry, "Scheme registory");
    Args.notNull(tunit, "Time unit");
    this.ioreactor = ioreactor;
    this.pool = new HttpNIOConnPool(this.log, ioreactor, schemeRegistry, timeToLive, tunit);
    this.schemeRegistry = schemeRegistry;
    this.connFactory = createClientAsyncConnectionFactory();
}