Example usage for org.apache.http.util Asserts check

List of usage examples for org.apache.http.util Asserts check

Introduction

In this page you can find the example usage for org.apache.http.util Asserts check.

Prototype

public static void check(boolean z, String str) 

Source Link

Usage

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

public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(target, "Target host");
    Args.notNull(params, "HTTP parameters");
    Asserts.check(!conn.isOpen(), "Connection must not be open");

    final SchemeRegistry registry = getSchemeRegistry(context);
    final Scheme schm = registry.getScheme(target.getSchemeName());
    final SchemeSocketFactory sf = schm.getSchemeSocketFactory();

    final InetAddress[] addresses = resolveHostname(target.getHostName());
    final int port = schm.resolvePort(target.getPort());
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(params);
        conn.opening(sock, target);// ww  w.  ja  v a  2 s  .c  o  m

        final InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port);
        InetSocketAddress localAddress = null;
        if (local != null) {
            localAddress = new InetSocketAddress(local, 0);
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            final Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            prepareSocket(sock, context, params);
            conn.openCompleted(sf.isSecure(sock), params);
            return;
        } catch (final ConnectException ex) {
            if (last) {
                throw ex;
            }
        } catch (final ConnectTimeoutException ex) {
            if (last) {
                throw ex;
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

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

public void updateSecureConnection(final OperatedClientConnection conn, final HttpHost target,
        final HttpContext context, final HttpParams params) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(target, "Target host");
    Args.notNull(params, "Parameters");
    Asserts.check(conn.isOpen(), "Connection must be open");

    final SchemeRegistry registry = getSchemeRegistry(context);
    final Scheme schm = registry.getScheme(target.getSchemeName());
    Asserts.check(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory,
            "Socket factory must implement SchemeLayeredSocketFactory");
    final SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
    final Socket sock = lsf.createLayeredSocket(conn.getSocket(), target.getHostName(),
            schm.resolvePort(target.getPort()), params);
    prepareSocket(sock, context, params);
    conn.update(sock, target, lsf.isSecure(sock), params);
}

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

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    final HttpPoolEntry entry;
    try {/*from   ww w.  j a va2 s  .c  o m*/
        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 new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

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

@Override
public void releaseConnection(final ManagedClientConnection conn, final long keepalive, final TimeUnit tunit) {

    Args.check(conn instanceof ManagedClientConnectionImpl,
            "Connection class mismatch, " + "connection not obtained from this manager");
    final ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
    Asserts.check(managedConn.getManager() == this, "Connection not obtained from this manager");
    synchronized (managedConn) {
        final HttpPoolEntry entry = managedConn.detach();
        if (entry == null) {
            return;
        }//from   w w w  . j av a 2  s. c om
        try {
            if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
                try {
                    managedConn.shutdown();
                } catch (final IOException iox) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("I/O exception shutting down released connection", iox);
                    }
                }
            }
            // Only reusable connections can be kept alive
            if (managedConn.isMarkedReusable()) {
                entry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (keepalive > 0) {
                        s = "for " + keepalive + " " + tunit;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
                }
            }
        } finally {
            this.pool.release(entry, managedConn.isMarkedReusable());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
        }
    }
}

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

public void releaseConnection(final ManagedClientConnection conn, final long keepalive, final TimeUnit tunit) {

    Args.check(conn instanceof ManagedClientConnectionImpl,
            "Connection class mismatch, " + "connection not obtained from this manager");
    final ManagedClientConnectionImpl managedConn = (ManagedClientConnectionImpl) conn;
    Asserts.check(managedConn.getManager() == this, "Connection not obtained from this manager");
    synchronized (managedConn) {
        final HttpPoolEntry entry = managedConn.detach();
        if (entry == null) {
            return;
        }//from ww w  . jav  a  2 s.com
        try {
            if (managedConn.isOpen() && !managedConn.isMarkedReusable()) {
                try {
                    managedConn.shutdown();
                } catch (final IOException iox) {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("I/O exception shutting down released connection", iox);
                    }
                }
            }
            // Only reusable connections can be kept alive
            if (managedConn.isMarkedReusable()) {
                entry.updateExpiry(keepalive, tunit != null ? tunit : TimeUnit.MILLISECONDS);
                if (this.log.isDebugEnabled()) {
                    final String s;
                    if (keepalive > 0) {
                        s = "for " + keepalive + " " + tunit;
                    } else {
                        s = "indefinitely";
                    }
                    this.log.debug("Connection " + format(entry) + " can be kept alive " + s);
                }
            }
        } finally {
            this.pool.release(entry, managedConn.isMarkedReusable());
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection released: " + format(entry) + formatStats(entry.getRoute()));
        }
    }
}

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

protected HttpClientConnection leaseConnection(final Future<CPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {//from   w w w .  ja  v a2  s.  c  o m
        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");
    }
}

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

/**
 * Asserts that this manager is not shut down.
 *
 * @throws IllegalStateException    if this manager is shut down
 *///from   w  w  w .j  a  v  a  2s .  c o m
protected final void assertStillUp() throws IllegalStateException {
    Asserts.check(!this.isShutDown, "Manager is shut down");
}

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

/**
 * Obtains a connection./*from  ww  w  .  j  av  a  2s .  co m*/
 *
 * @param route     where the connection should point to
 *
 * @return  a connection that can be used to communicate
 *          along the given route
 */
public ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "Route");
    assertStillUp();

    if (log.isDebugEnabled()) {
        log.debug("Get connection for route " + route);
    }

    synchronized (this) {

        Asserts.check(managedConn == null, MISUSE_MESSAGE);

        // check re-usability of the connection
        boolean recreate = false;
        boolean shutdown = false;

        // Kill the connection if it expired.
        closeExpiredConnections();

        if (uniquePoolEntry.connection.isOpen()) {
            final RouteTracker tracker = uniquePoolEntry.tracker;
            shutdown = (tracker == null || // can happen if method is aborted
                    !tracker.toRoute().equals(route));
        } else {
            // If the connection is not open, create a new PoolEntry,
            // as the connection may have been marked not reusable,
            // due to aborts -- and the PoolEntry should not be reused
            // either.  There's no harm in recreating an entry if
            // the connection is closed.
            recreate = true;
        }

        if (shutdown) {
            recreate = true;
            try {
                uniquePoolEntry.shutdown();
            } catch (final IOException iox) {
                log.debug("Problem shutting down connection.", iox);
            }
        }

        if (recreate) {
            uniquePoolEntry = new PoolEntry();
        }

        managedConn = new ConnAdapter(uniquePoolEntry, route);

        return managedConn;
    }
}

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

public void releaseConnection(final ManagedClientConnection conn, final long validDuration,
        final TimeUnit timeUnit) {
    Args.check(conn instanceof ConnAdapter,
            "Connection class mismatch, " + "connection not obtained from this manager");
    assertStillUp();/* w  w w  . ja v  a2s  .  c  o  m*/

    if (log.isDebugEnabled()) {
        log.debug("Releasing connection " + conn);
    }

    final ConnAdapter sca = (ConnAdapter) conn;
    synchronized (sca) {
        if (sca.poolEntry == null) {
            return; // already released
        }
        final ClientConnectionManager manager = sca.getManager();
        Asserts.check(manager == this, "Connection not obtained from this manager");
        try {
            // make sure that the response has been read completely
            if (sca.isOpen() && (this.alwaysShutDown || !sca.isMarkedReusable())) {
                if (log.isDebugEnabled()) {
                    log.debug("Released connection open but not reusable.");
                }

                // make sure this connection will not be re-used
                // we might have gotten here because of a shutdown trigger
                // shutdown of the adapter also clears the tracked route
                sca.shutdown();
            }
        } catch (final IOException iox) {
            if (log.isDebugEnabled()) {
                log.debug("Exception shutting down released connection.", iox);
            }
        } finally {
            sca.detach();
            synchronized (this) {
                managedConn = null;
                lastReleaseTime = System.currentTimeMillis();
                if (validDuration > 0) {
                    connectionExpiresTime = timeUnit.toMillis(validDuration) + lastReleaseTime;
                } else {
                    connectionExpiresTime = Long.MAX_VALUE;
                }
            }
        }
    }
}

From source file:org.apache.http.impl.conn.tsccm.ConnPoolByRoute.java

/**
 * Obtains a pool entry with a connection within the given timeout.
 * If a {@link WaitingThread} is used to block, {@link WaitingThreadAborter#setWaitingThread(WaitingThread)}
 * must be called before blocking, to allow the thread to be interrupted.
 *
 * @param route     the route for which to get the connection
 * @param timeout   the timeout, 0 or negative for no timeout
 * @param tunit     the unit for the <code>timeout</code>,
 *                  may be <code>null</code> only if there is no timeout
 * @param aborter   an object which can abort a {@link WaitingThread}.
 *
 * @return  pool entry holding a connection for the route
 *
 * @throws ConnectionPoolTimeoutException
 *         if the timeout expired//from   w  w w . j ava  2  s . c  o m
 * @throws InterruptedException
 *         if the calling thread was interrupted
 */
protected BasicPoolEntry getEntryBlocking(final HttpRoute route, final Object state, final long timeout,
        final TimeUnit tunit, final WaitingThreadAborter aborter)
        throws ConnectionPoolTimeoutException, InterruptedException {

    Date deadline = null;
    if (timeout > 0) {
        deadline = new Date(System.currentTimeMillis() + tunit.toMillis(timeout));
    }

    BasicPoolEntry entry = null;
    poolLock.lock();
    try {

        RouteSpecificPool rospl = getRoutePool(route, true);
        WaitingThread waitingThread = null;

        while (entry == null) {
            Asserts.check(!shutdown, "Connection pool shut down");

            if (log.isDebugEnabled()) {
                log.debug("[" + route + "] total kept alive: " + freeConnections.size() + ", total issued: "
                        + leasedConnections.size() + ", total allocated: " + numConnections + " out of "
                        + maxTotalConnections);
            }

            // the cases to check for:
            // - have a free connection for that route
            // - allowed to create a free connection for that route
            // - can delete and replace a free connection for another route
            // - need to wait for one of the things above to come true

            entry = getFreeEntry(rospl, state);
            if (entry != null) {
                break;
            }

            final boolean hasCapacity = rospl.getCapacity() > 0;

            if (log.isDebugEnabled()) {
                log.debug("Available capacity: " + rospl.getCapacity() + " out of " + rospl.getMaxEntries()
                        + " [" + route + "][" + state + "]");
            }

            if (hasCapacity && numConnections < maxTotalConnections) {

                entry = createEntry(rospl, operator);

            } else if (hasCapacity && !freeConnections.isEmpty()) {

                deleteLeastUsedEntry();
                // if least used entry's route was the same as rospl,
                // rospl is now out of date : we preemptively refresh
                rospl = getRoutePool(route, true);
                entry = createEntry(rospl, operator);

            } else {

                if (log.isDebugEnabled()) {
                    log.debug("Need to wait for connection" + " [" + route + "][" + state + "]");
                }

                if (waitingThread == null) {
                    waitingThread = newWaitingThread(poolLock.newCondition(), rospl);
                    aborter.setWaitingThread(waitingThread);
                }

                boolean success = false;
                try {
                    rospl.queueThread(waitingThread);
                    waitingThreads.add(waitingThread);
                    success = waitingThread.await(deadline);

                } finally {
                    // In case of 'success', we were woken up by the
                    // connection pool and should now have a connection
                    // waiting for us, or else we're shutting down.
                    // Just continue in the loop, both cases are checked.
                    rospl.removeThread(waitingThread);
                    waitingThreads.remove(waitingThread);
                }

                // check for spurious wakeup vs. timeout
                if (!success && (deadline != null) && (deadline.getTime() <= System.currentTimeMillis())) {
                    throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
                }
            }
        } // while no entry

    } finally {
        poolLock.unlock();
    }
    return entry;
}