Search in sources :

Example 6 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project platform_external_apache-http by android.

the class DefaultClientConnectionOperator method openConnection.

// non-javadoc, see interface ClientConnectionOperator
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (conn.isOpen()) {
        throw new IllegalArgumentException("Connection must not be open.");
    }
    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    final SocketFactory sf = schm.getSocketFactory();
    final SocketFactory plain_sf;
    final LayeredSocketFactory layered_sf;
    if (sf instanceof LayeredSocketFactory) {
        plain_sf = staticPlainSocketFactory;
        layered_sf = (LayeredSocketFactory) sf;
    } else {
        plain_sf = sf;
        layered_sf = null;
    }
    InetAddress[] addresses = InetAddress.getAllByName(target.getHostName());
    for (int i = 0; i < addresses.length; ++i) {
        Socket sock = plain_sf.createSocket();
        conn.opening(sock, target);
        try {
            Socket connsock = plain_sf.connectSocket(sock, addresses[i].getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            /*
                 * prepareSocket is called on the just connected
                 * socket before the creation of the layered socket to
                 * ensure that desired socket options such as
                 * TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
                 * before any I/O is performed on the socket. This
                 * happens in the common case as
                 * SSLSocketFactory.createSocket performs hostname
                 * verification which requires that SSL handshaking be
                 * performed.
                 */
            prepareSocket(sock, context, params);
            if (layered_sf != null) {
                Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true);
                if (layeredsock != sock) {
                    conn.opening(layeredsock, target);
                }
                conn.openCompleted(sf.isSecure(layeredsock), params);
            } else {
                conn.openCompleted(sf.isSecure(sock), params);
            }
            break;
        // BEGIN android-changed
        //       catch SocketException to cover any kind of connect failure
        } catch (SocketException ex) {
            if (i == addresses.length - 1) {
                final ConnectException cause;
                if (ex instanceof ConnectException) {
                    cause = (ConnectException) ex;
                } else {
                    cause = new ConnectException(ex.getMessage());
                    cause.initCause(ex);
                }
                throw new HttpHostConnectException(target, cause);
            }
        // END android-changed
        } catch (ConnectTimeoutException ex) {
            if (i == addresses.length - 1) {
                throw ex;
            }
        }
    }
}
Also used : SocketException(java.net.SocketException) Scheme(org.apache.http.conn.scheme.Scheme) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) SocketFactory(org.apache.http.conn.scheme.SocketFactory) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) InetAddress(java.net.InetAddress) Socket(java.net.Socket) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 7 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project sling by apache.

the class CheckRootIT method testHttpRoot.

@Test
public void testHttpRoot() throws Exception {
    final HttpUriRequest get = new HttpGet(TestSuiteLauncherIT.crankstartSetup.getBaseUrl());
    HttpResponse response = null;
    long timeout = System.currentTimeMillis() + 60000L;
    boolean found = false;
    try {
        while (System.currentTimeMillis() < timeout) {
            try {
                response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == 404) {
                    found = true;
                    break;
                }
            } catch (HttpHostConnectException e) {
                Thread.sleep(1000);
            }
        }
        if (!found) {
            Assert.fail("Expected to get 404 from " + get.getURI());
        }
    } finally {
        Models.closeConnection(response);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 8 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project stanbol by apache.

the class StanbolTestBase method waitForServerReady.

@Before
public void waitForServerReady() throws Exception {
    log.debug("> before {}#waitForServerReady()", getClass().getSimpleName());
    // initialize instance request builder and HTTP client
    builder = new RequestBuilder(serverBaseUrl);
    //TODO:user name and pwd
    String credentials = getCredentials();
    if (credentials != null && !credentials.isEmpty()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(HttpHost.create(serverBaseUrl)), new UsernamePasswordCredentials(credentials));
        httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    } else {
        httpClient = HttpClients.createDefault();
    }
    executor = new RequestExecutor(httpClient);
    if (serverReady) {
        log.debug(" ... server already marked as ready!");
        return;
    }
    // Timeout for readiness test
    final String sec = System.getProperty(SERVER_READY_TIMEOUT_PROP);
    final int timeoutSec = sec == null ? 60 : Integer.valueOf(sec);
    log.info("Will wait up to " + timeoutSec + " seconds for server to become ready");
    final long endTime = System.currentTimeMillis() + timeoutSec * 1000L;
    // Get the list of paths to test and expected content regexps
    final List<String> testPaths = new ArrayList<String>();
    final TreeSet<Object> propertyNames = new TreeSet<Object>();
    propertyNames.addAll(System.getProperties().keySet());
    for (Object o : propertyNames) {
        final String key = (String) o;
        if (key.startsWith(SERVER_READY_PROP_PREFIX)) {
            testPaths.add(System.getProperty(key));
        }
    }
    // Consider the server ready if it responds to a GET on each of 
    // our configured request paths with a 200 result and content
    // that matches the regexp supplied with the path
    long sleepTime = 100;
    readyLoop: while (!serverReady && System.currentTimeMillis() < endTime) {
        // Wait a bit between checks, to let the server come up
        Thread.sleep(sleepTime);
        sleepTime = Math.min(5000L, sleepTime * 2);
        // A test path is in the form path:substring or just path, in which case
        // we don't check that the content contains the substring 
        log.debug(" - check serverReady Paths");
        for (String p : testPaths) {
            final String[] s = p.split(":");
            final String path = s[0];
            final String substring = (s.length > 0 ? s[1] : null);
            final String url = serverBaseUrl + path;
            log.debug("    > url: {}", url);
            log.debug("    > content: {}", substring);
            final HttpGet get = new HttpGet(url);
            //authenticate as admin with password admin
            get.setHeader("Authorization", "Basic YWRtaW46YWRtaW4=");
            for (int i = 2; i + 1 < s.length; i = i + 2) {
                log.debug("    > header: {}:{}", s[i], s[i + 1]);
                if (s[i] != null && !s[i].isEmpty() && s[i + 1] != null && !s[i + 1].isEmpty()) {
                    get.setHeader(s[i], s[i + 1]);
                }
            }
            CloseableHttpResponse response = null;
            HttpEntity entity = null;
            try {
                log.debug("    > execute: {}", get);
                response = httpClient.execute(get);
                log.debug("    > response: {}", response);
                entity = response.getEntity();
                final int status = response.getStatusLine().getStatusCode();
                if (status != 200) {
                    log.info("Got {} at {} - will retry", status, url);
                    continue readyLoop;
                } else {
                    log.debug("Got {} at {} - will retry", status, url);
                }
                if (substring != null) {
                    if (entity == null) {
                        log.info("No entity returned for {} - will retry", url);
                        continue readyLoop;
                    }
                    final String content = EntityUtils.toString(entity);
                    if (!content.contains(substring)) {
                        log.info("Returned content for {}  does not contain " + "{} - will retry", url, substring);
                        continue readyLoop;
                    }
                }
            } catch (HttpHostConnectException e) {
                log.info("Got HttpHostConnectException at " + url + " - will retry");
                continue readyLoop;
            } finally {
                EntityUtils.consumeQuietly(entity);
                if (response != null) {
                    response.close();
                }
            }
        }
        serverReady = true;
        log.info("Got expected content for all configured requests, server is ready");
    }
    if (!serverReady) {
        throw new Exception("Server not ready after " + timeoutSec + " seconds");
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) RequestBuilder(org.apache.stanbol.commons.testing.http.RequestBuilder) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) RequestExecutor(org.apache.stanbol.commons.testing.http.RequestExecutor) ArrayList(java.util.ArrayList) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) MalformedURLException(java.net.MalformedURLException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) TreeSet(java.util.TreeSet) AuthScope(org.apache.http.auth.AuthScope) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) Before(org.junit.Before)

Example 9 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project sling by apache.

the class SimpleHttpDistributionTransport method deliverPackage.

public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage, @Nonnull DistributionTransportContext distributionContext) throws DistributionException {
    String hostAndPort = getHostAndPort(distributionEndpoint.getUri());
    DistributionPackageInfo info = distributionPackage.getInfo();
    URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class);
    if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) {
        log.debug("skipping distribution of package {} to same origin {}", distributionPackage.getId(), hostAndPort);
    } else {
        try {
            Executor executor = getExecutor(distributionContext);
            Request req = Request.Post(distributionEndpoint.getUri()).connectTimeout(httpConfiguration.getConnectTimeout()).socketTimeout(httpConfiguration.getSocketTimeout()).addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE).useExpectContinue();
            // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2
            if (distributionPackage instanceof AbstractDistributionPackage) {
                AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage;
                if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) {
                    req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage()));
                }
            }
            InputStream inputStream = null;
            try {
                inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage);
                req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM);
                Response response = executor.execute(req);
                // throws an error if HTTP status is >= 300
                response.returnContent();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
            log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri());
        } catch (HttpHostConnectException e) {
            throw new RecoverableDistributionException("endpoint not available " + distributionEndpoint.getUri(), e);
        } catch (HttpResponseException e) {
            int statusCode = e.getStatusCode();
            if (statusCode == 404 || statusCode == 401) {
                throw new RecoverableDistributionException("not enough rights for " + distributionEndpoint.getUri(), e);
            }
            throw new DistributionException(e);
        } catch (Exception e) {
            throw new DistributionException(e);
        }
    }
}
Also used : DistributionPackageInfo(org.apache.sling.distribution.packaging.DistributionPackageInfo) InputStream(java.io.InputStream) Request(org.apache.http.client.fluent.Request) DistributionRequest(org.apache.sling.distribution.DistributionRequest) HttpResponseException(org.apache.http.client.HttpResponseException) URI(java.net.URI) DistributionException(org.apache.sling.distribution.common.DistributionException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) HttpResponseException(org.apache.http.client.HttpResponseException) Response(org.apache.http.client.fluent.Response) Executor(org.apache.http.client.fluent.Executor) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) DistributionException(org.apache.sling.distribution.common.DistributionException) RecoverableDistributionException(org.apache.sling.distribution.common.RecoverableDistributionException) AbstractDistributionPackage(org.apache.sling.distribution.packaging.impl.AbstractDistributionPackage)

Example 10 with HttpHostConnectException

use of org.apache.http.conn.HttpHostConnectException in project dropwizard by dropwizard.

the class DropwizardApacheConnectorTest method connect_timeout_override_changes_how_long_it_takes_for_a_connection_to_timeout.

/**
     * <p>In first assertion we prove, that a request takes no longer than:
     * <em>request_time < connect_timeout + error_margin</em> (1)</p>
     * <p/>
     * </p>In the second we show that if we set <b>connect_timeout</b> to
     * <b>set_connect_timeout + increase + error_margin</b> then
     * <em>request_time > connect_timeout + increase + error_margin</em> (2)</p>
     * <p/>
     * <p>Now, (1) and (2) can hold at the same time if then connect_timeout update was successful.</p>
     */
@Test
public void connect_timeout_override_changes_how_long_it_takes_for_a_connection_to_timeout() {
    // before override
    WebTarget target = client.target(NON_ROUTABLE_ADDRESS);
    //This can't be tested without a real connection
    try {
        target.request().get(Response.class);
    } catch (ProcessingException e) {
        if (e.getCause() instanceof HttpHostConnectException) {
            return;
        }
    }
    assertThatConnectionTimeoutFor(target).isLessThan(DEFAULT_CONNECT_TIMEOUT_IN_MILLIS + ERROR_MARGIN_IN_MILLIS);
    // after override
    final int newTimeout = DEFAULT_CONNECT_TIMEOUT_IN_MILLIS + INCREASE_IN_MILLIS + ERROR_MARGIN_IN_MILLIS;
    final WebTarget newTarget = target.property(ClientProperties.CONNECT_TIMEOUT, newTimeout);
    assertThatConnectionTimeoutFor(newTarget).isGreaterThan(newTimeout);
}
Also used : HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) WebTarget(javax.ws.rs.client.WebTarget) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Aggregations

HttpHostConnectException (org.apache.http.conn.HttpHostConnectException)17 ConnectException (java.net.ConnectException)6 Socket (java.net.Socket)6 LayeredSocketFactory (org.apache.http.conn.scheme.LayeredSocketFactory)6 Scheme (org.apache.http.conn.scheme.Scheme)6 HttpResponse (org.apache.http.HttpResponse)4 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)4 InputStream (java.io.InputStream)3 InetAddress (java.net.InetAddress)3 SocketException (java.net.SocketException)3 HttpGet (org.apache.http.client.methods.HttpGet)3 PlainSocketFactory (org.apache.http.conn.scheme.PlainSocketFactory)3 SocketFactory (org.apache.http.conn.scheme.SocketFactory)3 IOException (java.io.IOException)2 URI (java.net.URI)2 HttpEntity (org.apache.http.HttpEntity)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2 HttpResponseException (org.apache.http.client.HttpResponseException)2 Executor (org.apache.http.client.fluent.Executor)2 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)2