Example usage for java.net URLConnection setReadTimeout

List of usage examples for java.net URLConnection setReadTimeout

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

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 ava 2s.  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:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getLycancoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    try {/*from w w  w  . j a v  a 2 s.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: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 ww .j  a v a  2 s.  co  m*/
    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:Main.java

/**
 *  This method is used to send a XML request file to web server to process the request and return
 *  xml response containing event id./*www.  jav a2 s.  co  m*/
 */
public static String postXMLWithTimeout(String postUrl, String xml, int readTimeout) throws Exception {

    System.out.println("XMLUtils.postXMLWithTimeout: Connecting to Web Server .......");

    InputStream in = null;
    BufferedReader bufferedReader = null;
    OutputStream out = null;
    PrintWriter printWriter = null;
    StringBuffer responseMessageBuffer = new StringBuffer("");

    try {
        URL url = new URL(postUrl);
        URLConnection con = url.openConnection();

        // Prepare for both input and output
        con.setDoInput(true);
        con.setDoOutput(true);

        // Turn off caching
        con.setUseCaches(false);
        con.setRequestProperty("Content-Type", "text/xml");
        con.setReadTimeout(readTimeout);
        out = con.getOutputStream();
        // Write the arguments as post data
        printWriter = new PrintWriter(out);

        printWriter.println(xml);
        printWriter.flush();

        //Process response and return back to caller function
        in = con.getInputStream();
        bufferedReader = new BufferedReader(new InputStreamReader(in));
        String tempStr = null;

        int tempClearResponseMessageBufferCounter = 0;
        while ((tempStr = bufferedReader.readLine()) != null) {
            tempClearResponseMessageBufferCounter++;
            //clear the buffer for the first time
            if (tempClearResponseMessageBufferCounter == 1)
                responseMessageBuffer.setLength(0);
            responseMessageBuffer.append(tempStr);
        }

    } catch (Exception ex) {
        throw ex;
    } finally {
        System.out.println("Calling finally in POSTXML");
        try {
            if (in != null)
                in.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Input Stream in try");
        }
        try {
            if (out != null)
                out.close();
        } catch (Exception eex) {
            System.out.println("COULD NOT Close Output Stream in try");
        }

    }
    System.out.println("XMLUtils.postXMLWithTimeout: end .......");
    return responseMessageBuffer.toString();
}

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;//from   www  .  j av a 2 s .c  o m
    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.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;/*from  w w  w. jav 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.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);//  ww w .j a va2 s .  c om
    connection.setReadTimeout(5000);
    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:net.technicpack.rest.RestObject.java

public static <T extends RestObject> T getRestObject(Class<T> restObject, String url)
        throws RestfulAPIException {
    InputStream stream = null;//from   w  w w  .ja va  2  s . c o m
    try {
        URLConnection conn = new URL(url).openConnection();
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);

        stream = conn.getInputStream();
        String data = IOUtils.toString(stream, Charsets.UTF_8);
        T result = gson.fromJson(data, restObject);

        if (result == null) {
            throw new RestfulAPIException("Unable to access URL [" + url + "]");
        }

        if (result.hasError()) {
            throw new RestfulAPIException("Error in response: " + result.getError());
        }

        return result;
    } catch (SocketTimeoutException e) {
        throw new RestfulAPIException("Timed out accessing URL [" + url + "]", e);
    } catch (MalformedURLException e) {
        throw new RestfulAPIException("Invalid URL [" + url + "]", e);
    } catch (JsonParseException e) {
        throw new RestfulAPIException("Error parsing response JSON at URL [" + url + "]", e);
    } catch (IOException e) {
        throw new RestfulAPIException("Error accessing URL [" + url + "]", e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

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

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from w w  w .  jav a  2  s  . c  o m*/
        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.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadTM(final String url, final String authUrl, final String username,
        final String password, final int timeout) throws IOException {
    InputStream in = null;//w w w. jav  a 2  s. com
    OutputStream out = null;

    try {
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();

        if (timeout != 0) {
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
        }

        if (urlc instanceof HttpsURLConnection) {
            final String cookie = getTmCookie(authUrl, username, password, timeout).toString();

            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
            http.addRequestProperty("Cookie", cookie);
        }

        in = urlc.getInputStream();

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}