Example usage for org.apache.http.conn ConnectTimeoutException ConnectTimeoutException

List of usage examples for org.apache.http.conn ConnectTimeoutException ConnectTimeoutException

Introduction

In this page you can find the example usage for org.apache.http.conn ConnectTimeoutException ConnectTimeoutException.

Prototype

public ConnectTimeoutException() 

Source Link

Document

Creates a ConnectTimeoutException with a null detail message.

Usage

From source file:com.aliyun.oss.common.utils.ExceptionFactoryTest.java

@Test
public void testCreateNetworkException() {
    SocketTimeoutException ste = new SocketTimeoutException();
    ClientException ex = ExceptionFactory.createNetworkException(ste);
    assertEquals(ex.getErrorCode(), ClientErrorCode.SOCKET_TIMEOUT);
    ConnectTimeoutException cte = new ConnectTimeoutException();
    ex = ExceptionFactory.createNetworkException(cte);
    assertEquals(ex.getErrorCode(), ClientErrorCode.CONNECTION_TIMEOUT);
    IOException ioe = new IOException();
    ex = ExceptionFactory.createNetworkException(ioe);
    assertEquals(ex.getErrorCode(), ClientErrorCode.UNKNOWN);
}

From source file:bad.robot.http.apache.ApacheExceptionWrappingExecutorTest.java

@Test
public void wrapsConnectTimeoutException() {
    exception.expect(HttpConnectionTimeoutException.class);
    exception.expect(new ThrowableCauseMatcher(ConnectTimeoutException.class));
    wrapper.submit(throwsException(new ConnectTimeoutException()));
}

From source file:org.jolokia.client.J4pClientTest.java

@Test(expectedExceptions = J4pTimeoutException.class, expectedExceptionsMessageRegExp = ".*timeout.*")
public void timeout() throws IOException, MalformedObjectNameException, J4pException {
    throwException(false, new ConnectTimeoutException());
}

From source file:org.jolokia.client.J4pClientTest.java

@Test(expectedExceptions = J4pTimeoutException.class, expectedExceptionsMessageRegExp = ".*timeout.*")
public void connectExceptionForBulkRequests() throws IOException, J4pException {
    throwException(true, new ConnectTimeoutException());
}

From source file:com.kubeiwu.commontool.khttp.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();// 
    while (true) {// while???while
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {/*  w  w w.j  a  va2 s  .c  o  m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());// cache
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();

            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
                return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data,
                        responseHeaders, true);
            }

            // Some responses such as 204s do not have content. We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());// entity?byte[];
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;// 
            logSlowRequests(requestLifetime, request, responseContents, statusLine);// log?

            if (statusCode < 200 || statusCode > 299) {
                System.out.println("http-NetworkResponse performRequest==statusCode=" + statusCode);
                switch (statusCode) {
                case HttpStatus.SC_REQUEST_TIMEOUT:// 408

                    throw new ConnectTimeoutException();
                default:
                    throw new IOException();
                }
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);// ?
        } catch (SocketTimeoutException e) {
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(e);// bug networkResponsenull,e??
                // throw new NetworkError(networkResponse);
            }
        }
    }
}

From source file:org.elasticsearch.client.RestClientSingleHostTests.java

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class),
            any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)))
                    .thenAnswer(new Answer<Future<HttpResponse>>() {
                        @Override
                        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
                            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock
                                    .getArguments()[0];
                            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
                            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
                            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock
                                    .getArguments()[3];
                            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
                            //return the desired status code or exception depending on the path
                            if (request.getURI().getPath().equals("/soe")) {
                                futureCallback.failed(new SocketTimeoutException());
                            } else if (request.getURI().getPath().equals("/coe")) {
                                futureCallback.failed(new ConnectTimeoutException());
                            } else {
                                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1),
                                        statusCode, "");

                                HttpResponse httpResponse = new BasicHttpResponse(statusLine);
                                //return the same body that was sent
                                if (request instanceof HttpEntityEnclosingRequest) {
                                    HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                                    if (entity != null) {
                                        assertTrue(
                                                "the entity is not repeatable, cannot set it to the response directly",
                                                entity.isRepeatable());
                                        httpResponse.setEntity(entity);
                                    }/*w ww . j a  v  a2 s.c om*/
                                }
                                //return the same headers that were sent
                                httpResponse.setHeaders(request.getAllHeaders());
                                futureCallback.completed(httpResponse);
                            }
                            return null;
                        }
                    });

    defaultHeaders = RestClientTestUtil.randomHeaders(getRandom(), "Header-default");
    httpHost = new HttpHost("localhost", 9200);
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, defaultHeaders, new HttpHost[] { httpHost }, null,
            failureListener);
}

From source file:es.sonxurxo.android.androidroulette.client.HttpHelper.java

public void start() throws NoMateFoundException, Exception {

    this.request = new HttpPost(this.FULL_ADDRESS + this.START_URL);

    try {//from   w w w.jav a  2  s. c  o m
        HttpConnectionParams.setConnectionTimeout(client.getParams(), HttpHelper.TIMEOUT);
        HttpConnectionParams.setSoTimeout(client.getParams(), HttpHelper.TIMEOUT);
        this.response = client.execute(this.request);
        String s = this.convertStreamToString(this.response.getEntity().getContent());
        if (new JSONObject(s).getString(this.JSON_MESSAGE).equals(this.JSON_NO_MATE_FOUND)) {
            throw new NoMateFoundException();
        }

    } catch (NoMateFoundException e) {
        throw e;
    } catch (ConnectTimeoutException e) {
        throw e;
    } catch (SocketTimeoutException e) {
        throw new ConnectTimeoutException();
    } catch (Exception e) {
        throw e;
    }
}

From source file:eu.vital.TrustManager.connectors.dms.DMSManager.java

private String queryWithExceptions(String dms_endpoint, String body, String method)
        throws SocketTimeoutException, ConnectException, IOException, InterruptedException {
    Cookie ck;//from w  ww.j a va  2s  .co  m
    //String internalToken;
    CloseableHttpClient httpclient;
    HttpRequestBase httpaction;
    //boolean wasEmpty;
    //int code;

    httpclient = HttpClients.createDefault();

    URI uri = null;
    try {
        // Prepare to forward the request to the proxy
        uri = new URI(dms_URL + "/" + dms_endpoint);
    } catch (URISyntaxException e1) {
        java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
    }

    if (method.equals("GET")) {
        httpaction = new HttpGet(uri);
    } else {
        httpaction = new HttpPost(uri);
    }

    // Get token or authenticate if null or invalid
    //internalToken = client.getToken();
    ck = new Cookie("vitalAccessToken", cookie.substring(17));

    httpaction.setHeader("Cookie", ck.toString());
    httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000)
            .setSocketTimeout(5000).build());
    httpaction.setHeader("Content-Type", javax.ws.rs.core.MediaType.APPLICATION_JSON);

    StringEntity strEntity = new StringEntity(body, StandardCharsets.UTF_8);

    if (method.equals("POST")) {
        ((HttpPost) httpaction).setEntity(strEntity);
    }

    // Execute and get the response.
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpaction);
    } catch (ClientProtocolException e) {
        throw new ClientProtocolException();
    } catch (IOException e) {
        try {
            // Try again with a higher timeout
            try {
                Thread.sleep(1000); // do not retry immediately
            } catch (InterruptedException e1) {
                throw new InterruptedException();
                // e1.printStackTrace();
            }
            httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(7000)
                    .setConnectTimeout(7000).setSocketTimeout(7000).build());
            response = httpclient.execute(httpaction);
        } catch (ClientProtocolException ea) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, ea);
            throw new ClientProtocolException();
        } catch (IOException ea) {
            try {
                // Try again with a higher timeout
                try {
                    Thread.sleep(1000); // do not retry immediately
                } catch (InterruptedException e1) {
                    java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e1);
                    throw new InterruptedException();
                }
                httpaction.setConfig(RequestConfig.custom().setConnectionRequestTimeout(12000)
                        .setConnectTimeout(12000).setSocketTimeout(12000).build());
                response = httpclient.execute(httpaction);
            } catch (ClientProtocolException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ClientProtocolException();
            } catch (SocketTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new SocketTimeoutException();
            } catch (ConnectException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectException();
            } catch (ConnectTimeoutException eaa) {
                java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, eaa);
                throw new ConnectTimeoutException();
            }
        }
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) {
        if (statusCode == 503) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 503");
            throw new ServiceUnavailableException();
        } else if (statusCode == 502) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 502");
            throw new ServerErrorException(502);
        } else if (statusCode == 401) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "could't Athorize the DMS");
            throw new NotAuthorizedException("could't Athorize the DMS");
        } else {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null,
                    "httpStatusCode 500");
            throw new ServiceUnavailableException();
        }
    }

    HttpEntity entity;
    entity = response.getEntity();
    String respString = "";

    if (entity != null) {
        try {
            respString = EntityUtils.toString(entity);
            response.close();
        } catch (ParseException | IOException e) {
            java.util.logging.Logger.getLogger(DMSManager.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return respString;

}