List of usage examples for org.apache.http.util Args notNull
public static <T> T notNull(T t, String str)
From source file:org.apache.http.impl.conn.tsccm.ConnPoolByRoute.java
/** * @since 4.1// ww w . j av a 2 s. c o m */ public ConnPoolByRoute(final ClientConnectionOperator operator, final ConnPerRoute connPerRoute, final int maxTotalConnections, final long connTTL, final TimeUnit connTTLTimeUnit) { super(); Args.notNull(operator, "Connection operator"); Args.notNull(connPerRoute, "Connections per route"); this.poolLock = super.poolLock; this.leasedConnections = super.leasedConnections; this.operator = operator; this.connPerRoute = connPerRoute; this.maxTotalConnections = maxTotalConnections; this.freeConnections = createFreeConnQueue(); this.waitingThreads = createWaitingThreadQueue(); this.routeToPool = createRouteToPoolMap(); this.connTTL = connTTL; this.connTTLTimeUnit = connTTLTimeUnit; }
From source file:org.apache.http.impl.conn.tsccm.ConnPoolByRoute.java
/** * Closes idle connections.// ww w. j a v a 2s. c om * * @param idletime the time the connections should have been idle * in order to be closed now * @param tunit the unit for the <code>idletime</code> */ @Override public void closeIdleConnections(final long idletime, final TimeUnit tunit) { Args.notNull(tunit, "Time unit"); final long t = idletime > 0 ? idletime : 0; if (log.isDebugEnabled()) { log.debug("Closing connections idle longer than " + t + " " + tunit); } // the latest time for which connections will be closed final long deadline = System.currentTimeMillis() - tunit.toMillis(t); poolLock.lock(); try { final Iterator<BasicPoolEntry> iter = freeConnections.iterator(); while (iter.hasNext()) { final BasicPoolEntry entry = iter.next(); if (entry.getUpdated() <= deadline) { if (log.isDebugEnabled()) { log.debug("Closing connection last used @ " + new Date(entry.getUpdated())); } iter.remove(); deleteEntry(entry); } } } finally { poolLock.unlock(); } }
From source file:org.apache.http.impl.conn.tsccm.RouteSpecificPool.java
/** * Adds a waiting thread.//from w ww.ja v a 2 s. c o m * This pool makes no attempt to match waiting threads with pool entries. * It is the caller's responsibility to check that there is no entry * before adding a waiting thread. * * @param wt the waiting thread */ public void queueThread(final WaitingThread wt) { Args.notNull(wt, "Waiting thread"); this.waitingThreads.add(wt); }
From source file:org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.java
/** * Creates a new thread safe connection manager. * * @param schreg the scheme registry. * @param connTTL max connection lifetime, <=0 implies "infinity" * @param connTTLTimeUnit TimeUnit of connTTL * @param connPerRoute mapping of maximum connections per route, * provided as a dependency so it can be managed externally, e.g. * for dynamic connection pool size management. * * @since 4.2/*from ww w . j a v a2 s.c o m*/ */ public ThreadSafeClientConnManager(final SchemeRegistry schreg, final long connTTL, final TimeUnit connTTLTimeUnit, final ConnPerRouteBean connPerRoute) { super(); Args.notNull(schreg, "Scheme registry"); this.log = LogFactory.getLog(getClass()); this.schemeRegistry = schreg; this.connPerRoute = connPerRoute; this.connOperator = createConnectionOperator(schreg); this.pool = createConnectionPool(connTTL, connTTLTimeUnit); this.connectionPool = this.pool; }
From source file:org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.java
/** * Creates a new thread safe connection manager. * * @param params the parameters for this manager. * @param schreg the scheme registry. * * @deprecated (4.1) use {@link ThreadSafeClientConnManager#ThreadSafeClientConnManager(SchemeRegistry)} *//*from w w w . j a va2s .c o m*/ @Deprecated public ThreadSafeClientConnManager(final HttpParams params, final SchemeRegistry schreg) { Args.notNull(schreg, "Scheme registry"); this.log = LogFactory.getLog(getClass()); this.schemeRegistry = schreg; this.connPerRoute = new ConnPerRouteBean(); this.connOperator = createConnectionOperator(schreg); this.pool = (ConnPoolByRoute) createConnectionPool(params); this.connectionPool = this.pool; }
From source file:org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.java
public ClientConnectionRequest requestConnection(final HttpRoute route, final Object state) { final PoolEntryRequest poolRequest = pool.requestPoolEntry(route, state); return new ClientConnectionRequest() { public void abortRequest() { poolRequest.abortRequest();// w w w .j a va2 s. co m } public ManagedClientConnection getConnection(final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { Args.notNull(route, "Route"); if (log.isDebugEnabled()) { log.debug("Get connection: " + route + ", timeout = " + timeout); } final BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit); return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry); } }; }
From source file:org.apache.http.impl.execchain.MainClientExec.java
public MainClientExec(final HttpRequestExecutor requestExecutor, final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepAliveStrategy, final AuthenticationStrategy targetAuthStrategy, final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler) { Args.notNull(requestExecutor, "HTTP request executor"); Args.notNull(connManager, "Client connection manager"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); Args.notNull(targetAuthStrategy, "Target authentication strategy"); Args.notNull(proxyAuthStrategy, "Proxy authentication strategy"); Args.notNull(userTokenHandler, "User token handler"); this.authenticator = new HttpAuthenticator(); this.proxyHttpProcessor = new ImmutableHttpProcessor(new RequestTargetHost(), new RequestClientConnControl()); this.routeDirector = new BasicRouteDirector(); this.requestExecutor = requestExecutor; this.connManager = connManager; this.reuseStrategy = reuseStrategy; this.keepAliveStrategy = keepAliveStrategy; this.targetAuthStrategy = targetAuthStrategy; this.proxyAuthStrategy = proxyAuthStrategy; this.userTokenHandler = userTokenHandler; }
From source file:org.apache.http.impl.execchain.MainClientExec.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"); AuthState targetAuthState = context.getTargetAuthState(); if (targetAuthState == null) { targetAuthState = new AuthState(); context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, targetAuthState); }// w w w . j av a 2s . c om AuthState proxyAuthState = context.getProxyAuthState(); if (proxyAuthState == null) { proxyAuthState = new AuthState(); context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, proxyAuthState); } if (request instanceof HttpEntityEnclosingRequest) { Proxies.enhanceEntity((HttpEntityEnclosingRequest) request); } Object userToken = context.getUserToken(); final ConnectionRequest connRequest = connManager.requestConnection(route, userToken); 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); } context.setAttribute(HttpCoreContext.HTTP_CONNECTION, managedConn); if (config.isStaleConnectionCheckEnabled()) { // validate connection if (managedConn.isOpen()) { this.log.debug("Stale connection check"); if (managedConn.isStale()) { this.log.debug("Stale connection detected"); managedConn.close(); } } } final ConnectionHolder connHolder = new ConnectionHolder(this.log, this.connManager, managedConn); try { if (execAware != null) { execAware.setCancellable(connHolder); } HttpResponse response; for (int execCount = 1;; execCount++) { if (execCount > 1 && !Proxies.isRepeatable(request)) { throw new NonRepeatableRequestException( "Cannot retry request " + "with a non-repeatable request entity."); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (!managedConn.isOpen()) { this.log.debug("Opening connection " + route); try { establishRoute(proxyAuthState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { if (this.log.isDebugEnabled()) { this.log.debug(ex.getMessage()); } response = ex.getResponse(); break; } } final int timeout = config.getSocketTimeout(); if (timeout >= 0) { managedConn.setSocketTimeout(timeout); } if (execAware != null && execAware.isAborted()) { throw new RequestAbortedException("Request aborted"); } if (this.log.isDebugEnabled()) { this.log.debug("Executing request " + request.getRequestLine()); } if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) { if (this.log.isDebugEnabled()) { this.log.debug("Target auth state: " + targetAuthState.getState()); } this.authenticator.generateAuthResponse(request, targetAuthState, context); } if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) { if (this.log.isDebugEnabled()) { this.log.debug("Proxy auth state: " + proxyAuthState.getState()); } this.authenticator.generateAuthResponse(request, proxyAuthState, context); } response = requestExecutor.execute(request, managedConn, 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); if (this.log.isDebugEnabled()) { final String s; if (duration > 0) { s = "for " + duration + " " + TimeUnit.MILLISECONDS; } else { s = "indefinitely"; } this.log.debug("Connection can be kept alive " + s); } connHolder.setValidFor(duration, TimeUnit.MILLISECONDS); connHolder.markReusable(); } else { connHolder.markNonReusable(); } if (needAuthentication(targetAuthState, proxyAuthState, route, response, context)) { // Make sure the response body is fully consumed, if present final HttpEntity entity = response.getEntity(); if (connHolder.isReusable()) { EntityUtils.consume(entity); } else { managedConn.close(); if (proxyAuthState.getState() == AuthProtocolState.SUCCESS && proxyAuthState.getAuthScheme() != null && proxyAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting proxy auth state"); proxyAuthState.reset(); } if (targetAuthState.getState() == AuthProtocolState.SUCCESS && targetAuthState.getAuthScheme() != null && targetAuthState.getAuthScheme().isConnectionBased()) { this.log.debug("Resetting target auth state"); targetAuthState.reset(); } } // discard previous auth headers final HttpRequest original = request.getOriginal(); if (!original.containsHeader(AUTH.WWW_AUTH_RESP)) { request.removeHeaders(AUTH.WWW_AUTH_RESP); } if (!original.containsHeader(AUTH.PROXY_AUTH_RESP)) { request.removeHeaders(AUTH.PROXY_AUTH_RESP); } } else { break; } } if (userToken == null) { userToken = userTokenHandler.getUserToken(context); context.setAttribute(HttpClientContext.USER_TOKEN, userToken); } if (userToken != null) { connHolder.setState(userToken); } // 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 connHolder.releaseConnection(); return Proxies.enhanceResponse(response, null); } else { return Proxies.enhanceResponse(response, connHolder); } } catch (final ConnectionShutdownException ex) { final InterruptedIOException ioex = new InterruptedIOException("Connection has been shut down"); ioex.initCause(ex); throw ioex; } catch (final HttpException ex) { connHolder.abortConnection(); throw ex; } catch (final IOException ex) { connHolder.abortConnection(); throw ex; } catch (final RuntimeException ex) { connHolder.abortConnection(); throw ex; } }
From source file:org.apache.http.impl.execchain.MinimalClientExec.java
public MinimalClientExec(final HttpRequestExecutor requestExecutor, final HttpClientConnectionManager connManager, final ConnectionReuseStrategy reuseStrategy, final ConnectionKeepAliveStrategy keepAliveStrategy) { Args.notNull(requestExecutor, "HTTP request executor"); Args.notNull(connManager, "Client connection manager"); Args.notNull(reuseStrategy, "Connection reuse strategy"); Args.notNull(keepAliveStrategy, "Connection keep alive strategy"); this.httpProcessor = new ImmutableHttpProcessor(new RequestContent(), new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent( VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", getClass()))); this.requestExecutor = requestExecutor; this.connManager = connManager; this.reuseStrategy = reuseStrategy; this.keepAliveStrategy = keepAliveStrategy; }
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);//w ww. j a v a2s .co m 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; } }