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:com.frostwire.gui.library.LibraryUtils.java

private static InternetRadioStation processInternetRadioStationUrl(String urlStr) throws Exception {
    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(10000);
    conn.setRequestProperty("User-Agent", "Java");
    InputStream is = conn.getInputStream();
    BufferedReader d = null;/*from   w w w  .j  a v a 2 s  .c o  m*/
    if (conn.getContentEncoding() != null) {
        d = new BufferedReader(new InputStreamReader(is, conn.getContentEncoding()));
    } else {
        d = new BufferedReader(new InputStreamReader(is));
    }

    String pls = "";
    String[] props = null;
    String strLine;
    int numLine = 0;
    while ((strLine = d.readLine()) != null) {
        pls += strLine + "\n";
        if (strLine.startsWith("File1=")) {
            String streamUrl = strLine.split("=")[1];
            props = processStreamUrl(streamUrl);
        } else if (strLine.startsWith("icy-name:")) {
            pls = "";
            props = processStreamUrl(urlStr);
            break;
        }

        numLine++;
        if (numLine > 10) {
            if (props == null) { // not a valid pls
                break;
            }
        }
    }

    is.close();

    if (props != null && props[0] != null) {
        return LibraryMediator.getLibrary().newInternetRadioStation(props[0], props[0], props[1], props[2],
                props[3], props[4], props[5], pls, false);
    } else {
        return null;
    }
}

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

private static Map<String, ExchangeRate> getLitecoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//from   ww w.java 2s . c  o m

    Object result = getGoldCoinValueBTC();

    if (result == null) {
        return null;
    }

    else
        btcRate = (Double) result;

    //Double btcRate = 0.0;
    try {
        rates.put("BTC", new ExchangeRate("BTC",
                Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com"));
        String currencies[] = { "USD" };//, "BTC"};//, "RUR"};
        String urls[] = { "https://btc-e.com/api/2/1/ticker" };//, "https://btc-e.com/api/2/14/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") * btcRate;
                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 GLD!
            avg *= btcRate;
            String s_avg = String.format("%.8f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));

            //Add LTC information
            //s_avg = String.format("%.8f", ltcRate);
            //rates.put("LTC", new ExchangeRate("LTC", 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.goldcoin.ExchangeRatesProvider.java

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

    if ((now < (lastBitcoinValueCheck + 10 * 60)) && lastBitcoinValue > 0.0)
        return lastBitcoinValue;

    //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 .  ja  va 2 s .  c o  m
    String currencyCryptsy = "BTC";
    String urlCryptsy = "https://c-cex.com/t/gld-btc.json";

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

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            IOUtils.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());

            //JSONObject returnObject = head.getJSONObject("return");
            //JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject GLD = head.getJSONObject("ticker");

            //JSONArray recenttrades = GLD.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double gldTraded = 0.0;

            /*for(int i = 0; i < recenttrades.length(); ++i)
            {
            JSONObject trade = (JSONObject)recenttrades.get(i);
                    
            btcTraded += trade.getDouble("total");
            gldTraded += trade.getDouble("quantity");
                    
            }
                    
            Double averageTrade = btcTraded / gldTraded;
            */

            Double averageTrade = head.getDouble("buy");

            //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;

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

    return null;
}

From source file:com.frostwire.gui.library.LibraryUtils.java

private static String[] processStreamUrl(String streamUrl) throws Exception {
    URL url = new URL(streamUrl);
    System.out.print(" - " + streamUrl);
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(10000);
    conn.setRequestProperty("User-Agent", "Java");
    InputStream is = conn.getInputStream();
    BufferedReader d = null;/*from   www.  ja va 2 s .  c om*/
    if (conn.getContentEncoding() != null) {
        d = new BufferedReader(new InputStreamReader(is, conn.getContentEncoding()));
    } else {
        d = new BufferedReader(new InputStreamReader(is));
    }

    String name = null;
    String genre = null;
    String website = null;
    String type = null;
    String br = null;

    String strLine;
    int i = 0;
    while ((strLine = d.readLine()) != null && i < 10) {
        if (strLine.startsWith("icy-name:")) {
            name = clean(strLine.split(":")[1]);
        } else if (strLine.startsWith("icy-genre:")) {
            genre = clean(strLine.split(":")[1]);
        } else if (strLine.startsWith("icy-url:")) {
            website = strLine.split("icy-url:")[1].trim();
        } else if (strLine.startsWith("content-type:")) {
            String contentType = strLine.split(":")[1].trim();
            if (contentType.equals("audio/aacp")) {
                type = "AAC+";
            } else if (contentType.equals("audio/mpeg")) {
                type = "MP3";
            } else if (contentType.equals("audio/aac")) {
                type = "AAC";
            }
        } else if (strLine.startsWith("icy-br:")) {
            br = strLine.split(":")[1].trim() + " kbps";
        }
        i++;
    }

    is.close();

    return new String[] { name, streamUrl, br, type, website, genre };
}

From source file:mas.MAS.java

/**
 * @param args the command line arguments
 *//*ww  w .j a  v  a 2s . com*/
public static String getData_old(String url_org, int start) {
    try {
        String complete_url = url_org + "&$skip=" + start;
        //            String url_str = generateURL(url_org, prop);
        URL url = new URL(complete_url);
        URLConnection yc = url.openConnection();
        yc.setConnectTimeout(25 * 1000);
        yc.setReadTimeout(25 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            //                System.out.println(inputLine);
            result.append(inputLine);
        }
        in.close();
        return result.toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(MAS.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;/*  w  w w . j  a  v a 2s  .  c om*/
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

public static Pair<String, String> getPageDataOldImpl(URL url, int timeout) {
    StringBuffer sb = new StringBuffer();
    String charset = null;//from  www.j a  v a  2s . co m
    try {
        URLConnection connection = url.openConnection();
        if (timeout >= 0)
            connection.setConnectTimeout(timeout);
        InputStream is = connection.getInputStream();
        final String type = connection.getContentType();
        if (type != null) {
            final String[] parts = type.split(";");
            for (int i = 1; i < parts.length && charset == null; i++) {
                final String t = parts[i].trim();
                final int index = t.toLowerCase().indexOf("charset=");
                if (index != -1)
                    charset = t.substring(index + 8);
            }
        }
        InputStreamReader isr = null;
        if (charset != null)
            isr = new InputStreamReader(is, charset);
        else
            isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        int read = 0;
        while ((read = br.read()) != -1) {
            sb.append((char) read);
        }
        br.close();
        isr.close();
        is.close();
    } catch (Exception e) {
        Debug.error(e);
    }
    return new Pair<String, String>(sb.toString(), charset);
}

From source file:org.spoutcraft.launcher.util.Utils.java

public static String executePost(String targetURL, String urlParameters, JProgressBar progress)
        throws PermissionDeniedException {
    URLConnection connection = null;
    try {//  www. j  a v a 2 s .  c o  m
        URL url = new URL(targetURL);
        connection = url.openConnection();
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.setConnectTimeout(10000);

        connection.connect();

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        StringBuilder response = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        return response.toString();
    } catch (SocketException e) {
        if (e.getMessage().equalsIgnoreCase("Permission denied: connect")) {
            throw new PermissionDeniedException("Permission to login was denied");
        }
    } catch (Exception e) {
        String message = "Login failed...";
        progress.setString(message);
    }
    return null;
}

From source file:net.rptools.maptool.client.WebDownloader.java

/**
 * Read the data at the given URL. This method should not be called on the EDT.
 * /*  ww w  . ja va2 s.  c  o  m*/
 * @return File pointer to the location of the data, file will be deleted at program end
 */
public String read() throws IOException {
    URLConnection conn = url.openConnection();

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);

    // Send the request.
    conn.connect();

    InputStream in = null;
    ByteArrayOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new ByteArrayOutputStream();

        int buflen = 1024 * 30;
        int bytesRead = 0;
        byte[] buf = new byte[buflen];

        for (int nRead = in.read(buf); nRead != -1; nRead = in.read(buf)) {
            bytesRead += nRead;
            out.write(buf, 0, nRead);
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
    return out != null ? new String(out.toByteArray()) : null;
}

From source file:org.deegree.commons.proxy.ProxySettings.java

/**
 * This method should be used everywhere instead of <code>URL.openConnection()</code>, as it copes with proxies that
 * require user authentication and http basic authentication.
 * /*w w w.  j  a v  a2  s .  c  o  m*/
 * @param url
 * @return connection
 * @throws IOException
 */
public static URLConnection openURLConnection(URL url, String proxyUser, String proxyPass, String httpUser,
        String httpPass) throws IOException {
    URLConnection conn = url.openConnection();
    if (proxyUser != null) {
        // TODO evaluate java.net.Authenticator
        String userAndPass = Base64.encodeBase64String((proxyUser + ":" + proxyPass).getBytes());
        conn.setRequestProperty("Proxy-Authorization", "Basic " + userAndPass);
    }
    if (httpUser != null) {
        // TODO evaluate java.net.Authenticator
        String userAndPass = Base64.encodeBase64String((httpUser + ":" + httpPass).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + userAndPass);
    }
    // TODO should this be a method parameter?
    conn.setConnectTimeout(5000);
    return conn;
}