Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:com.adaptris.core.services.dynamic.RemoteMarshallServiceStore.java

@Override
protected Service unmarshal(String s) throws CoreException {
    Service result = null;//from   www.  j a  v  a2 s .  c o m

    String remoteFile = getBaseUrl() + "/" + defaultIfEmpty(getFileNamePrefix(), "") + s
            + defaultIfEmpty(getFileNameSuffix(), "");
    try {
        URL url = new URL(remoteFile);
        log.debug("Retrieving [{}]", remoteFile);
        URLConnection c = url.openConnection();
        try (Reader reader = new InputStreamReader(c.getInputStream())) {
            result = (Service) currentMarshaller().unmarshal(reader);
        }
    } catch (IOException e) {
        if (e instanceof FileNotFoundException) {
            log.debug("service file name [{}] not found in store", remoteFile);
            result = null;
        } else {
            throw new CoreException(e);
        }
    }
    return result;
}

From source file:com.datos.vfs.provider.url.UrlFileObject.java

/**
 * Returns the size of the file content (in bytes).
 *//*  w ww  . jav  a2  s  .  co m*/
@Override
protected long doGetContentSize() throws Exception {
    final URLConnection conn = url.openConnection();
    final InputStream in = conn.getInputStream();
    try {
        return conn.getContentLength();
    } finally {
        in.close();
    }
}

From source file:com.datos.vfs.provider.url.UrlFileObject.java

/**
 * Returns the last modified time of this file.
 *//*from   www  .  j  a v  a 2  s  . c  o  m*/
@Override
protected long doGetLastModifiedTime() throws Exception {
    final URLConnection conn = url.openConnection();
    final InputStream in = conn.getInputStream();
    try {
        return conn.getLastModified();
    } finally {
        in.close();
    }
}

From source file:fr.jayasoft.ivy.url.BasicURLHandler.java

public void download(URL src, File dest, CopyProgressListener l) throws IOException {
    URLConnection srcConn = null;
    try {/*www .  j ava2  s.co m*/
        srcConn = src.openConnection();
        FileUtil.copy(srcConn.getInputStream(), dest, l);
    } finally {
        if (srcConn != null) {
            if (srcConn instanceof HttpURLConnection) {
                //System.out.println("Closing HttpURLConnection");
                ((HttpURLConnection) srcConn).disconnect();
            }
        }
    }
}

From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.GeekIncLogoDownloadService.java

public void downloadAndResize(int requiredSize) throws Exception {
    // Si le logo existe depuis moins d'une semaine, on ne le retlcharge
    // pas/* w w w . ja  va  2  s  .c  o  m*/
    if (outFile.exists()) {
        // Moins une semaine
        long uneSemainePlusTot = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000);

        if (outFile.lastModified() > uneSemainePlusTot) {
            Log.i("GeekIncLogoDownloadService",
                    "Le logo a dj t tlcharg il y a moins d'une semaine.");
            return;
        }
    }

    URLConnection ucon = toDownload.openConnection();
    InputStream is = ucon.getInputStream();

    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    bis.close();
    is.close();

    // Fichier temporaire pour redimensionnement
    File tmpFile = new File(outFile.getAbsolutePath() + "tmp");
    FileOutputStream fos = new FileOutputStream(tmpFile);
    fos.write(baf.toByteArray());
    fos.close();

    saveAndResizeFile(tmpFile, outFile, requiredSize);

    // Suppression du fichier temporaire
    tmpFile.delete();
}

From source file:com.glaf.base.modules.todo.job.TodoQuartzJob.java

public void sendMessageToAllUsersViaJSP() {
    try {/*www .j av a 2 s.  c o  m*/
        if (sendMessageServiceUrl != null) {
            URL url = new URL(sendMessageServiceUrl);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
            InputStream in = con.getInputStream();
            in = new BufferedInputStream(in);
            Reader r = new InputStreamReader(in);
            int c;
            logger.debug("==============Beging====================");

            while ((c = r.read()) != -1) {
                logger.debug((char) c);
            }
            in.close();

            logger.debug("===============End======================");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    }
}

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  w w  . ja va 2  s .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:richtercloud.reflection.form.builder.components.FixerAmountMoneyExchangeRateRetriever.java

private FixerJsonResponse retrieveResponse() throws AmountMoneyCurrencyStorageException {
    try {// ww w.j  av a2s.c om
        URLConnection uRLConnection = new URL(FIXER_URL).openConnection();
        InputStream inputStream = uRLConnection.getInputStream();
        String responseJsonString = IOUtils.toString(inputStream);
        LOGGER.debug(String.format("%s replied: %s", FIXER_URL, responseJsonString));
        FixerJsonResponse response = new ObjectMapper().readValue(responseJsonString, FixerJsonResponse.class);
        return response;
    } catch (MalformedURLException ex) {
        throw new AmountMoneyCurrencyStorageException(ex);
    } catch (IOException ex) {
        throw new AmountMoneyCurrencyStorageException(ex);
    }
}

From source file:com.adamrosenfield.wordswithcrosses.net.derstandard.SolutionParser.java

private InputStream getInputStream(String publicid, String systemid) throws IOException, SAXException {
    URL basis = new URL("file", "", System.getProperty("user.dir") + "/.");
    URL url = new URL(basis, systemid);
    URLConnection c = url.openConnection();
    return c.getInputStream();
}

From source file:com.bradleyjh.blazefly.Updater.java

public void run() {
    URL url;// w  w  w.  j a  v  a  2 s.com
    try {
        url = new URL("https://api.curseforge.com/servermods/files?projectIds=50224");
    } catch (MalformedURLException e) {
        return;
    }

    try {
        URLConnection conn = url.openConnection();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = reader.readLine();
        JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() > 0) {
            JSONObject latest = (JSONObject) array.get(array.size() - 1);
            String latestFile = (String) latest.get("name");

            // SomePlugin v2.3 = "230", SomePlugin v2.3.4 = "234"
            // means we can check if the newer file is a newer version
            String latestVersion = latestFile.replaceAll("\\D+", "");
            if (latestVersion.length() == 2) {
                latestVersion = latestVersion + "0";
            }
            thisVersion = thisVersion.replaceAll("\\D+", "");
            if (thisVersion.length() == 2) {
                thisVersion = thisVersion + "0";
            }

            if (Integer.parseInt(latestVersion) > Integer.parseInt(thisVersion)) {
                main.updateAvailable = latestFile;
                main.getLogger().info(latestFile + " is available for download!");
            }
        }
    } catch (IOException e) {
        return;
    }
}