Package org.apache.http.impl.conn.tsccm

Examples of org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager


     * Tests releasing with time limits.
     */
    @Test
    public void testReleaseConnectionWithTimeLimits() throws Exception {

        ThreadSafeClientConnManager mgr = createTSCCM(null);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);
        final int      rsplen = 8;
        final String      uri = "/random/" + rsplen;

        HttpRequest request =
            new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);

        ManagedClientConnection conn = getConnection(mgr, route);
        conn.open(route, httpContext, defaultParams);

        // a new context is created for each testcase, no need to reset
        HttpResponse response = Helper.execute(
                request, conn, target,
                httpExecutor, httpProcessor, defaultParams, httpContext);

        Assert.assertEquals("wrong status in first response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        byte[] data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of first response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        // check that there is no auto-release by default
        try {
            // this should fail quickly, connection has not been released
            getConnection(mgr, route, 10L, TimeUnit.MILLISECONDS);
            Assert.fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException e) {
            // expected
        }

        // release connection without marking for re-use
        // expect the next connection obtained to be closed
        mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
        conn = getConnection(mgr, route);
        Assert.assertFalse("connection should have been closed", conn.isOpen());

        // repeat the communication, no need to prepare the request again
        conn.open(route, httpContext, defaultParams);
        httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        response = httpExecutor.execute(request, conn, httpContext);
        httpExecutor.postProcess(response, httpProcessor, httpContext);

        Assert.assertEquals("wrong status in second response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of second response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        // release connection after marking it for re-use
        // expect the next connection obtained to be open
        conn.markReusable();
        mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
        conn = getConnection(mgr, route);
        Assert.assertTrue("connection should have been open", conn.isOpen());

        // repeat the communication, no need to prepare the request again
        httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        response = httpExecutor.execute(request, conn, httpContext);
        httpExecutor.postProcess(response, httpProcessor, httpContext);

        Assert.assertEquals("wrong status in third response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of third response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        conn.markReusable();
        mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);
        Thread.sleep(150);
        conn = getConnection(mgr, route);
        Assert.assertTrue("connection should have been closed", !conn.isOpen());

        // repeat the communication, no need to prepare the request again
        conn.open(route, httpContext, defaultParams);
        httpContext.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        response = httpExecutor.execute(request, conn, httpContext);
        httpExecutor.postProcess(response, httpProcessor, httpContext);

        Assert.assertEquals("wrong status in third response",
                     HttpStatus.SC_OK,
                     response.getStatusLine().getStatusCode());
        data = EntityUtils.toByteArray(response.getEntity());
        Assert.assertEquals("wrong length of fourth response entity",
                     rsplen, data.length);
        // ignore data, but it must be read

        mgr.shutdown();
    }
View Full Code Here


    }

    @Test
    public void testCloseExpiredIdleConnections() throws Exception {

        ThreadSafeClientConnManager mgr = createTSCCM(null);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        ManagedClientConnection conn = getConnection(mgr, route);
        conn.open(route, httpContext, defaultParams);

        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
        mgr.releaseConnection(conn, 100, TimeUnit.MILLISECONDS);

        // Released, still active.
        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1,  mgr.getConnectionsInPool(route));

        mgr.closeExpiredConnections();

        // Time has not expired yet.
        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1,  mgr.getConnectionsInPool(route));

        Thread.sleep(150);

        mgr.closeExpiredConnections();

        // Time expired now, connections are destroyed.
        Assert.assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));

        mgr.shutdown();
    }
View Full Code Here

    }

    @Test
    public void testCloseExpiredTTLConnections() throws Exception {

        ThreadSafeClientConnManager mgr = createTSCCM(null, 100, TimeUnit.MILLISECONDS);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        ManagedClientConnection conn = getConnection(mgr, route);
        conn.open(route, httpContext, defaultParams);

        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1, mgr.getConnectionsInPool(route));
        // Release, let remain idle for forever
        mgr.releaseConnection(conn, -1, TimeUnit.MILLISECONDS);

        // Released, still active.
        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1,  mgr.getConnectionsInPool(route));

        mgr.closeExpiredConnections();

        // Time has not expired yet.
        Assert.assertEquals("connectionsInPool", 1, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 1,  mgr.getConnectionsInPool(route));

        Thread.sleep(150);

        mgr.closeExpiredConnections();

        // TTL expired now, connections are destroyed.
        Assert.assertEquals("connectionsInPool", 0, mgr.getConnectionsInPool());
        Assert.assertEquals("connectionsInPool(host)", 0, mgr.getConnectionsInPool(route));

        mgr.shutdown();
    }
View Full Code Here

     * main execution thread while there is no blocking I/O operation.
     */
    @Test
    public void testReleaseConnectionOnAbort() throws Exception {

        ThreadSafeClientConnManager mgr = createTSCCM(null);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);
        final int      rsplen = 8;
        final String      uri = "/random/" + rsplen;

        HttpRequest request =
            new BasicHttpRequest("GET", uri, HttpVersion.HTTP_1_1);

        ManagedClientConnection conn = getConnection(mgr, route);
        conn.open(route, httpContext, defaultParams);

        // a new context is created for each testcase, no need to reset
        HttpResponse response = Helper.execute(
                request, conn, target,
                httpExecutor, httpProcessor, defaultParams, httpContext);

        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(mgr, route, 100L, TimeUnit.MILLISECONDS);
            Assert.fail("ConnectionPoolTimeoutException should have been thrown");
        } catch (ConnectionPoolTimeoutException e) {
            // expected
        }

        // abort the connection
        Assert.assertTrue(conn instanceof AbstractClientConnAdapter);
        ((AbstractClientConnAdapter) conn).abortConnection();

        // the connection is expected to be released back to the manager
        conn = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
        Assert.assertFalse("connection should have been closed", conn.isOpen());

        mgr.releaseConnection(conn, -1, null);
        mgr.shutdown();
    }
View Full Code Here

                connectLatch, WaitPolicy.BEFORE_CONNECT, PlainSocketFactory.getSocketFactory());
        Scheme scheme = new Scheme("http", 80, stallingSocketFactory);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(scheme);

        ThreadSafeClientConnManager mgr = createTSCCM(registry);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        final ManagedClientConnection conn = getConnection(mgr, route);
        Assert.assertTrue(conn instanceof AbstractClientConnAdapter);

        final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
        Thread abortingThread = new Thread(new Runnable() {
            public void run() {
                try {
                    stallingSocketFactory.waitForState();
                    conn.abortConnection();
                    connectLatch.countDown();
                } catch (Throwable e) {
                    throwRef.set(e);
                }
            }
        });
        abortingThread.start();

        try {
            conn.open(route, httpContext, defaultParams);
            Assert.fail("expected SocketException");
        } catch(SocketException expected) {}

        abortingThread.join(5000);
        if(throwRef.get() != null)
            throw new RuntimeException(throwRef.get());

        Assert.assertFalse(conn.isOpen());
        Assert.assertEquals(0, localServer.getAcceptedConnectionCount());

        // the connection is expected to be released back to the manager
        ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
        Assert.assertFalse("connection should have been closed", conn2.isOpen());

        mgr.releaseConnection(conn2, -1, null);
        mgr.shutdown();
    }
View Full Code Here

                connectLatch, WaitPolicy.BEFORE_CREATE, PlainSocketFactory.getSocketFactory());
        Scheme scheme = new Scheme("http", 80, stallingSocketFactory);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(scheme);

        ThreadSafeClientConnManager mgr = createTSCCM(registry);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        final ManagedClientConnection conn = getConnection(mgr, route);
        Assert.assertTrue(conn instanceof AbstractClientConnAdapter);

        final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
        Thread abortingThread = new Thread(new Runnable() {
            public void run() {
                try {
                    stallingSocketFactory.waitForState();
                    conn.abortConnection();
                    connectLatch.countDown();
                } catch (Throwable e) {
                    throwRef.set(e);
                }
            }
        });
        abortingThread.start();

        try {
            conn.open(route, httpContext, defaultParams);
            Assert.fail("expected exception");
        } catch(IOException expected) {
            Assert.assertEquals("Connection already shutdown", expected.getMessage());
        }

        abortingThread.join(5000);
        if(throwRef.get() != null)
            throw new RuntimeException(throwRef.get());

        Assert.assertFalse(conn.isOpen());
        Assert.assertEquals(0, localServer.getAcceptedConnectionCount());

        // the connection is expected to be released back to the manager
        ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
        Assert.assertFalse("connection should have been closed", conn2.isOpen());

        mgr.releaseConnection(conn2, -1, null);
        mgr.shutdown();
    }
View Full Code Here

                connectLatch, WaitPolicy.AFTER_CONNECT, PlainSocketFactory.getSocketFactory());
        Scheme scheme = new Scheme("http", 80, stallingSocketFactory);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(scheme);

        ThreadSafeClientConnManager mgr = createTSCCM(registry);
        mgr.setMaxTotal(1);

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        final ManagedClientConnection conn = getConnection(mgr, route);
        Assert.assertTrue(conn instanceof AbstractClientConnAdapter);

        final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
        Thread abortingThread = new Thread(new Runnable() {
            public void run() {
                try {
                    stallingSocketFactory.waitForState();
                    conn.abortConnection();
                    connectLatch.countDown();
                } catch (Throwable e) {
                    throwRef.set(e);
                }
            }
        });
        abortingThread.start();

        try {
            conn.open(route, httpContext, defaultParams);
            Assert.fail("expected SocketException");
        } catch(SocketException expected) {}

        abortingThread.join(5000);
        if(throwRef.get() != null)
            throw new RuntimeException(throwRef.get());

        Assert.assertFalse(conn.isOpen());
        // Give the server a bit of time to accept the connection, but
        // ensure that it can accept it.
        for(int i = 0; i < 10; i++) {
            if(localServer.getAcceptedConnectionCount() == 1)
                break;
            Thread.sleep(100);
        }
        Assert.assertEquals(1, localServer.getAcceptedConnectionCount());

        // the connection is expected to be released back to the manager
        ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
        Assert.assertFalse("connection should have been closed", conn2.isOpen());

        mgr.releaseConnection(conn2, -1, null);
        mgr.shutdown();
    }
View Full Code Here

    @Test
    public void testAbortAfterOperatorOpen() throws Exception {
        final CountDownLatch connectLatch = new CountDownLatch(1);
        final AtomicReference<StallingOperator> operatorRef = new AtomicReference<StallingOperator>();

        ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(supportedSchemes) {
            @Override
            protected ClientConnectionOperator createConnectionOperator(
                    SchemeRegistry schreg) {
                operatorRef.set(new StallingOperator(connectLatch, WaitPolicy.AFTER_OPEN, super.createConnectionOperator(schreg)));
                return operatorRef.get();
            }
        };
        mgr.setMaxTotal(1);
        Assert.assertNotNull(operatorRef.get());

        final HttpHost target = getServerHttp();
        final HttpRoute route = new HttpRoute(target, null, false);

        final ManagedClientConnection conn = getConnection(mgr, route);
        Assert.assertTrue(conn instanceof AbstractClientConnAdapter);

        final AtomicReference<Throwable> throwRef = new AtomicReference<Throwable>();
        Thread abortingThread = new Thread(new Runnable() {
            public void run() {
                try {
                    operatorRef.get().waitForState();
                    conn.abortConnection();
                    connectLatch.countDown();
                } catch (Throwable e) {
                    throwRef.set(e);
                }
            }
        });
        abortingThread.start();

        try {
            conn.open(route, httpContext, defaultParams);
            Assert.fail("expected exception");
        } catch(IOException iox) {
            Assert.assertEquals("Request aborted", iox.getMessage());
        }

        abortingThread.join(5000);
        if(throwRef.get() != null)
            throw new RuntimeException(throwRef.get());

        Assert.assertFalse(conn.isOpen());
        // Give the server a bit of time to accept the connection, but
        // ensure that it can accept it.
        for(int i = 0; i < 10; i++) {
            if(localServer.getAcceptedConnectionCount() == 1)
                break;
            Thread.sleep(100);
        }
        Assert.assertEquals(1, localServer.getAcceptedConnectionCount());

        // the connection is expected to be released back to the manager
        ManagedClientConnection conn2 = getConnection(mgr, route, 5L, TimeUnit.SECONDS);
        Assert.assertFalse("connection should have been closed", conn2.isOpen());

        mgr.releaseConnection(conn2, -1, null);
        mgr.shutdown();
    }
View Full Code Here

    synchronized (connectionManagerSynchronizer)
    {
      if (client == null)
      {
        // Initialize the connection pool
        httpConnectionManager = new ThreadSafeClientConnManager();
        httpConnectionManager.setMaxTotal(poolSize);
        httpConnectionManager.setDefaultMaxPerRoute(poolSize);
        BasicHttpParams params = new BasicHttpParams();
        params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true);
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,false);
View Full Code Here

                new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
       
        // Create an HttpClient with the ThreadSafeClientConnManager.
        // This connection manager must be used if more than one thread will
        // be using the HttpClient.
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
        HttpClient httpClient = new DefaultHttpClient(cm, params);
       
        // create an array of URIs to perform GETs on
        String[] urisToGet = {
            "http://jakarta.apache.org/",
View Full Code Here

TOP

Related Classes of org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.