Example usage for java.net ConnectException getMessage

List of usage examples for java.net ConnectException getMessage

Introduction

In this page you can find the example usage for java.net ConnectException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:client.lib.Client.java

private Response request(OkHttpClient client, URL url) {
    Response response = null;//from www .j  av a 2  s. com

    try {
        System.out.println(client.getProtocols().get(0) + " => " + url.toString());

        Request request = new Request.Builder().url(url.toString()).build();
        response = client.newCall(request).execute();

        System.out.println("> " + response.code() + " " + response.protocol());

    } catch (ConnectException e) {
        System.out.println("ConnectException: " + e.getMessage());
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
    }

    return response;
}

From source file:org.apache.camel.component.http4.HttpNoConnectionRedeliveryTest.java

@Test
public void httpConnectionNotOk() throws Exception {
    // stop server so there are no connection
    // and wait for it to terminate
    localServer.stop();//from w w w .  j av a2 s.co m
    localServer.awaitTermination(5000);

    Exchange exchange = template.request("direct:start", null);
    assertTrue(exchange.isFailed());

    ConnectException cause = assertIsInstanceOf(ConnectException.class, exchange.getException());
    assertTrue(cause.getMessage().contains("refused"));

    assertEquals(true, exchange.getIn().getHeader(Exchange.REDELIVERED));
    assertEquals(4, exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER));
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//  w w  w.ja  v a  2s .c  om
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:com.intel.iotkitlib.LibHttp.HttpDeleteTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/*from  w w  w. j a v  a 2s . c o m*/
        HttpContext localContext = new BasicHttpContext();
        HttpDelete httpDelete = new HttpDelete(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpDelete.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpDelete.getURI());
            Header[] headers = httpDelete.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpDelete, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }
        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.intel.iotkitlib.http.HttpDeleteTask.java

public CloudResponse doSync(String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {//from   www.  j ava2  s. c o  m
        HttpContext localContext = new BasicHttpContext();
        HttpDelete httpDelete = new HttpDelete(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpDelete.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpDelete.getURI());
            Header[] headers = httpDelete.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpDelete, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }
        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//from   w  w  w .  j  ava  2  s  .  c  o  m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

From source file:com.intel.iotkitlib.LibHttp.HttpGetTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {//from  w  w  w  . j  av a 2 s.  co  m
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpGet.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpGet.getURI());
            Header[] headers = httpGet.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.intel.iotkitlib.http.HttpGetTask.java

public CloudResponse doSync(String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {//from  www . j  a  v a 2 s . c  o  m
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpGet.addHeader(nvp.getName(), nvp.getValue());
        }
        if (debug) {
            Log.e(TAG, "URI is : " + httpGet.getURI());
            Header[] headers = httpGet.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
        }
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:org.apache.sling.launchpad.LaunchpadReadyRule.java

private void runCheck(CloseableHttpClient client, Check check) throws Exception {

    String lastFailure = null;//  w  ww.  j a  v  a  2s . c om
    HttpGet get = new HttpGet(check.getUrl());

    for (int i = 0; i < TRIES; i++) {
        try (CloseableHttpResponse response = client.execute(get)) {

            if (response.getStatusLine().getStatusCode() != 200) {
                lastFailure = "Status code is " + response.getStatusLine();
                Thread.sleep(WAIT_BETWEEN_TRIES_MILLIS);
                continue;
            }

            lastFailure = check.runCheck(response);
            if (lastFailure == null) {
                return;
            }
        } catch (ConnectException e) {
            lastFailure = e.getClass().getName() + " : " + e.getMessage();
        }

        Thread.sleep(WAIT_BETWEEN_TRIES_MILLIS);
    }

    throw new RuntimeException(String.format("Launchpad not ready. Failed check for URL %s with message '%s'",
            check.getUrl(), lastFailure));
}

From source file:com.twistbyte.affiliate.HttpUtility.java

/**
 * Do a get request to the given url and set the header values passed
 *
 * @param url//  w  ww  .  ja  v a2 s  .c o  m
 * @param headerValues
 * @return
 */
public HttpResult doGet(String url, Map<String, String> headerValues) {

    String resp = "";

    logger.info("url : " + url);
    GetMethod method = new GetMethod(url);

    logger.info("Now use connection timeout: " + connectionTimeout);
    httpclient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);

    if (headerValues != null) {
        for (Map.Entry<String, String> entry : headerValues.entrySet()) {

            method.setRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResult serviceResult = new HttpResult();
    serviceResult.setSuccess(false);
    serviceResult.setHttpStatus(404);
    Reader reader = null;
    try {

        int result = httpclient.executeMethod(new HostConfiguration(), method, new HttpState());
        logger.info("http result : " + result);
        resp = method.getResponseBodyAsString();

        logger.info("response: " + resp);

        serviceResult.setHttpStatus(result);
        serviceResult.setBody(resp);
        serviceResult.setSuccess(200 == serviceResult.getHttpStatus());
    } catch (java.net.ConnectException ce) {
        logger.warn("ConnectException: " + ce.getMessage());
    } catch (IOException e) {
        logger.error("IOException sending request to " + url + " Reason:" + e.getMessage(), e);
    } finally {
        method.releaseConnection();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {

            }
        }
    }

    return serviceResult;
}