java类org.apache.http.util.Asserts的实例源码

AbstractConnPool.java 文件源码 项目:ZTLib 阅读 29 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
GroupsIOApiClient.java 文件源码 项目:groupsio-api-java 阅读 18 收藏 0 点赞 0 评论 0
/**
 * More in-depth constructor to override the defaults.
 * 
 * @param hostname
 *            - the base hostname (e.g. api.groups.io) to use
 * @param version
 *            - the API version (e.g. v1) to use
 * @param apiKey
 *            - TODO: Update with details once published.
 * @param email
 *            - the email of the user to log in as
 * @param domain
 *            - the domain name to connect with
 * @param twoFactor
 *            - the appropriate two-factor code to use
 */
public GroupsIOApiClient(
        final String hostname,
        final String version,
        final String apiKey,
        final String email,
        final String domain,
        final Integer twoFactor)
{
    Asserts.notBlank(apiKey, "apiKey");
    Asserts.notBlank(email, "email");
    this.hostname = hostname;
    this.version = version;
    this.apiKey = apiKey;
    this.email = email;
    this.domain = domain;
    this.twoFactor = twoFactor;
}
AbstractConnPool.java 文件源码 项目:remote-files-sync 阅读 25 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
BasicHttpClientConnectionManager.java 文件源码 项目:remote-files-sync 阅读 21 收藏 0 点赞 0 评论 0
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
BasicHttpClientConnectionManager.java 文件源码 项目:remote-files-sync 阅读 29 收藏 0 点赞 0 评论 0
public void connect(
        final HttpClientConnection conn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;;
    this.connectionOperator.connect(this.conn, host, localAddress,
            connectTimeout, this.socketConfig, context);
}
PoolingHttpClientConnectionManager.java 文件源码 项目:remote-files-sync 阅读 28 收藏 0 点赞 0 评论 0
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");
    }
}
SyncMain.java 文件源码 项目:remote-files-sync 阅读 17 收藏 0 点赞 0 评论 0
public static void main(String argvs[]) throws TTransportException, IOException {
    Asserts.check(argvs != null && argvs.length == 2, "require params type and config path");
    String type = argvs[0];
    String config = argvs[1];

    try {
        if ("server".equals(type)) {
            ServerForSync.main(new String[] { config });
        } else if ("client".equals(type)) {
            ClientForSync.main(new String[] { config });
        } else if ("client_sync".equals(type)) {
            ClientForSync.sync(config);
        } else if ("client_validate".equals(type)) {
            ClientForSync.validate(config);
        } else {
            throw new RuntimeException("unknow type " + type);
        }
    } finally {
        ThriftClientPool.closeAll();
    }
}
ClientFolder.java 文件源码 项目:remote-files-sync 阅读 17 收藏 0 点赞 0 评论 0
public void sync(StopAble stop) throws IOException {

        String store_path = new File(new File(store_folder), store_name).getCanonicalPath();
        if (null == fromManage) {
            fromManage = RemoteFileFactory.queryManage(url);
        }
        logger.stdout(String.format("sync[%s] %s => %s", name, url, store_path));
        File root = new File(store_path);
        if (!root.exists()) {
            root.mkdir();
        }
        Asserts.check(root.isDirectory(), "must be a directory :" + store_path);
        long time = System.currentTimeMillis();
        try {
            if (stop.isStop()) {
                return;
            }
            doSync(stop, null, root);
        } finally {
            long end = System.currentTimeMillis();
            logger.stdout(String.format("sync finish[%s](cost: %s) %s => %s", name, (end - time) / 1000 + "s", url,
                    store_path));
        }
    }
DefaultClientConnectionOperator.java 文件源码 项目:purecloud-iot 阅读 31 收藏 0 点赞 0 评论 0
@Override
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);
}
BasicClientConnectionManager.java 文件源码 项目:purecloud-iot 阅读 28 收藏 0 点赞 0 评论 0
ManagedClientConnection getConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "Route");
    synchronized (this) {
        assertNotShutdown();
        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 opconn = this.connOperator.createConnection();
            this.poolEntry = new HttpPoolEntry(this.log, id, route, opconn, 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;
    }
}
AbstractPoolEntry.java 文件源码 项目:purecloud-iot 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Layers a protocol on top of an established tunnel.
 *
 * @param context   the context for layering
 * @param params    the parameters for layering
 *
 * @throws IOException  in case of a problem
 */
public void layerProtocol(final HttpContext context, final HttpParams params)
    throws IOException {

    //@@@ is context allowed to be null? depends on operator?
    Args.notNull(params, "HTTP parameters");
    Asserts.notNull(this.tracker, "Route tracker");
    Asserts.check(this.tracker.isConnected(), "Connection not open");
    Asserts.check(this.tracker.isTunnelled(), "Protocol layering without a tunnel not supported");
    Asserts.check(!this.tracker.isLayered(), "Multiple protocol layering not supported");
    // - collect the arguments
    // - call the operator
    // - update the tracking data
    // In this order, we can be sure that only a successful
    // layering on top of the connection will be tracked.

    final HttpHost target = tracker.getTargetHost();

    connOperator.updateSecureConnection(this.connection, target,
                                         context, params);

    this.tracker.layerProtocol(this.connection.isSecure());

}
BasicHttpClientConnectionManager.java 文件源码 项目:purecloud-iot 阅读 20 收藏 0 点赞 0 评论 0
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
BasicHttpClientConnectionManager.java 文件源码 项目:purecloud-iot 阅读 22 收藏 0 点赞 0 评论 0
@Override
public void connect(
        final HttpClientConnection conn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalSocketAddress();
    this.connectionOperator.connect(this.conn, host, localAddress,
            connectTimeout, this.socketConfig, context);
}
PoolingHttpClientConnectionManager.java 文件源码 项目:purecloud-iot 阅读 28 收藏 0 点赞 0 评论 0
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");
    }
}
AbstractConnPool.java 文件源码 项目:Visit 阅读 27 收藏 0 点赞 0 评论 0
/**
 * {@inheritDoc}
 * <p/>
 * Please note that this class does not maintain its own pool of execution
 * {@link Thread}s. Therefore, one <b>must</b> call {@link Future#get()}
 * or {@link Future#get(long, TimeUnit)} method on the {@link Future}
 * returned by this method in order for the lease operation to complete.
 */
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
    Args.notNull(route, "Route");
    Asserts.check(!this.isShutDown, "Connection pool shut down");
    return new PoolEntryFuture<E>(this.lock, callback) {

        @Override
        public E getPoolEntry(
                final long timeout,
                final TimeUnit tunit)
                    throws InterruptedException, TimeoutException, IOException {
            final E entry = getPoolEntryBlocking(route, state, timeout, tunit, this);
            onLease(entry);
            return entry;
        }

    };
}
BasicHttpClientConnectionManager.java 文件源码 项目:Visit 阅读 22 收藏 0 点赞 0 评论 0
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
BasicHttpClientConnectionManager.java 文件源码 项目:Visit 阅读 25 收藏 0 点赞 0 评论 0
public void connect(
        final HttpClientConnection conn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;;
    this.connectionOperator.connect(this.conn, host, localAddress,
            connectTimeout, this.socketConfig, context);
}
PoolingHttpClientConnectionManager.java 文件源码 项目:Visit 阅读 38 收藏 0 点赞 0 评论 0
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");
    }
}
TargetHostsBuilderTest.java 文件源码 项目:parallec 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void setTargetHostsFromJsonPathTest() {
    String jsonPath = "$.sample.small-target-hosts[*].hostName";
    List<String> targetHosts = thb.setTargetHostsFromJsonPath(jsonPath,
            URL_JSON_PATH, SOURCE_URL);
    logger.info("Get list " + targetHosts.size() + " from json path  "
            + jsonPath + " from file " + URL_JSON_PATH);

    Asserts.check(targetHosts.size() > 0,
            "fail setTargetHostsFromJsonPathTest");
    // try bad
    try {
        thb.setTargetHostsFromJsonPath(jsonPath,
                FILEPATH_JSON_PATH + "bad", SOURCE_LOCAL);
    } catch (TargetHostsLoadException e) {
        logger.info("expected error. Get bad list " + " from json path  "
                + jsonPath + " from file " + URL_JSON_PATH);
    }

}
NotifyRecorder.java 文件源码 项目:jenkins-notify-plugin 阅读 18 收藏 0 点赞 0 评论 0
private String buildNotifyJson( @Nonnull final AbstractBuild build,
                                @Nonnull final Map<String,?> env )
{
    Map<String,?> binding = new HashMap<String, Object>(){{
       put( "jenkins", notNull( Jenkins.getInstance(), "Jenkins instance" ));
       put( "build",   notNull( build, "Build instance" ));
       put( "env",     notNull( env, "Build environment" ));
    }};

    String json     = null;
    String template = "<%\n\n" + JSON_FUNCTION + "\n\n%>\n\n" +
                      notBlank( notifyTemplate, "Notify template" );

    try
    {
        json = notBlank( new SimpleTemplateEngine( getClass().getClassLoader()).
                         createTemplate( template ).
                         make( binding ).toString(), "Payload JSON" ).trim();

        Asserts.check(( json.startsWith( "{" ) && json.endsWith( "}" )) ||
                      ( json.startsWith( "[" ) && json.endsWith( "]" )),
                      "Illegal JSON content: should start and end with {} or []" );

        Asserts.notNull( new JsonSlurper().parseText( json ), "Parsed JSON" );
    }
    catch ( Exception e )
    {
        throwError(( json == null ?
            String.format( "Failed to parse Groovy template:%s%s%s",
                           LINE, template, LINE ) :
            String.format( "Failed to validate JSON payload (check with http://jsonlint.com/):%s%s%s",
                           LINE, json, LINE )), e );
    }

    return json;
}
NotifyRecorder.java 文件源码 项目:jenkins-notify-plugin 阅读 20 收藏 0 点赞 0 评论 0
private void sendNotifyRequest( @Nonnull String url, @Nonnull String json )
    throws IOException
{
    try
    {
        HttpPost request = new HttpPost( notBlank( url, "Notify URL" ));
        request.setEntity( new StringEntity( notBlank( json, "Notify JSON" ),
                                             ContentType.create( "application/json", Consts.UTF_8 )));
        HttpResponse response   = HTTP_CLIENT.execute( request );
        int          statusCode = response.getStatusLine().getStatusCode();

        Asserts.check( statusCode == 200, String.format( "status code is %s, expected 200", statusCode ));
        EntityUtils.consumeQuietly( notNull( response.getEntity(), "Response entity" ));
        request.releaseConnection();
    }
    catch ( Exception e )
    {
        throwError( String.format( "Failed to publish notify request to '%s', payload JSON was:%s%s%s",
                                   notifyUrl, LINE, json, LINE ), e );
    }
}
BasicHttpClientConnectionManager.java 文件源码 项目:ZTLib 阅读 22 收藏 0 点赞 0 评论 0
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
    Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Get connection for route " + route);
    }
    Asserts.check(!this.leased, "Connection is still allocated");
    if (!LangUtils.equals(this.route, route) || !LangUtils.equals(this.state, state)) {
        closeConnection();
    }
    this.route = route;
    this.state = state;
    checkExpiry();
    if (this.conn == null) {
        this.conn = this.connFactory.create(route, this.connConfig);
    }
    this.leased = true;
    return this.conn;
}
BasicHttpClientConnectionManager.java 文件源码 项目:ZTLib 阅读 22 收藏 0 点赞 0 评论 0
public void connect(
        final HttpClientConnection conn,
        final HttpRoute route,
        final int connectTimeout,
        final HttpContext context) throws IOException {
    Args.notNull(conn, "Connection");
    Args.notNull(route, "HTTP route");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    final HttpHost host;
    if (route.getProxyHost() != null) {
        host = route.getProxyHost();
    } else {
        host = route.getTargetHost();
    }
    final InetSocketAddress localAddress = route.getLocalAddress() != null ? new InetSocketAddress(route.getLocalAddress(), 0) : null;;
    this.connectionOperator.connect(this.conn, host, localAddress,
            connectTimeout, this.socketConfig, context);
}
PoolingHttpClientConnectionManager.java 文件源码 项目:ZTLib 阅读 28 收藏 0 点赞 0 评论 0
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");
    }
}
SolrSearchServer.java 文件源码 项目:vind 阅读 17 收藏 0 点赞 0 评论 0
@Override
public void index(Document ... docs) {
    Asserts.notNull(docs,"Document to index should not be null.");
    Asserts.check(docs.length > 0, "Should be at least one document to index.");
    for(Document doc: docs) {
        indexSingleDocument(doc);
    }
}
SolrSearchServer.java 文件源码 项目:vind 阅读 19 收藏 0 点赞 0 评论 0
@Override
public void index(List<Document> docs) {
    Asserts.notNull(docs,"Document to index should not be null.");
    Asserts.check(docs.size() > 0, "Should be at least one document to index.");

    indexMultipleDocuments(docs);
}
RouteSpecificPool.java 文件源码 项目:remote-files-sync 阅读 22 收藏 0 点赞 0 评论 0
public void free(final E entry, final boolean reusable) {
    Args.notNull(entry, "Pool entry");
    final boolean found = this.leased.remove(entry);
    Asserts.check(found, "Entry %s has not been leased from this pool", entry);
    if (reusable) {
        this.available.addFirst(entry);
    }
}
DefaultRedirectStrategy.java 文件源码 项目:remote-files-sync 阅读 30 收藏 0 点赞 0 评论 0
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");
    }
    final String location = locationHeader.getValue();
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "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 = URIUtilsHC4.rewriteURI(requestURI, target, false);
            uri = URIUtilsHC4.resolve(absoluteRequestURI, uri);
        }
    } catch (final URISyntaxException ex) {
        throw new ProtocolException(ex.getMessage(), ex);
    }

    RedirectLocationsHC4 redirectLocations = (RedirectLocationsHC4) clientContext.getAttribute(
            HttpClientContext.REDIRECT_LOCATIONS);
    if (redirectLocations == null) {
        redirectLocations = new RedirectLocationsHC4();
        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;
}
BHttpConnectionBase.java 文件源码 项目:remote-files-sync 阅读 22 收藏 0 点赞 0 评论 0
protected void ensureOpen() throws IOException {
    Asserts.check(this.open, "Connection is not open");
    if (!this.inbuffer.isBound()) {
        this.inbuffer.bind(getSocketInputStream(this.socket));
    }
    if (!this.outbuffer.isBound()) {
        this.outbuffer.bind(getSocketOutputStream(this.socket));
    }
}
BasicHttpClientConnectionManager.java 文件源码 项目:remote-files-sync 阅读 24 收藏 0 点赞 0 评论 0
public synchronized void releaseConnection(
        final HttpClientConnection conn,
        final Object state,
        final long keepalive, final TimeUnit tunit) {
    Args.notNull(conn, "Connection");
    Asserts.check(conn == this.conn, "Connection not obtained from this manager");
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Releasing connection " + conn);
    }
    if (this.isShutdown.get()) {
        return;
    }
    try {
        this.updated = System.currentTimeMillis();
        if (!this.conn.isOpen()) {
            this.conn = null;
            this.route = null;
            this.conn = null;
            this.expiry = Long.MAX_VALUE;
        } else {
            this.state = state;
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                final String s;
                if (keepalive > 0) {
                    s = "for " + keepalive + " " + tunit;
                } else {
                    s = "indefinitely";
                }
                Log.d(TAG, "Connection can be kept alive " + s);
            }
            if (keepalive > 0) {
                this.expiry = this.updated + tunit.toMillis(keepalive);
            } else {
                this.expiry = Long.MAX_VALUE;
            }
        }
    } finally {
        this.leased = false;
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号