Example usage for java.net ConnectException printStackTrace

List of usage examples for java.net ConnectException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:Main.java

public static boolean isPortOpen(final String ip, final int port, final int timeout) {
    try {/*  w  ww  . j a  va2s  . c  o m*/
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(ip, port), timeout);
        socket.close();
        return true;
    }

    catch (ConnectException ce) {
        ce.printStackTrace();
        return false;
    }

    catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
}

From source file:org.eclipse.virgo.qa.performance.UrlWaitLatch.java

private static void waitForServerShutdownFully(String url, HttpClient client, long interval, long duration) {
    HttpMethod get = new GetMethod(url);

    try {/*from  www .  j a  v a 2s .c om*/
        for (;;) {
            try {
                client.executeMethod(get);
                Thread.sleep(interval);
            } catch (ConnectException e) {
                break;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } finally {
        get.releaseConnection();
    }
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?/*  w ww.j  av a2  s  . c om*/
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:org.geosdi.geoplatform.publish.HttpUtilsLocal.java

public static boolean httpPing(String url, String username, String pw) {

    GetMethod httpMethod = null;/*from   ww  w  .j a  va2s  . com*/

    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        int status = client.executeMethod(httpMethod);
        if (status != HttpStatus.SC_OK) {
            LOGGER.warn("PING failed at '" + url + "': (" + status + ") " + httpMethod.getStatusText());
            return false;
        } else {
            return true;
        }

    } catch (ConnectException e) {
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private static List<String> connectAndReadFromURL(URL url) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*w  w  w .  jav a  2 s .  c o m*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair(osParam, os));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode == HttpStatus.SC_OK) {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        } else {
            JOptionPane.showMessageDialog(null, "Incorrect response from server: " + responseCode);
        }

    } catch (java.net.ConnectException e) {
        String note = "Connection error 1 while connecting to " + url.toString() + ":\n" + getProxyInfo();
        //+ checkListeningPort("127.0.0.1", 8888);
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 1: " + e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        String note = "Connection error 2 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 2: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        String note = "Connection error 3 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 3: " + e.getMessage());
        e.printStackTrace();
    } catch (KeyManagementException e) {
        String note = "Connection error 4 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 4: " + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        String note = "Connection error 5 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 5: " + e.getMessage());
        e.printStackTrace();
    } catch (KeyStoreException e) {
        String note = "Connection error 6 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 6: " + e.getMessage());
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        String note = "Connection error 7 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 7: " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}

From source file:org.accelio.jxio.tests.benchmarks.jxioConnection.StreamClient.java

public void run() {
    for (int i = 0; i < repeats; i++) {
        try {/*ww  w.  j a v  a2 s  . co m*/
            long time = System.nanoTime();
            connection = new JxioConnection(uri);
            if (type.compareTo("input") == 0)
                read();
            else if (type.compareTo("output") == 0)
                write();
            else
                throw new UnsupportedOperationException("stream type " + type + " is not supported");
            calcBW(time);
            connection.disconnect();
        } catch (ConnectException e1) {
            e1.printStackTrace();
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        try {
            Thread.currentThread().sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:uk.org.openeyes.APIUtils.java

/**
 * Trigger a WS call through HTTP for patient search
 * /*from  w w w.  j  ava  2  s  .c o m*/
 * @param resourceType The REST resource name (only "Patient" supported now)
 * @param requestParams The arguments for the HTTP call 
 * @return The status code from the HTTP answer
 * @throws ConnectException 
 */
public int read(String resourceType, String requestParams) throws ConnectException {

    DefaultHttpClient http = new DefaultHttpClient();

    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType
            + "?resource_type=Patient&_format=xml";
    if (requestParams != null) {
        strURL += "&" + requestParams;
    }
    HttpGet get = new HttpGet(strURL);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(authUserName, authUserPassword);

    get.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));

    try {
        get.addHeader("Content-type", "text/xml");
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient httpclient = builder.build();

        CloseableHttpResponse httpResponse = httpclient.execute(get);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();
        StringWriter writer = new StringWriter();
        //IOUtils.copy(entity2.getContent(), writer);
        this.response = entity2.getContent().toString();
        EntityUtils.consume(entity2);
    } catch (ConnectException e) {
        // this happens when there's no server to connect to
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return result;
}

From source file:uk.org.openeyes.diagnostics.HttpTransfer.java

/**
 * /*from w w  w.j  a  va2  s.c  om*/
 * @param resourceType
 * @param jsonType
 * @param requestParams
 * @param username
 * @param password
 * @return
 * @throws ConnectException 
 */
public int read(String resourceType, String jsonType, String requestParams, String username, String password)
        throws ConnectException {
    DefaultHttpClient http = new DefaultHttpClient();

    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType
            + "?resource_type=Patient&_format=xml";
    if (requestParams != null) {
        strURL += "&" + requestParams;
    }
    HttpGet get = new HttpGet(strURL);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    get.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));

    try {
        get.addHeader("Content-type", "text/xml");
        HttpClientBuilder builder = HttpClientBuilder.create();
        CloseableHttpClient httpclient = builder.build();

        CloseableHttpResponse httpResponse = httpclient.execute(get);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();
        StringWriter writer = new StringWriter();
        IOUtils.copy(entity2.getContent(), writer);
        this.response = writer.toString();
        EntityUtils.consume(entity2);
    } catch (ConnectException e) {
        // this happens when there's no server to connect to
        e.printStackTrace();
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();
    }
    return result;
}

From source file:uk.org.openeyes.diagnostics.FhirUtils.java

/**
 * //from  w  w  w  .  ja va 2s  .  c o m
 * @param host
 * @param port
 * @param metaData
 * @param username
 * @param password
 * @return
 * @throws ConnectException 
 */
public Patient readPatient(String host, int port, HumphreyFieldMetaData metaData, String username,
        String password) throws ConnectException {
    Patient p = null;
    HttpTransfer sender = new HttpTransfer();
    String requestParams = "identifier=" + metaData.getPatientId();
    //            + "&last_name=" + metaData.getFamilyName()
    //            + "&first_name=" + metaData.getGivenName();
    sender.setHost(host);
    sender.setPort(port);
    int result = -1;
    try {
        result = sender.read("Patient", "pat", requestParams, username, password);
        if (result == 200) {
            FeedDocument doc = FeedDocument.Factory.parse(sender.getResponse());
            if (doc.getFeed().getEntryArray().length > 0) {
                EntryType entry = doc.getFeed().getEntryArray(0);
                ContentType content = entry.getContentArray(0);
                p = content.getPatient();
                // reference to patient, last part is ID:
                p.setId(FilenameUtils.getBaseName(entry.getIdArray(0).getStringValue()));
            }
        }
    } catch (ConnectException ex) {
        throw ex;
    } catch (XmlException ex) {
        ex.printStackTrace();
    }
    return p;
}

From source file:uk.org.openeyes.diagnostics.HttpTransfer.java

/**
 * /* www.  j a  v  a  2 s . com*/
 * @param resourceType
 * @param data
 * @param username
 * @param password
 * @return
 * @throws ConnectException 
 */
public int send(String resourceType, String data, String username, String password) throws ConnectException {
    int result = -1;
    String strURL = "http://" + host + ":" + port + "/api/" + resourceType + "?_format=xml&resource_type="
            + resourceType;
    HttpPost post = new HttpPost(strURL);
    try {
        data = data.replace("fhir:", "");
        StringEntity entity = new StringEntity(data);
        post.setEntity(entity);
        post.addHeader("Content-type", "text/xml");
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
        post.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
        DefaultHttpClient httpclient = new DefaultHttpClient();

        CloseableHttpResponse httpResponse = httpclient.execute(post);
        result = httpResponse.getStatusLine().getStatusCode();
        HttpEntity entity2 = httpResponse.getEntity();

        StringWriter writer = new StringWriter();
        IOUtils.copy(entity2.getContent(), writer);
        this.response = writer.toString();
        EntityUtils.consume(entity2);
        Header[] headers = post.getHeaders("Location");
        if (headers.length > 0) {
            this.location = headers[0];
        }

    } catch (ConnectException e) {
        // TODO - binary exponential backoff algorithm  
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
    return result;
}