Example usage for org.apache.http.params HttpConnectionParams getSoTimeout

List of usage examples for org.apache.http.params HttpConnectionParams getSoTimeout

Introduction

In this page you can find the example usage for org.apache.http.params HttpConnectionParams getSoTimeout.

Prototype

public static int getSoTimeout(HttpParams httpParams) 

Source Link

Usage

From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java

/**
 * Forming a POST request/*  w  ww .  j a  v  a  2  s .  c o m*/
 * 
 * @param url
 * @param create
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 * @throws TogathorException
 * @throws IllegalStateException 
 * @throws JSONException 
 * @throws TogathorForbiddenException
 */
private static InputStream httpPostRequest(String url, Object create, String userId) throws IOException,
        IllegalStateException, TogathorException, JSONException, TogathorForbiddenException {

    HttpPost httppost = new HttpPost(url);

    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpConnectionParams.setConnectionTimeout(httppost.getParams(), 5000);
    HttpConnectionParams.setSoTimeout(httppost.getParams(), 5000);

    Logger.debug("TIMEOUTS", HttpConnectionParams.getConnectionTimeout(httppost.getParams()) + " "
            + HttpConnectionParams.getSoTimeout(httppost.getParams()));

    httppost.setHeader("Content-Type", "application/json");
    httppost.setHeader("Encoding", "utf-8");
    httppost.setHeader("database", Const.DATABASE);

    if (userId != null && userId.length() > 0)
        httppost.setHeader("user_id", userId);
    else {
        String userIdSaved = Togathor.getPreferences().getUserId();
        if (userIdSaved != null)
            httppost.setHeader("user_id", userIdSaved);
    }

    String token = Togathor.getPreferences().getUserToken();
    if (token != null && token.length() > 0)
        httppost.setHeader("token", token);

    StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8);

    httppost.setEntity(stringEntity);

    print(httppost);

    HttpResponse response = HttpSingleton.getInstance().execute(httppost);
    HttpEntity entity = response.getEntity();

    Logger.debug("STATUS", "" + response.getStatusLine().getStatusCode());
    if (response.getStatusLine().getStatusCode() > 400) {
        HttpSingleton.sInstance = null;
        if (response.getStatusLine().getStatusCode() == 500)
            throw new TogathorException(getError(entity.getContent()));
        if (response.getStatusLine().getStatusCode() == 403)
            throw new TogathorForbiddenException();
        throw new IOException(response.getStatusLine().getReasonPhrase());
    }

    return entity.getContent();
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java

@Override
public HttpResponse execute(HttpHost originalTarget, final HttpRequest request, HttpContext context)
        throws HttpException, IOException {
    HttpHost target = originalTarget;//w  ww.  ja  v a  2 s.  c om
    final HttpRoute route = determineRoute(target, request, context);

    virtualHost = (HttpHost) request.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    long timeout = ConnManagerParams.getTimeout(params);

    try {
        HttpResponse response = null;

        // See if we have a user token bound to the execution context
        Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

        // Allocate connection if needed
        if (managedConn == null) {
            ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
            if (request instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) request).setConnectionRequest(connRequest);
            }

            try {
                managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException interrupted) {
                InterruptedIOException iox = new InterruptedIOException();
                iox.initCause(interrupted);
                throw iox;
            }

            if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                // validate connection
                if (managedConn.isOpen()) {
                    LOGGER.debug("Stale connection check");
                    if (managedConn.isStale()) {
                        LOGGER.debug("Stale connection detected");
                        managedConn.close();
                    }
                }
            }
        }

        if (request instanceof AbortableHttpRequest) {
            ((AbortableHttpRequest) request).setReleaseTrigger(managedConn);
        }

        // Reopen connection if needed
        if (!managedConn.isOpen()) {
            managedConn.open(route, context, params);
        } else {
            managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
        }

        try {
            establishRoute(route, context);
        } catch (TunnelRefusedException ex) {
            LOGGER.debug(ex.getMessage());
            response = ex.getResponse();
        }

        // Use virtual host if set
        target = virtualHost;

        if (target == null) {
            target = route.getTargetHost();
        }

        HttpHost proxy = route.getProxyHost();

        // Populate the execution context
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
        context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
        context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
        context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

        // Run request protocol interceptors
        requestExec.preProcess(request, httpProcessor, context);

        try {
            response = requestExec.execute(request, managedConn, context);
        } catch (IOException ex) {
            LOGGER.debug("Closing connection after request failure.");
            managedConn.close();
            throw ex;
        }

        if (response == null) {
            return null;
        }

        // Run response protocol interceptors
        response.setParams(params);
        requestExec.postProcess(response, httpProcessor, context);

        // The connection is in or can be brought to a re-usable state.
        boolean reuse = reuseStrategy.keepAlive(response, context);
        if (reuse) {
            // Set the idle duration of this connection
            long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
            managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

            if (duration >= 0) {
                LOGGER.trace("Connection can be kept alive for " + duration + " ms");
            } else {
                LOGGER.trace("Connection can be kept alive indefinitely");
            }
        }

        if ((managedConn != null) && (userToken == null)) {
            userToken = userTokenHandler.getUserToken(context);
            context.setAttribute(ClientContext.USER_TOKEN, userToken);
            if (userToken != null) {
                managedConn.setState(userToken);
            }
        }

        // check for entity, release connection if possible
        if ((response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse) {
                managedConn.markReusable();
            }
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:info.guardianproject.net.http.ModSSLSocketFactory.java

public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {

    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }/*w  w  w  .  j  ava  2s.  c o m*/
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    //Socket underlying = (Socket)
    //    ((sock != null) ? sock : createSocket());
    //Socket underlying = sock;
    //if (underlying == null) underlying = new Socket(); 

    //  Socket underlying = SocksSocketFactory.getSocketFactory("localhost", 9050).connectSocket(sock, host, port, localAddress, localPort, params);

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    Socket underlying = null;

    if (proxy != null) {
        //underlying = new Socket(proxy);
        //   InetSocketAddress sAddress = InetSocketAddress.createUnresolved(host,port);
        //    InetSocketAddress sAddress = new InetSocketAddress(host,port);
        //underlying.connect(sAddress,Socks soTimeout);

        SocksSocketFactory ssf = SocksSocketFactory.getSocketFactory(proxyAddr.getHostName(),
                proxyAddr.getPort());
        underlying = ssf.createSocket(null, null, -1, params);
        //   underlying.connect(sAddress);
    }

    SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(underlying, host, port, true);

    if ((localAddress != null) || (localPort > 0)) {

        // we need to bind explicitly
        if (localPort < 0)
            localPort = 0; // indicates "any"

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }

    InetSocketAddress remoteAddress;
    if (this.nameResolver != null) {
        remoteAddress = new InetSocketAddress(this.nameResolver.resolve(host), port);
    } else {
        remoteAddress = new InetSocketAddress(host, port);
    }

    sslsock.connect(remoteAddress, connTimeout);
    sslsock.setSoTimeout(soTimeout);

    try {

        hostnameVerifier.verify(host, sslsock);
        // verifyHostName() didn't blowup - good!
    } catch (IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (Exception x) {
            /*ignore*/ }
        throw iox;
    }

    return sslsock;
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

/**
 * @since 4.1/*w ww.  j a va  2 s.  c o  m*/
 */
public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    SSLSocket sslsock = (SSLSocket) (sock != null ? sock : createSocket());
    if (localAddress != null) {
        //            sslsock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sslsock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sslsock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(
                "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    sslsock.setSoTimeout(soTimeout);
    if (this.hostnameVerifier != null) {
        try {
            this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try {
                sslsock.close();
            } catch (Exception x) {
                /*ignore*/ }
            throw iox;
        }
    }
    return sslsock;
}

From source file:github.popeen.dsub.service.ssl.SSLSocketFactory.java

/**
 * @since 4.1/* ww w  .  j av  a 2s  .com*/
 */
public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    SSLSocket sslsock = (SSLSocket) (sock != null ? sock : createSocket());
    if (localAddress != null) {
        //            sslsock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sslsock.bind(localAddress);
    }

    setHostName(sslsock, remoteAddress.getHostName());
    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sslsock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException(
                "Connect to " + remoteAddress.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    sslsock.setSoTimeout(soTimeout);
    if (this.hostnameVerifier != null) {
        try {
            this.hostnameVerifier.verify(remoteAddress.getHostName(), sslsock);
            // verifyHostName() didn't blowup - good!
        } catch (IOException iox) {
            // close the socket before re-throwing the exception
            try {
                sslsock.close();
            } catch (Exception x) {
                /*ignore*/ }
            throw iox;
        }
    }
    return sslsock;
}

From source file:com.example.heya.couchdb.ConnectionHandler.java

/**
 * Forming a POST request//from  w w w.  j a  v  a2s. c  o m
 * 
 * @param url
 * @param create
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 * @throws SpikaException 
 * @throws IllegalStateException 
 * @throws JSONException 
 * @throws SpikaForbiddenException 
 */
private static InputStream httpPostRequest(String url, Object create, String userId)
        throws ClientProtocolException, IOException, IllegalStateException, SpikaException, JSONException,
        SpikaForbiddenException {

    HttpPost httppost = new HttpPost(url);

    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpConnectionParams.setConnectionTimeout(httppost.getParams(), 5000);
    HttpConnectionParams.setSoTimeout(httppost.getParams(), 5000);

    Logger.debug("TIMEOUTS", HttpConnectionParams.getConnectionTimeout(httppost.getParams()) + " "
            + HttpConnectionParams.getSoTimeout(httppost.getParams()));

    httppost.setHeader("Content-Type", "application/json");
    httppost.setHeader("Encoding", "utf-8");
    httppost.setHeader("database", Const.DATABASE);

    if (userId != null && userId.length() > 0)
        httppost.setHeader("user_id", userId);
    else {
        String userIdSaved = SpikaApp.getPreferences().getUserId();
        if (userIdSaved != null)
            httppost.setHeader("user_id", userIdSaved);
    }

    String token = SpikaApp.getPreferences().getUserToken();
    if (token != null && token.length() > 0)
        httppost.setHeader("token", token);

    StringEntity stringEntity = new StringEntity(create.toString(), HTTP.UTF_8);

    httppost.setEntity(stringEntity);

    print(httppost);

    HttpResponse response = HttpSingleton.getInstance().execute(httppost);
    HttpEntity entity = response.getEntity();

    Logger.debug("STATUS", "" + response.getStatusLine().getStatusCode());
    if (response.getStatusLine().getStatusCode() > 400) {
        HttpSingleton.sInstance = null;
        if (response.getStatusLine().getStatusCode() == 500)
            throw new SpikaException(getError(entity.getContent()));
        if (response.getStatusLine().getStatusCode() == 403)
            throw new SpikaForbiddenException();
        throw new IOException(response.getStatusLine().getReasonPhrase());
    }

    return entity.getContent();
}

From source file:com.hardincoding.sonar.subsonic.service.SubsonicMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;/*from w  w w  .j ava2s.  com*/
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Util.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        try {
            HttpResponse response = mHttpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;//w  w  w  . j  a v  a2  s  .co  m
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }

            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request "
                                + "with a non-repeatable request entity.  The cause lists the "
                                + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException(
                                "Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }

                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;

                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName()
                                    + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }

                    // If we have a direct route to the target host
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }

                }

            }

            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException ex) {
        abortConnection();
        throw ex;
    } catch (IOException ex) {
        abortConnection();
        throw ex;
    } catch (RuntimeException ex) {
        abortConnection();
        throw ex;
    }
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {

    HttpRequest orig = request;/*from  w  w  w .j av a 2  s.co m*/
    RequestWrapper origWrapper = wrapRequest(orig);
    origWrapper.setParams(params);
    HttpRoute origRoute = determineRoute(target, origWrapper, context);

    virtualHost = (HttpHost) orig.getParams().getParameter(ClientPNames.VIRTUAL_HOST);

    RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);

    long timeout = ConnManagerParams.getTimeout(params);

    int execCount = 0;

    boolean reuse = false;
    boolean done = false;
    try {
        HttpResponse response = null;
        while (!done) {
            // In this loop, the RoutedRequest may be replaced by a
            // followup request and route. The request and route passed
            // in the method arguments will be replaced. The original
            // request is still available in 'orig'.

            RequestWrapper wrapper = roureq.getRequest();
            HttpRoute route = roureq.getRoute();
            response = null;

            // See if we have a user token bound to the execution context
            Object userToken = context.getAttribute(ClientContext.USER_TOKEN);

            // Allocate connection if needed
            if (managedConn == null) {
                ClientConnectionRequest connRequest = connManager.requestConnection(route, userToken);
                if (orig instanceof AbortableHttpRequest) {
                    ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
                }

                try {
                    managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
                } catch (InterruptedException interrupted) {
                    InterruptedIOException iox = new InterruptedIOException();
                    iox.initCause(interrupted);
                    throw iox;
                }

                if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
                    // validate connection
                    if (managedConn.isOpen()) {
                        this.log.debug("Stale connection check");
                        if (managedConn.isStale()) {
                            this.log.debug("Stale connection detected");
                            managedConn.close();
                        }
                    }
                }
            }

            if (orig instanceof AbortableHttpRequest) {
                ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
            }

            // Reopen connection if needed
            if (!managedConn.isOpen()) {
                managedConn.open(route, context, params);
            } else {
                managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
            }

            try {
                establishRoute(route, context);
            } catch (TunnelRefusedException ex) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug(ex.getMessage());
                }
                response = ex.getResponse();
                break;
            }

            // Reset headers on the request wrapper
            wrapper.resetHeaders();

            // Re-write request URI if needed
            rewriteRequestURI(wrapper, route);

            // Use virtual host if set
            target = virtualHost;

            if (target == null) {
                target = route.getTargetHost();
            }

            HttpHost proxy = route.getProxyHost();

            // Populate the execution context
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
            context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, proxy);
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, managedConn);
            context.setAttribute(ClientContext.TARGET_AUTH_STATE, targetAuthState);
            context.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);

            // Run request protocol interceptors
            requestExec.preProcess(wrapper, httpProcessor, context);

            boolean retrying = true;
            Exception retryReason = null;
            while (retrying) {
                // Increment total exec count (with redirects)
                execCount++;
                // Increment exec count for this particular request
                wrapper.incrementExecCount();
                if (!wrapper.isRepeatable()) {
                    this.log.debug("Cannot retry non-repeatable request");
                    if (retryReason != null) {
                        throw new NonRepeatableRequestException("Cannot retry request "
                                + "with a non-repeatable request entity.  The cause lists the "
                                + "reason the original request failed: " + retryReason);
                    } else {
                        throw new NonRepeatableRequestException(
                                "Cannot retry request " + "with a non-repeatable request entity.");
                    }
                }

                try {
                    if (this.log.isDebugEnabled()) {
                        this.log.debug("Attempt " + execCount + " to execute request");
                    }
                    response = requestExec.execute(wrapper, managedConn, context);
                    retrying = false;

                } catch (IOException ex) {
                    this.log.debug("Closing the connection.");
                    managedConn.close();
                    if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
                        if (this.log.isInfoEnabled()) {
                            this.log.info("I/O exception (" + ex.getClass().getName()
                                    + ") caught when processing request: " + ex.getMessage());
                        }
                        if (this.log.isDebugEnabled()) {
                            this.log.debug(ex.getMessage(), ex);
                        }
                        this.log.info("Retrying request");
                        retryReason = ex;
                    } else {
                        throw ex;
                    }

                    // If we have a direct route to the target host
                    // just re-open connection and re-try the request
                    if (!route.isTunnelled()) {
                        this.log.debug("Reopening the direct connection.");
                        managedConn.open(route, context, params);
                    } else {
                        // otherwise give up
                        this.log.debug("Proxied connection. Need to start over.");
                        retrying = false;
                    }

                }

            }

            if (response == null) {
                // Need to start over
                continue;
            }

            // Run response protocol interceptors
            response.setParams(params);
            requestExec.postProcess(response, httpProcessor, context);

            // The connection is in or can be brought to a re-usable state.
            reuse = reuseStrategy.keepAlive(response, context);
            if (reuse) {
                // Set the idle duration of this connection
                long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
                managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);

                if (this.log.isDebugEnabled()) {
                    if (duration >= 0) {
                        this.log.debug("Connection can be kept alive for " + duration + " ms");
                    } else {
                        this.log.debug("Connection can be kept alive indefinitely");
                    }
                }
            }

            RoutedRequest followup = handleResponse(roureq, response, context);
            if (followup == null) {
                done = true;
            } else {
                if (reuse) {
                    // Make sure the response body is fully consumed, if present
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        entity.consumeContent();
                    }
                    // entity consumed above is not an auto-release entity,
                    // need to mark the connection re-usable explicitly
                    managedConn.markReusable();
                } else {
                    managedConn.close();
                }
                // check if we can use the same connection for the followup
                if (!followup.getRoute().equals(roureq.getRoute())) {
                    releaseConnection();
                }
                roureq = followup;
            }

            if (managedConn != null && userToken == null) {
                userToken = userTokenHandler.getUserToken(context);
                context.setAttribute(ClientContext.USER_TOKEN, userToken);
                if (userToken != null) {
                    managedConn.setState(userToken);
                }
            }

        } // while not done

        // check for entity, release connection if possible
        if ((response == null) || (response.getEntity() == null) || !response.getEntity().isStreaming()) {
            // connection not needed and (assumed to be) in re-usable state
            if (reuse)
                managedConn.markReusable();
            releaseConnection();
        } else {
            // install an auto-release entity
            HttpEntity entity = response.getEntity();
            entity = new BasicManagedEntity(entity, managedConn, reuse);
            response.setEntity(entity);
        }

        return response;

    } catch (HttpException | RuntimeException | IOException ex) {
        abortConnection();
        throw ex;
    }
}