Example usage for java.net URLConnection setConnectTimeout

List of usage examples for java.net URLConnection setConnectTimeout

Introduction

In this page you can find the example usage for java.net URLConnection setConnectTimeout.

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:org.apache.niolex.commons.net.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl//from  w  ww  .j  a v a  2  s  .co m
 *            The Url to be downloaded.
 * @param connectTimeout
 *            Connect timeout in milliseconds.
 * @param readTimeout
 *            Read timeout in milliseconds.
 * @param maxFileSize
 *            Max file size in BYTE.
 * @param useCache Whether we use thread local cache or not.
 * @return The file content as byte array.
 * @throws NetException
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize,
        Boolean useCache) throws NetException {
    LOG.debug("Start to download file [{}], C{}R{}M{}.", strUrl, connectTimeout, readTimeout, maxFileSize);
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // We use Java URL to download file.
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.setDoOutput(false);
        ucon.setDoInput(true);
        ucon.connect();
        final int contentLength = ucon.getContentLength();
        validateContentLength(strUrl, contentLength, maxFileSize);
        if (ucon instanceof HttpURLConnection) {
            validateHttpCode(strUrl, (HttpURLConnection) ucon);
        }
        in = ucon.getInputStream(); // Get the input stream.
        byte[] ret = null;
        // Create the byte array buffer according to the strategy.
        if (contentLength > 0) {
            ret = commonDownload(contentLength, in);
        } else {
            ret = unusualDownload(strUrl, in, maxFileSize, useCache);
        }
        LOG.debug("Succeeded to download file [{}] size {}.", strUrl, ret.length);
        return ret;
    } catch (NetException e) {
        LOG.info(e.getMessage());
        throw e;
    } catch (Exception e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.toString();
        LOG.warn(msg);
        throw new NetException(NetException.ExCode.IOEXCEPTION, msg, e);
    } finally {
        // Close the input stream.
        StreamUtil.closeStream(in);
    }
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getLycancoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    try {// ww  w  .  j  ava2s.co  m
        String currencies[] = { "USD", "EUR" };
        String urls[] = { "https://btc-e.com/api/2/btc_usd/ticker", "https://btc-e.com/api/2/btc_eur/ticker" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                JSONObject ticker = head.getJSONObject("ticker");
                Double avg = ticker.getDouble("avg") * LycBtcRate;
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros),
                        "cryptsy.com and " + URL.getHost()));
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.feanor.yeoldemensa.data.MensaFactory.java

/**
 * Returns an input stream for the given path on the server defined by
 * MensaFactory.SERVER_URL. Checks for a valid internet connection before
 * conneting.//from w  w w  .  j  av a  2  s.  co m
 * 
 * @param path
 *            Path on the server/URL
 * @param context
 *            Application context, required for connection check
 * @return Inputstream for the given path
 * @throws IOException
 *             Thrown if problems with the connection occur
 */
private static InputStream getInputStream(String path) throws IOException {
    URLConnection conn = new URL(SERVER_URL + path).openConnection();
    conn.setConnectTimeout(TIMEOUT * 1000);
    conn.setReadTimeout(TIMEOUT * 1000);

    return conn.getInputStream();
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchSecureContent(final String url, final int timeout) throws IOException {
    LOGGER.info("fetchSecureContent: " + url);
    final URL u = new URL(url);
    final URLConnection conn = u.openConnection();
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);//w w  w .  j a  v a 2  s  .c  om
    }
    if (conn instanceof HttpsURLConnection) {
        final HttpsURLConnection http = (HttpsURLConnection) conn;
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        http.setRequestMethod(GET_STR);
        http.setAllowUserInteraction(true);
    }
    return IOUtils.toString(conn.getInputStream());
}

From source file:de.schildbach.wallet.elysium.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getElysiumCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;// w  w  w  .j ava 2 s  .c om
    try {
        String currencies[] = { "USD", "BTC", "RUR" };
        String urls[] = { "https://btc-e.com/api/2/14/ticker", "https://btc-e.com/api/2/10/ticker",
                "https://btc-e.com/api/2/elsm_rur/ticker" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                JSONObject ticker = head.getJSONObject("ticker");
                Double avg = ticker.getDouble("avg");
                String euros = String.format("%.4f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle ELSM/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is elysiums priced in euros.  We want ELSM!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * checks if GRIT can connect to the remote SVN server.
 *
 * @param svnRepoAdress/*from w ww.  java  2 s.co  m*/
 *            the adress of the remote
 * @return true if GRIT can connect to the SVN.
 * @throws SubmissionFetchingException
 *             If the URL to the SVN is invalid.
 */
private static boolean checkConnectionToRemoteSVN(String svnRepoAdress) throws SubmissionFetchingException {
    try {
        int connectionTimeoutMillis = 10000;
        if (!svnRepoAdress.startsWith("file://")) {
            URL svnRepoLocation = new URL(svnRepoAdress);
            URLConnection svnRepoConnection = svnRepoLocation.openConnection();
            svnRepoConnection.setConnectTimeout(connectionTimeoutMillis);
            svnRepoConnection.connect();
        }
        return true;
    } catch (MalformedURLException e) {
        throw new SubmissionFetchingException(
                "Bad URL specified. Can not connect to this URL: " + svnRepoAdress + e.getMessage());
    } catch (IOException e) {
        return false;
    }
}

From source file:de.schildbach.wallet.marscoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getmarscoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;/*  w  w w .  ja v a2 s  . c  o  m*/
    try {
        String currencies[] = { "BTC" };
        //String urls[] = {"https://cryptorush.in/api.php?get=market&m=mrs&b=btc&json=true"};
        String urls[] = { "http://hlds.ws/marscoinj/api" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                //JSONObject ticker = head.getJSONObject("ticker");
                //rate = Float.parseFloat(head.getString("current_ask"));
                Double avg = head.getDouble("current_ask");
                //Double avg = Float.parseFloat(head.getString("current_ask"));
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle LTC/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want MRS!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from ww w  .j  av a  2s . c om*/
        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                final String rate = o.optString("15m", null);

                if (rate != null)
                    rates.put(currencyCode,
                            new ExchangeRate(currencyCode, Utils.toNanoCoins(rate), URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.hortonworks.amstore.view.AmbariStoreHelper.java

@SuppressWarnings("restriction")
public static String readStringFromUrl(String url, String username, String password) throws IOException {

    URLConnection connection = new URL(url).openConnection();
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);/*from   w  w w  . j a v a2 s  .c o m*/
    connection.setDoOutput(true);

    if (username != null) {
        String userpass = username + ":" + password;
        // TODO: Use apache commons instead.
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
        connection.setRequestProperty("Authorization", basicAuth);
    }
    InputStream in = connection.getInputStream();

    try {
        return IOUtils.toString(in, "UTF-8");
    } finally {
        in.close();
    }
}

From source file:Downloader.java

/**
 * Creates an URL connection for the specified URL and data.
 * /*from w ww. ja  va2  s. c o m*/
 * @param url The URL to connect to
 * @param postData The POST data to pass to the URL
 * @return An URLConnection for the specified URL/data
 * @throws java.net.MalformedURLException If the specified URL is malformed
 * @throws java.io.IOException If an I/O exception occurs while connecting
 */
private static URLConnection getConnection(final String url, final String postData)
        throws MalformedURLException, IOException {
    final URL myUrl = new URL(url);
    final URLConnection urlConn = myUrl.openConnection();

    urlConn.setUseCaches(false);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(postData.length() > 0);
    urlConn.setConnectTimeout(10000);

    if (postData.length() > 0) {
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        final DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
        out.writeBytes(postData);
        out.flush();
        out.close();
    }

    return urlConn;
}