public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { if (route == null) { throw new IllegalArgumentException("HTTP route may not be null"); } if (this.log.isDebugEnabled()) { this.log.debug("Connection request: " + format(route, state) + formatStats(route)); } final Future<HttpPoolEntry> future = this.pool.lease(route, state); return new ClientConnectionRequest() { public void abortRequest() { future.cancel(true); } public ManagedClientConnection getConnection( final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { return leaseConnection(future, timeout, tunit); } }; }
@Test(timeout = 60 * 1000) public void leasing_a_new_connection_fails_with_connection_pool_timeout() throws Exception { String localhostEndpoint = "http://localhost:" + server.getPort(); AmazonHttpClient httpClient = new AmazonHttpClient( new ClientConfiguration() .withMaxConnections(1) .withConnectionTimeout(100) .withMaxErrorRetry(0)); Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET); // Block the first connection in the pool with this request. httpClient.requestExecutionBuilder().request(request).execute(new EmptyAWSResponseHandler()); try { // A new connection will be leased here which would fail in // ConnectionPoolTimeoutException. httpClient.requestExecutionBuilder().request(request).execute(); Assert.fail("Connection pool timeout exception is expected!"); } catch (AmazonClientException e) { Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException); } }
public ConnectionRequest requestConnection( final HttpRoute route, final Object state) { Args.notNull(route, "HTTP route"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Connection request: " + format(route, state) + formatStats(route)); } final Future<CPoolEntry> future = this.pool.lease(route, state, null); return new ConnectionRequest() { public boolean cancel() { return future.cancel(true); } public HttpClientConnection get( final long timeout, final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { return leaseConnection(future, timeout, tunit); } }; }
protected HttpClientConnection leaseConnection( final Future<CPoolEntry> future, final long timeout, final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final CPoolEntry entry; try { entry = future.get(timeout, tunit); if (entry == null || future.isCancelled()) { throw new InterruptedException(); } Asserts.check(entry.getConnection() != null, "Pool entry with no connection"); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Connection leased: " + format(entry) + formatStats(entry.getRoute())); } return CPoolProxy.newProxy(entry); } catch (final TimeoutException ex) { throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); } }
@Override public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { Args.notNull(route, "HTTP route"); if (this.log.isDebugEnabled()) { this.log.debug("Connection request: " + format(route, state) + formatStats(route)); } final Future<HttpPoolEntry> future = this.pool.lease(route, state); return new ClientConnectionRequest() { @Override public void abortRequest() { future.cancel(true); } @Override public ManagedClientConnection getConnection( final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { return leaseConnection(future, timeout, tunit); } }; }
@Override public ConnectionRequest requestConnection( final HttpRoute route, final Object state) { Args.notNull(route, "HTTP route"); if (this.log.isDebugEnabled()) { this.log.debug("Connection request: " + format(route, state) + formatStats(route)); } final Future<CPoolEntry> future = this.pool.lease(route, state, null); return new ConnectionRequest() { @Override public boolean cancel() { return future.cancel(true); } @Override public HttpClientConnection get( final long timeout, final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { return leaseConnection(future, timeout, tunit); } }; }
protected HttpClientConnection leaseConnection( final Future<CPoolEntry> future, final long timeout, final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { final CPoolEntry entry; try { entry = future.get(timeout, tunit); if (entry == null || future.isCancelled()) { throw new InterruptedException(); } Asserts.check(entry.getConnection() != null, "Pool entry with no connection"); if (this.log.isDebugEnabled()) { this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute())); } return CPoolProxy.newProxy(entry); } catch (final TimeoutException ex) { throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool"); } }
public final ClientConnectionRequest requestConnection(final HttpRoute paramHttpRoute, Object paramObject) { new ClientConnectionRequest() { public final void abortRequest() { this.val$poolRequest.abortRequest(); } public final ManagedClientConnection getConnection(long paramAnonymousLong, TimeUnit paramAnonymousTimeUnit) throws InterruptedException, ConnectionPoolTimeoutException { if (paramHttpRoute == null) { throw new IllegalArgumentException("Route may not be null."); } BasicPoolEntry localBasicPoolEntry = this.val$poolRequest.getPoolEntry(paramAnonymousLong, paramAnonymousTimeUnit); return new ElegantThreadSafeConnManager.ElegantBasicPooledConnAdapter(ElegantThreadSafeConnManager.this, localBasicPoolEntry); } }; }
public final PoolEntryRequest requestPoolEntry(final HttpRoute paramHttpRoute, final Object paramObject) { new PoolEntryRequest() { public final void abortRequest() { ElegantThreadSafeConnManager.ElegantPool.this.poolLock.lock(); try { this.val$aborter.abort(); return; } finally { ElegantThreadSafeConnManager.ElegantPool.this.poolLock.unlock(); } } public final BasicPoolEntry getPoolEntry(long paramAnonymousLong, TimeUnit paramAnonymousTimeUnit) throws InterruptedException, ConnectionPoolTimeoutException { return ElegantThreadSafeConnManager.ElegantPool.this.getEntryBlocking(paramHttpRoute, paramObject, paramAnonymousLong, paramAnonymousTimeUnit, this.val$aborter); } }; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The following exceptions will be whitelisted, i.e.: When an exception // of this type is raised, the request will be retried. AsyncHttpClient.allowRetryExceptionClass(IOException.class); AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class); AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class); // The following exceptions will be blacklisted, i.e.: When an exception // of this type is raised, the request will not be retried and it will // fail immediately. AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class); AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); }
private void handleException(String message, Exception e, User user) { if (e instanceof HttpClientErrorException) { String responseBody = ((HttpClientErrorException) e).getResponseBodyAsString(); // if unauthorized if (((HttpClientErrorException) e).getStatusCode() == HttpStatus.UNAUTHORIZED) { logger.info("Auth problem with user " + user + ". Resetting token. The problem is due to exception: " + e.getMessage() + "; Response body: " + responseBody); user.getGooglePlusSettings().setDisconnectReason(e.getMessage()); helper.forciblyDisconnect(this, user); } else { logger.warn(message + ": " + e.getMessage() + " : " + ExceptionUtils.getRootCauseMessage(e) + "; Response body: " + responseBody); } } else if (e.getCause() instanceof ConnectionPoolTimeoutException || e.getCause() instanceof SocketTimeoutException) { logger.warn("Google+ timeout (for user: " + user + ") " + ExceptionUtils.getRootCauseMessage(e)); } else { logger.warn(message, e); } }
@Override public PoolEntryRequest requestPoolEntry( final HttpRoute route, final Object state) { final WaitingThreadAborter aborter = new WaitingThreadAborter(); return new PoolEntryRequest() { public void abortRequest() { poolLock.lock(); try { aborter.abort(); } finally { poolLock.unlock(); } } public BasicPoolEntry getPoolEntry( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { return getEntryBlocking(route, state, timeout, tunit, aborter); } }; }
public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { final PoolEntryRequest poolRequest = pool.requestPoolEntry( route, state); return new ClientConnectionRequest() { public void abortRequest() { poolRequest.abortRequest(); } public ManagedClientConnection getConnection( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } if (log.isDebugEnabled()) { log.debug("Get connection: " + route + ", timeout = " + timeout); } BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit); return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry); } }; }
@Test(timeout = 60 * 1000) public void leasing_a_new_connection_fails_with_connection_pool_timeout() throws Exception { String localhostEndpoint = "http://localhost:" + server.getPort(); AmazonHttpClient httpClient = HttpTestUtils.testClientBuilder() .clientExecutionTimeout(null) .retryPolicy(RetryPolicy.NONE) .httpClient(ApacheSdkHttpClientFactory.builder() .connectionTimeout( Duration.ofMillis(100)) .maxConnections(1) .build() .createHttpClient()) .build(); Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET); // Block the first connection in the pool with this request. httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestAwsRequest.builder().build()) .executionContext(executionContext(SdkHttpFullRequestAdapter.toHttpFullRequest(request))) .execute(new EmptyAWSResponseHandler()); try { // A new connection will be leased here which would fail in // ConnectionPoolTimeoutException. httpClient.requestExecutionBuilder() .request(request) .originalRequest(NoopTestAwsRequest.builder().build()) .executionContext(executionContext(SdkHttpFullRequestAdapter.toHttpFullRequest(request))) .execute(); Assert.fail("Connection pool timeout exception is expected!"); } catch (SdkClientException e) { Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException); } }
@Override public PoolEntryRequest requestPoolEntry( final HttpRoute route, final Object state) { final WaitingThreadAborter aborter = new WaitingThreadAborter(); return new PoolEntryRequest() { @Override public void abortRequest() { poolLock.lock(); try { aborter.abort(); } finally { poolLock.unlock(); } } @Override public BasicPoolEntry getPoolEntry( final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { return getEntryBlocking(route, state, timeout, tunit, aborter); } }; }
@Override public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { final PoolEntryRequest poolRequest = pool.requestPoolEntry( route, state); return new ClientConnectionRequest() { @Override public void abortRequest() { poolRequest.abortRequest(); } @Override 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); } }; }
@Test public void testReleaseOnEntityConsumeContent() throws Exception { this.connManager.setDefaultMaxPerRoute(1); this.connManager.setMaxTotal(1); // Zero connections in the pool PoolStats stats = this.connManager.getTotalStats(); Assert.assertEquals(0, stats.getAvailable()); final HttpHost target = start(); // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); final HttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { connreq.get(250, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException expected) { } final HttpEntity e = response.getEntity(); Assert.assertNotNull(e); EntityUtils.consume(e); // Expect one connection in the pool stats = this.connManager.getTotalStats(); Assert.assertEquals(1, stats.getAvailable()); // Make sure one connection is available connreq = this.connManager.requestConnection(new HttpRoute(target), null); final HttpClientConnection conn = connreq.get(250, TimeUnit.MILLISECONDS); this.connManager.releaseConnection(conn, null, -1, null); }
@Test public void testReleaseOnEntityWriteTo() throws Exception { this.connManager.setDefaultMaxPerRoute(1); this.connManager.setMaxTotal(1); // Zero connections in the pool PoolStats stats = this.connManager.getTotalStats(); Assert.assertEquals(0, stats.getAvailable()); final HttpHost target = start(); // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); final HttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { connreq.get(250, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException expected) { } final HttpEntity e = response.getEntity(); Assert.assertNotNull(e); final ByteArrayOutputStream outsteam = new ByteArrayOutputStream(); e.writeTo(outsteam); // Expect one connection in the pool stats = this.connManager.getTotalStats(); Assert.assertEquals(1, stats.getAvailable()); // Make sure one connection is available connreq = this.connManager.requestConnection(new HttpRoute(target), null); final HttpClientConnection conn = connreq.get(250, TimeUnit.MILLISECONDS); this.connManager.releaseConnection(conn, null, -1, null); }
@Test public void testReleaseOnAbort() throws Exception { this.connManager.setDefaultMaxPerRoute(1); this.connManager.setMaxTotal(1); // Zero connections in the pool final PoolStats stats = this.connManager.getTotalStats(); Assert.assertEquals(0, stats.getAvailable()); final HttpHost target = start(); // Get some random data final HttpGet httpget = new HttpGet("/random/20000"); final HttpResponse response = this.httpclient.execute(target, httpget); ConnectionRequest connreq = this.connManager.requestConnection(new HttpRoute(target), null); try { connreq.get(250, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException expected) { } final HttpEntity e = response.getEntity(); Assert.assertNotNull(e); httpget.abort(); // Expect zero connections in the pool Assert.assertEquals(0, this.connManager.getTotalStats().getAvailable()); // Make sure one connection is available connreq = this.connManager.requestConnection(new HttpRoute(target), null); final HttpClientConnection conn = connreq.get(250, TimeUnit.MILLISECONDS); this.connManager.releaseConnection(conn, null, -1, null); }
private static HttpClientConnection getConnection( final HttpClientConnectionManager mgr, final HttpRoute route, final long timeout, final TimeUnit unit) throws ConnectionPoolTimeoutException, ExecutionException, InterruptedException { final ConnectionRequest connRequest = mgr.requestConnection(route, null); return connRequest.get(timeout, unit); }
@Override public ConnectionRequest requestConnection(final HttpRoute route, final Object state) { // If this is the redirect route, stub the return value // so-as to pretend the host is waiting on a slot... if(route.getTargetHost().getHostName().equals("localhost")) { final Thread currentThread = Thread.currentThread(); return new ConnectionRequest() { @Override public boolean cancel() { currentThread.interrupt(); return true; } @Override public HttpClientConnection get( final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { connLatch.countDown(); // notify waiter that we're getting a connection // zero usually means sleep forever, but CountDownLatch doesn't interpret it that way. if(!awaitLatch.await(timeout > 0 ? timeout : Integer.MAX_VALUE, tunit)) { throw new ConnectionPoolTimeoutException(); } return Mockito.mock(HttpClientConnection.class); } }; } else { return super.requestConnection(route, state); } }
@Override public ConnectionRequest requestConnection( final HttpRoute route, final Object state) { final Thread currentThread = Thread.currentThread(); return new ConnectionRequest() { @Override public boolean cancel() { currentThread.interrupt(); return true; } @Override public HttpClientConnection get( final long timeout, final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { connLatch.countDown(); // notify waiter that we're getting a connection // zero usually means sleep forever, but CountDownLatch doesn't interpret it that way. if(!awaitLatch.await(timeout > 0 ? timeout : Integer.MAX_VALUE, tunit)) { throw new ConnectionPoolTimeoutException(); } return Mockito.mock(HttpClientConnection.class); } }; }
@Test(expected=ConnectionPoolTimeoutException.class) public void testLeaseFutureTimeout() throws Exception { final HttpHost target = new HttpHost("localhost", 80); final HttpRoute route = new HttpRoute(target); Mockito.when(future.isCancelled()).thenReturn(Boolean.TRUE); Mockito.when(future.get(1, TimeUnit.SECONDS)).thenThrow(new TimeoutException()); Mockito.when(pool.lease(route, null, null)).thenReturn(future); final ConnectionRequest connRequest1 = mgr.requestConnection(route, null); connRequest1.get(1, TimeUnit.SECONDS); }
public ClientConnectionRequest requestConnection( final HttpRoute route, final Object state) { final PoolEntryRequest poolRequest = connectionPool.requestPoolEntry( route, state); return new ClientConnectionRequest() { public void abortRequest() { poolRequest.abortRequest(); } public ManagedClientConnection getConnection( long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { if (route == null) { throw new IllegalArgumentException("Route may not be null."); } if (log.isDebugEnabled()) { log.debug("Get connection: " + route + ", timeout = " + timeout); } BasicPoolEntry entry = poolRequest.getPoolEntry(timeout, tunit); return new BasicPooledConnAdapter(ThreadSafeClientConnManager.this, entry); } }; }
@Override protected void onResume() { super.onResume(); List<Model> projectList = center.getProjectList(); projectList.clear(); center.setContext(this.getApplicationContext()); JsonUtils.parseProjectList("/", Config.ProjectConfig, projectList); if (projectList.size() > 0) { Project project = (Project) projectList.get(0); center.setCurrentProject(project); Log.i("START", "" + projectList.size()); } AsyncHttpClient.allowRetryExceptionClass(IOException.class); AsyncHttpClient.allowRetryExceptionClass(SocketTimeoutException.class); AsyncHttpClient.allowRetryExceptionClass(ConnectTimeoutException.class); // The following exceptions will be blacklisted, i.e.: When an exception // of this type is raised, the request will not be retried and it will // fail immediately. AsyncHttpClient.blockRetryExceptionClass(UnknownHostException.class); AsyncHttpClient.blockRetryExceptionClass(ConnectionPoolTimeoutException.class); new Handler().postDelayed(r, 2000);// 2秒后关闭,并跳转到主页面 center.setIsFirstLoad(firstLoad()); }
@Override protected BasicPoolEntry getEntryBlocking(HttpRoute route, Object state, long timeout, TimeUnit tunit, WaitingThreadAborter aborter) throws ConnectionPoolTimeoutException, InterruptedException { Stopwatch stopWatch = requestTimer.start(); try { return super.getEntryBlocking(route, state, timeout, tunit, aborter); } finally { stopWatch.stop(); } }
@Override public HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { return null; }
@Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (exception == null) { throw new IllegalArgumentException( "Exception parameter may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (executionCount > getRetryCount()) { // Do not retry if over max retry count return false; } if (exception instanceof ConnectTimeoutException) { //连接超时,重试 return true; } if (exception instanceof InterruptedIOException) { //连接池等待超时 if (exception instanceof ConnectionPoolTimeoutException) { return true; } // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpRequest request = (HttpRequest) context .getAttribute(ExecutionContext.HTTP_REQUEST); if (requestIsAborted(request)) { return false; } //NoHttpResponseException if (handleAsIdempotent(request)) { // Retry if the request is considered idempotent return true; } Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT); boolean sent = (b != null && b); if (!sent || isRequestSentRetryEnabled()) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent return true; } // otherwise do not retry return false; }
@Override public ManagedClientConnection getConnection(long timeout, TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException { ManagedClientConnection res = handler.getConnection(timeout, tunit); return new MeasuredConnection(res); }
private static HttpClientConnection getConnection( final HttpClientConnectionManager mgr, final HttpRoute route) throws ConnectionPoolTimeoutException, ExecutionException, InterruptedException { final ConnectionRequest connRequest = mgr.requestConnection(route, null); return connRequest.get(0, TimeUnit.MILLISECONDS); }
/** * Tests releasing connection from #abort method called from the * main execution thread while there is no blocking I/O operation. */ @Test public void testReleaseConnectionOnAbort() throws Exception { this.connManager.setMaxTotal(1); final HttpHost target = start(); final HttpRoute route = new HttpRoute(target, null, false); final int rsplen = 8; final String uri = "/random/" + rsplen; final HttpContext context = new BasicHttpContext(); final HttpRequest request = new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1); HttpClientConnection conn = getConnection(this.connManager, route); this.connManager.connect(conn, route, 0, context); this.connManager.routeComplete(conn, route, context); context.setAttribute(HttpCoreContext.HTTP_CONNECTION, conn); context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, target); final HttpProcessor httpProcessor = new ImmutableHttpProcessor( new HttpRequestInterceptor[] { new RequestContent(), new RequestConnControl() }); final HttpRequestExecutor exec = new HttpRequestExecutor(); exec.preProcess(request, httpProcessor, context); final HttpResponse response = exec.execute(request, conn, context); Assert.assertEquals("wrong status in first response", HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // check that there are no connections available try { // this should fail quickly, connection has not been released getConnection(this.connManager, route, 100L, TimeUnit.MILLISECONDS); Assert.fail("ConnectionPoolTimeoutException should have been thrown"); } catch (final ConnectionPoolTimeoutException e) { // expected } // abort the connection Assert.assertTrue(conn instanceof HttpClientConnection); conn.shutdown(); this.connManager.releaseConnection(conn, null, -1, null); // the connection is expected to be released back to the manager conn = getConnection(this.connManager, route, 5L, TimeUnit.SECONDS); Assert.assertFalse("connection should have been closed", conn.isOpen()); this.connManager.releaseConnection(conn, null, -1, null); this.connManager.shutdown(); }
@Test public void doesNotBackOffForConnectionManagerTimeout() { assertFalse(impl.shouldBackoff(new ConnectionPoolTimeoutException())); }
private boolean isRemoteUnavailable(final Exception e) { if (e instanceof ConnectionPoolTimeoutException) { return false; } return true; }