Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

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

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

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

private static Map<String, ExchangeRate> getLitecoinChartsOld() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double ltcRate = getGoldCoinValueLTC();

    Double btcRate = 0.0;//  www  . ja  v  a 2  s.  co 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/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") * ltcRate;
                String euros = String.format("%.7f", 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.replace(",", ".")), 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.asimba.util.saml2.metadata.provider.MetadataProviderUtil.java

/**
 * Create a new HTTP Metadata Provider from the provided URL and HTTP settings<br/>
 * An exception is thrown when the provider could not be initiated.
 * //  w w  w. j  a  v a 2 s.  co  m
 * @param sMetadataURL
 * @param sMetadataTimeout
 * @param oParserPool
 * @param oMPM
 * @return
 * @throws OAException
 */
public static MetadataProvider newHTTPMetadataProvider(String sId, String sMetadataURL, int iTimeout,
        ParserPool oParserPool, IMetadataProviderManager oMPM) throws OAException {
    MetadataProvider oProvider = null;

    // Check URL format
    URL oURLTarget = null;
    try {
        oURLTarget = new URL(sMetadataURL);
    } catch (MalformedURLException e) {
        _oLogger.error("Invalid url for metadata: " + sMetadataURL, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }

    // Check valid and existing destination (with configured timeout settings)
    try {
        URLConnection oURLConnection = oURLTarget.openConnection();
        if (iTimeout <= 0) {
            oURLConnection.setConnectTimeout(3000);
            oURLConnection.setReadTimeout(3000);
        } else {
            oURLConnection.setConnectTimeout(iTimeout);
            oURLConnection.setReadTimeout(iTimeout);
        }

        oURLConnection.connect();
    } catch (IOException e) {
        _oLogger.warn("Could not connect to metadata url: " + sMetadataURL + "(using timout "
                + (iTimeout == 0 ? "3000" : iTimeout) + "ms)", e);
    }

    // Establish dedicated refresh timer:
    String sTimername = "Metadata_HTTP-" + (oMPM == null ? "" : oMPM.getId() + "-") + sId + "-Timer";
    Timer oRefreshTimer = new Timer(sTimername, true);

    // Establish HttpClient
    HttpClient oHttpClient = new HttpClient();

    if (iTimeout > 0) {
        // Set configured Timeout settings
        oHttpClient.getParams().setSoTimeout(iTimeout);
    }

    oProvider = MetadataProviderUtil.createProviderForURL(sMetadataURL, oParserPool, oRefreshTimer,
            oHttpClient);

    if (oProvider != null) {
        // Start managing it:
        if (oMPM != null) {
            oMPM.setProviderFor(sId, oProvider, oRefreshTimer);
        }
    } else {
        // Unsuccessful creation; clean up created Timer
        oRefreshTimer.cancel();
    }

    return oProvider;
}

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 w ww .  ja  v a 2  s.  com*/

    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:tufts.vue.ds.XMLIngest.java

private static InputStream getTestXMLStream() throws IOException {

    //         // SMF 2008-10-02: E.g. Craigslist XML streams use ISO-8859-1, which is provided in
    //         // HTML headers as "Content-Type: application/rss+xml; charset=ISO-8859-1", (tho not
    //         // in a special content-encoding header), and our current XML parser fails unless
    //         // the stream is read with this set: e.g.: [org.xml.sax.SAXParseException: Character
    //         // conversion error: "Unconvertible UTF-8 character beginning with 0x95" (line
    //         // number may be too low).]  Actually, in this case it turns out that providing a
    //         // default InputStreamReader (encoding not specified) as opposed to a direct
    //         // InputStream from the URLConnection works, and the XML parser is presumably then
    //         // finding and handling the "<?xml version="1.0" encoding="ISO-8859-1"?>" line at
    //         // the top of the XML stream
    //         final XmlSchema schema = new XmlSchema(conn.getURL(), itemKey);
    //         InputStream is = null;
    //         try {
    //             is = conn.getInputStream();
    //             errout("GOT INPUT STREAM: " + Util.tags(is));
    //         } catch (IOException e) {
    //             e.printStackTrace();
    //             return null;
    //         }/*from   ww  w.  j  a  v a  2 s.c  o m*/
    //         final Document doc = parseXML(is, false);

    // Could also use a ROME API XmlReader(URLConnection) for handling
    // the input, which does it's own magic to figure out the encoding.
    // For more on the complexity of this issue, see:
    // http://diveintomark.org/archives/2004/02/13/xml-media-types

    URL url = new URL(JIRA_VUE_URL);
    URLConnection conn = url.openConnection();
    conn.setRequestProperty("Cookie", JIRA_SFRAIZE_COOKIE);
    errout("Opening connection to " + url);
    conn.connect();

    errout("Getting InputStream...");
    InputStream in = conn.getInputStream();
    errout("Got " + Util.tags(in));

    errout("Getting headers...");
    Map<String, List<String>> headers = conn.getHeaderFields();

    errout("HEADERS:");
    for (Map.Entry<String, List<String>> e : headers.entrySet()) {
        errout(e.getKey() + ": " + e.getValue());
    }

    return in;
}

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

private static Object getGoldCoinValueBTC() {
    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;/*  w  w w.jav  a  2s.com*/
    String currencyCryptsy = "BTC";
    String urlCryptsy2 = "http://pubapi.cryptsy.com/api.php?method=marketdata";
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=30";

    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 = markets.getJSONObject("GLD");

            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 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: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 ww . ja  v  a2 s  .  com*/
    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:org.nuxeo.rss.reader.FeedHelper.java

public static SyndFeed parseFeed(String feedUrl) throws Exception {
    URL url = new URL(feedUrl);
    SyndFeedInput input = new SyndFeedInput();
    URLConnection urlConnection;
    if (FeedUrlConfig.useProxy()) {
        SocketAddress addr = new InetSocketAddress(FeedUrlConfig.getProxyHost(), FeedUrlConfig.getProxyPort());
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        urlConnection = url.openConnection(proxy);
        if (FeedUrlConfig.isProxyAuthenticated()) {
            String encoded = Base64.encodeBytes(
                    new String(FeedUrlConfig.getProxyLogin() + ":" + FeedUrlConfig.getProxyPassword())
                            .getBytes());
            urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
            urlConnection.connect();
        }//from   ww  w .  ja  v a 2 s . c o  m
    } else {
        urlConnection = url.openConnection();
    }
    SyndFeed feed = input.build(new XmlReader(urlConnection));
    return feed;
}

From source file:ubic.gemma.loader.expression.geo.DatasetCombiner.java

/**
 * Given a GDS, find the corresponding GSEs (there can be more than one in rare cases).
 * /*from w  w  w  .jav  a2s. co m*/
 * @param datasetAccession
 * @return Collection of series this data set is derived from (this is almost always just a single item).
 */
public static Collection<String> findGSEforGDS(String datasetAccession) {
    /*
     * go from GDS to GSE, using screen scraping.
     */
    // http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?db=gds&term=GSE674[Accession]&cmd=search
    // grep on "GDS[[digits]] record"
    URL url = null;

    Pattern pat = Pattern.compile(GSE_RECORD_REGEXP);

    Collection<String> associatedSeriesAccession = new HashSet<String>();

    try {
        url = new URL(ENTREZ_GEO_QUERY_URL_BASE + datasetAccession + ENTREZ_GEO_QUERY_URL_SUFFIX);

        URLConnection conn = url.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            Matcher mat = pat.matcher(line);
            if (mat.find()) {
                String capturedAccession = mat.group(1);
                associatedSeriesAccession.add(capturedAccession);
            }
        }
        is.close();
    } catch (MalformedURLException e) {
        log.error(e, e);
        throw new RuntimeException("Invalid URL " + url, e);
    } catch (IOException e) {
        log.error(e, e);
        throw new RuntimeException("Could not get data from remote server", e);
    }

    if (associatedSeriesAccession.size() == 0) {
        throw new IllegalStateException("No GSE found for " + datasetAccession);
    }

    return associatedSeriesAccession;

}

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 {//from w w w  .  j  a  va  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:com.elega9t.commons.geo.impl.HostIpDotInfoGeoLocationProvider.java

@Override
public GeoLocationInfo lookup(String ip) throws IOException {
    URL url = new URL("http://api.hostip.info/get_json.php?ip=" + URLEncoder.encode(ip, "UTF-8"));
    URLConnection connection = url.openConnection();
    connection.connect();
    InputStream inputStream = connection.getInputStream();
    String json = IOUtilities.toString(inputStream);
    inputStream.close();/*from w  ww.  j  a  v  a  2 s . co  m*/
    try {
        JSONObject object = new JSONObject(json);
        return new GeoLocationInfo(object.getString("ip"), object.getString("country_name"),
                object.getString("country_code"), object.getString("city"));
    } catch (JSONException e) {
        throw new IOException(e);
    }
}