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.client.CloseableHttpClient.java

/**
 * {@inheritDoc}/*  ww  w  .  j  a  v  a  2  s. c  o m*/
 */
public CloseableHttpResponse execute(final HttpUriRequest request, final HttpContext context)
        throws IOException, ClientProtocolException {
    Args.notNull(request, "HTTP request");
    return doExecute(determineTarget(request), request, context);
}

From source file:org.apache.http.impl.client.CloseableHttpClient.java

/**
 * Executes a request using the default context and processes the
 * response using the given response handler. The content entity associated
 * with the response is fully consumed and the underlying connection is
 * released back to the connection manager automatically in all cases
 * relieving individual {@link ResponseHandler}s from having to manage
 * resource deallocation internally./*from  ww w . j a  v a 2s .  co  m*/
 *
 * @param target    the target host for the request.
 *                  Implementations may accept <code>null</code>
 *                  if they can still determine a route, for example
 *                  to a default target or by inspecting the request.
 * @param request   the request to execute
 * @param responseHandler the response handler
 * @param context   the context to use for the execution, or
 *                  <code>null</code> to use the default context
 *
 * @return  the response object as generated by the response handler.
 * @throws IOException in case of a problem or the connection was aborted
 * @throws ClientProtocolException in case of an http protocol error
 */
public <T> T execute(final HttpHost target, final HttpRequest request,
        final ResponseHandler<? extends T> responseHandler, final HttpContext context)
        throws IOException, ClientProtocolException {
    Args.notNull(responseHandler, "Response handler");

    final HttpResponse response = execute(target, request, context);

    final T result;
    try {
        result = responseHandler.handleResponse(response);
    } catch (final Exception t) {
        final HttpEntity entity = response.getEntity();
        try {
            EntityUtils.consume(entity);
        } catch (final Exception t2) {
            // Log this exception. The original exception is more
            // important and will be thrown to the caller.
            this.log.warn("Error consuming content after an exception.", t2);
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        throw new UndeclaredThrowableException(t);
    }

    // Handling the response was successful. Ensure that the content has
    // been fully consumed.
    final HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    return result;
}

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
    Args.notNull(response, "HTTP response");

    final int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        final String method = request.getRequestLine().getMethod();
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default:/*from   www .j a  va  2  s . co  m*/
        return false;
    } //end of switch
}

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public URI getLocationURI(final HttpResponse response, final HttpContext context) throws ProtocolException {
    Args.notNull(response, "HTTP response");
    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }/*from   w ww .j a  v a 2s . c  o  m*/
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri;
    try {
        uri = new URI(location);
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }

    final HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        final HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        Asserts.notNull(target, "Target host");

        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);

        try {
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (final URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        final URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (final URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:org.apache.http.impl.client.DefaultRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    Args.notNull(request, "HTTP request");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    //get the location header to find out where to redirect to
    final Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }//from w  w w.j a  va  2 s .co  m
    final String location = locationHeader.getValue();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    final RequestConfig config = clientContext.getRequestConfig();

    URI uri = createLocationURI(location);

    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    try {
        if (!uri.isAbsolute()) {
            if (!config.isRelativeRedirectsAllowed()) {
                throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
            }
            // Adjust location URI
            final HttpHost target = clientContext.getTargetHost();
            Asserts.notNull(target, "Target host");
            final URI requestURI = new URI(request.getRequestLine().getUri());
            final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, false);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocations redirectLocations = (RedirectLocations) clientContext
            .getAttribute(HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocations();
        context.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
    }
    if (!config.isCircularRedirectsAllowed()) {
        if (redirectLocations.contains(uri)) {
            throw new CircularRedirectException("Circular redirect to '" + uri + "'");
        }
    }
    redirectLocations.add(uri);
    return uri;
}

From source file:org.apache.http.impl.client.DefaultRequestDirector.java

/**
 * @since 4.2//from   w  w  w  .  j  a va  2  s.c om
 */
public DefaultRequestDirector(final Log log, final HttpRequestExecutor requestExec,
        final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat,
        final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan,
        final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler,
        final RedirectStrategy redirectStrategy, final AuthenticationStrategy targetAuthStrategy,
        final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler,
        final HttpParams params) {

    Args.notNull(log, "Log");
    Args.notNull(requestExec, "Request executor");
    Args.notNull(conman, "Client connection manager");
    Args.notNull(reustrat, "Connection reuse strategy");
    Args.notNull(kastrat, "Connection keep alive strategy");
    Args.notNull(rouplan, "Route planner");
    Args.notNull(httpProcessor, "HTTP protocol processor");
    Args.notNull(retryHandler, "HTTP request retry handler");
    Args.notNull(redirectStrategy, "Redirect strategy");
    Args.notNull(targetAuthStrategy, "Target authentication strategy");
    Args.notNull(proxyAuthStrategy, "Proxy authentication strategy");
    Args.notNull(userTokenHandler, "User token handler");
    Args.notNull(params, "HTTP parameters");
    this.log = log;
    this.authenticator = new HttpAuthenticator(log);
    this.requestExec = requestExec;
    this.connManager = conman;
    this.reuseStrategy = reustrat;
    this.keepAliveStrategy = kastrat;
    this.routePlanner = rouplan;
    this.httpProcessor = httpProcessor;
    this.retryHandler = retryHandler;
    this.redirectStrategy = redirectStrategy;
    this.targetAuthStrategy = targetAuthStrategy;
    this.proxyAuthStrategy = proxyAuthStrategy;
    this.userTokenHandler = userTokenHandler;
    this.params = params;

    if (redirectStrategy instanceof DefaultRedirectStrategyAdaptor) {
        this.redirectHandler = ((DefaultRedirectStrategyAdaptor) redirectStrategy).getHandler();
    } else {
        this.redirectHandler = null;
    }
    if (targetAuthStrategy instanceof AuthenticationStrategyAdaptor) {
        this.targetAuthHandler = ((AuthenticationStrategyAdaptor) targetAuthStrategy).getHandler();
    } else {
        this.targetAuthHandler = null;
    }
    if (proxyAuthStrategy instanceof AuthenticationStrategyAdaptor) {
        this.proxyAuthHandler = ((AuthenticationStrategyAdaptor) proxyAuthStrategy).getHandler();
    } else {
        this.proxyAuthHandler = null;
    }

    this.managedConn = null;

    this.execCount = 0;
    this.redirectCount = 0;
    this.targetAuthState = new AuthState();
    this.proxyAuthState = new AuthState();
    this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
}

From source file:org.apache.http.impl.client.InternalHttpClient.java

public InternalHttpClient(final ClientExecChain execChain, final HttpClientConnectionManager connManager,
        final HttpRoutePlanner routePlanner, final Lookup<CookieSpecProvider> cookieSpecRegistry,
        final Lookup<AuthSchemeProvider> authSchemeRegistry, final CookieStore cookieStore,
        final CredentialsProvider credentialsProvider, final RequestConfig defaultConfig,
        final List<Closeable> closeables) {
    super();//from   w w w  . ja va  2s.  co  m
    Args.notNull(execChain, "HTTP client exec chain");
    Args.notNull(connManager, "HTTP connection manager");
    Args.notNull(routePlanner, "HTTP route planner");
    this.execChain = execChain;
    this.connManager = connManager;
    this.routePlanner = routePlanner;
    this.cookieSpecRegistry = cookieSpecRegistry;
    this.authSchemeRegistry = authSchemeRegistry;
    this.cookieStore = cookieStore;
    this.credentialsProvider = credentialsProvider;
    this.defaultConfig = defaultConfig;
    this.closeables = closeables;
}

From source file:org.apache.http.impl.client.InternalHttpClient.java

@Override
protected CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request,
        final HttpContext context) throws IOException, ClientProtocolException {
    Args.notNull(request, "HTTP request");
    HttpExecutionAware execAware = null;
    if (request instanceof HttpExecutionAware) {
        execAware = (HttpExecutionAware) request;
    }//w w w . j ava  2s  . co  m
    try {
        final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request);
        final HttpClientContext localcontext = HttpClientContext
                .adapt(context != null ? context : new BasicHttpContext());
        RequestConfig config = null;
        if (request instanceof Configurable) {
            config = ((Configurable) request).getConfig();
        }
        if (config == null) {
            final HttpParams params = request.getParams();
            if (params instanceof HttpParamsNames) {
                if (!((HttpParamsNames) params).getNames().isEmpty()) {
                    config = HttpClientParamConfig.getRequestConfig(params);
                }
            } else {
                config = HttpClientParamConfig.getRequestConfig(params);
            }
        }
        if (config != null) {
            localcontext.setRequestConfig(config);
        }
        setupContext(localcontext);
        final HttpRoute route = determineRoute(target, wrapper, localcontext);
        return this.execChain.execute(route, wrapper, localcontext, execAware);
    } catch (final HttpException httpException) {
        throw new ClientProtocolException(httpException);
    }
}

From source file:org.apache.http.impl.conn.BasicClientConnectionManager.java

/**
 * Creates a new simple connection manager.
 *
 * @param schreg    the scheme registry//from  w  w w .j a  v  a2 s  . c o  m
 */
public BasicClientConnectionManager(final SchemeRegistry schreg) {
    Args.notNull(schreg, "Scheme registry");
    this.schemeRegistry = schreg;
    this.connOperator = createConnectionOperator(schreg);
}

From source file:org.apache.http.impl.conn.BasicClientConnectionManager.java

ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "Route");
    synchronized (this) {
        assertNotShutdown();/*www. j ava 2s .  c om*/
        if (this.log.isDebugEnabled()) {
            this.log.debug("Get connection for route " + route);
        }
        Asserts.check(this.conn == null, MISUSE_MESSAGE);
        if (this.poolEntry != null && !this.poolEntry.getPlannedRoute().equals(route)) {
            this.poolEntry.close();
            this.poolEntry = null;
        }
        if (this.poolEntry == null) {
            final String id = Long.toString(COUNTER.getAndIncrement());
            final OperatedClientConnection conn = this.connOperator.createConnection();
            this.poolEntry = new HttpPoolEntry(this.log, id, route, conn, 0, TimeUnit.MILLISECONDS);
        }
        final long now = System.currentTimeMillis();
        if (this.poolEntry.isExpired(now)) {
            this.poolEntry.close();
            this.poolEntry.getTracker().reset();
        }
        this.conn = new ManagedClientConnectionImpl(this, this.connOperator, this.poolEntry);
        return this.conn;
    }
}