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:org.arasthel.almeribus.utils.LoadFromWeb.java

public static ResultTiempo calcularTiempo(Context context, int parada, int linea) {
    ResultTiempo result = new ResultTiempo();
    if (!isConnectionEnabled(context)) {
        Log.d("AlmeriBus", "No hay conexin");
        result.setTiempo(ERROR_IO);/*from w  w  w  .  j  a  v  a2  s . c  om*/
    }
    try {
        loadCookie();
        URL url = new URL(QUERY_ADDRESS_TIEMPO_PARADA + linea + "/" + parada + "/" + "3B5579C8FFD6");
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera/");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        Log.d("Almeribus", strBuilder.toString());
        JSONObject json = new JSONObject(strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        int type = json.getInt("waitTimeType");
        if (isSuccessful && type > 0) {
            int time = json.getInt("waitTime");
            if (time == Integer.MAX_VALUE) {
                time = NO_DATOS;
            }
            if (time <= 0) {
                time = 0;
            }
            result.setTiempo(time);
            result.setTiempoTexto(json.getString("waitTimeString"));
        } else {
            result.setTiempo(NO_DATOS);
        }
    } catch (Exception e) {
        Log.d("Almeribus", e.toString());
        result.setTiempo(ERROR_IO);
        return result;
    }
    return result;
}

From source file:org.wso2.carbon.cloud.gateway.agent.CGAgentUtils.java

public static OMNode getOMElementFromURI(String wsdlURI) throws CGException {
    if (wsdlURI == null || "null".equals(wsdlURI)) {
        throw new CGException("Can't create URI from a null value");
    }//from   w  w w .  j a  v a  2 s.c om
    URL url;
    try {
        url = new URL(wsdlURI);
    } catch (MalformedURLException e) {
        throw new CGException("Invalid URI reference '" + wsdlURI + "'", e);
    }
    URLConnection connection;
    connection = getURLConnection(url);
    if (connection == null) {
        throw new CGException("Cannot create a URLConnection for given URL : " + url);
    }
    connection.setReadTimeout(getReadTimeout());
    connection.setConnectTimeout(getConnectTimeout());
    connection.setRequestProperty("Connection", "close"); // if http is being used
    InputStream inStream = null;

    try {
        inStream = connection.getInputStream();
        StAXOMBuilder builder = new StAXOMBuilder(inStream);
        OMElement doc = builder.getDocumentElement();
        doc.build();
        return doc;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Reading as XML failed due to ", e);
        }
        return readNonXML(url);
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            log.warn("Error while closing the input stream to: " + url, e);
        }
    }
}

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

public static String fetchContent(final String stateUrl, final String ipStr, final int port, final int timeout)
        throws IOException {
    final URLConnection conn = new URL(stateUrl)
            .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipStr, port)));
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
    }//w  w w  .  j a  v  a 2  s . c o m
    conn.connect();

    return IOUtils.toString(new InputStreamReader(conn.getInputStream(), UTF8_STR));
}

From source file:ru.codeinside.gses.webui.form.JsonForm.java

static String loadTemplate(ActivitiApp app, String ref) {
    try {/*from  w  ww  .  j  a va2  s .c o m*/
        URL serverUrl = app.getServerUrl();
        URL url = new URL(serverUrl, ref);
        logger().info("fetch template " + url);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.setUseCaches(false);
        connection.connect();
        return Streams.toString(connection.getInputStream());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getMensajeDesarrollador() {
    String mensaje = null;// w  w  w.  j a v a 2 s . c  o m
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/message.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static String getUltimaVersion() {
    String mensaje = null;/*from  ww w.  j  a v  a 2s.  co  m*/
    try {
        URL url = new URL("http://arasthel.byethost14.com/almeribus/version.html?token="
                + new Random().nextInt(Integer.MAX_VALUE));
        URLConnection connection = url.openConnection();
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(15000);
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        mensaje = strBuilder.toString();
    } catch (Exception e) {

    }
    return mensaje;
}

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

private static Map<String, ExchangeRate> getFeathercoinCharts() {
    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  . j  av a 2 s  .  c om*/
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_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 FTC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        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 feathercoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        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 dollars.  We want FTC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle FTC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        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 FTC!
            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.worldcoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getworldcoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;/*from   ww w  .j  a  va 2 s .c om*/
    try {
        /*          String currencies[] = {"USD", "BTC", "RUR"};
                    String urls[] = {"https://btc-e.com/api/2/ftc_btc/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_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 WDC/USD special since we have to do maths
        URL URL = null;
        try {
            URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        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 worldcoins priced in bitcoins
            btcRate = avg;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/USD special since we have to do maths
        URL = null;
        URL = new URL("https://btc-e.com/api/2/btc_usd/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        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 dollars.  We want WDC!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        // Handle WDC/BTC special since we have to do maths
        URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        content = new StringBuilder();

        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 FTC!
            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:org.arasthel.almeribus.utils.LoadFromWeb.java

public static int cargarParadasLinea(Context context, int numeroLinea) {
    if (!isConnectionEnabled(context)) {
        return SIN_CONEXION;
    }//from   www.  ja v a 2s.  com
    try {
        if (cookie == null) {
            if (loadCookie() == MANTENIMIENTO) {
                return MANTENIMIENTO;
            }
        }
        URL url = new URL(QUERY_ADDRESS_PARADAS_LINEA + numeroLinea);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.connect();
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        JSONObject json = new JSONObject(strBuilder.toString());
        Log.d("Almeribus", strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        if (isSuccessful) {
            DataStorage.DBHelper.eliminarParadasLinea(numeroLinea);
            Linea l = new Linea(numeroLinea);
            JSONArray list = json.getJSONArray("list");
            Parada primeraParada = null;
            Parada paradaAnterior = null;
            for (int i = 0; i < list.length(); i++) {
                JSONObject paradaJSON = list.getJSONObject(i);
                int numeroParada = paradaJSON.getInt("IdBusStop");
                String nombreParada = paradaJSON.getString("Name");
                Parada p = null;
                if (DataStorage.paradas.containsKey(numeroParada)) {
                    p = DataStorage.paradas.get(numeroParada);
                    p.setNombre(nombreParada);
                } else {
                    p = new Parada(numeroParada, nombreParada);
                }
                synchronized (DataStorage.DBHelper) {
                    DataStorage.DBHelper.addInfoParada(numeroParada, nombreParada);
                }
                p.addLinea(l.getNumero());
                if (paradaAnterior != null) {
                    p.setAnterior(paradaAnterior.getId(), numeroLinea);
                }

                if (i == 0) {
                    primeraParada = p;
                } else if (i == list.length() - 1) {
                    primeraParada.setAnterior(p.getId(), numeroLinea);
                    p.setSiguiente(primeraParada.getId(), numeroLinea);
                }

                if (paradaAnterior != null) {
                    paradaAnterior.setSiguiente(p.getId(), numeroLinea);
                }

                paradaAnterior = p;
                synchronized (DataStorage.paradas) {
                    if (DataStorage.paradas.containsKey(numeroParada)) {
                        DataStorage.paradas.remove(numeroParada);
                    }
                    DataStorage.paradas.put(numeroParada, p);
                }

                l.addParada(p);
            }
            DataStorage.lineas.put(numeroLinea, l);
            for (Parada parada : l.getParadas()) {
                synchronized (DataStorage.DBHelper) {
                    try {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea,
                                parada.getSiguiente(numeroLinea));
                    } catch (ParadaNotFoundException e) {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, 0);
                    }
                }
            }
            return TODO_OK;
        } else {
            return ERROR_IO;
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        return ERROR_IO;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ERROR_IO;
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;//from w  w  w.j  a  va 2s .  c o  m
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        final URLConnection connectionCryptsy = URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

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

    return null;
}