Example usage for java.net URL openStream

List of usage examples for java.net URL openStream

Introduction

In this page you can find the example usage for java.net URL openStream.

Prototype

public final InputStream openStream() throws java.io.IOException 

Source Link

Document

Opens a connection to this URL and returns an InputStream for reading from that connection.

Usage

From source file:com.gs.obevo.util.IOUtilsDA.java

public static String toString(URL url) {
    // This method overload was added after 2.0. We have this here for backwards-compatibility with 2.0 for some
    // clients/* www .j  a va  2s . c  om*/
    // return IOUtils.toString(url);

    try {
        InputStream inputStream = url.openStream();
        try {
            return toString(inputStream);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wareninja.opensource.gravatar4android.common.Utils.java

public static byte[] downloadImage_alternative1(String imageUrl) throws GenericException {
    InputStream stream = null;//from   w  w  w . j  ava2s  .c om
    try {
        URL url = new URL(imageUrl);
        stream = url.openStream();
        return IOUtils.toByteArray(stream);
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {
        throw new GenericException(e);
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:lyonlancer5.karasu.util.ModFileUtils.java

static void download(String url, File output) throws IOException {
    URL url1 = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(url1.openStream());
    FileOutputStream fos = new FileOutputStream(output);

    if (!output.exists()) {
        output.getParentFile().mkdirs();
        output.createNewFile();//from   w ww .  ja  v a 2  s.  c  o  m
    }

    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
}

From source file:Main.java

public static void insertUrl(Context context, Uri contentUri, URL sourceUrl) {
    if (DEBUG) {/*from   www  .j  a va 2 s .  c  om*/
        Log.d(TAG, "Inserting " + sourceUrl + " to " + contentUri);
    }
    InputStream is = null;
    OutputStream os = null;
    try {
        is = sourceUrl.openStream();
        os = context.getContentResolver().openOutputStream(contentUri);
        copy(is, os);
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to write " + sourceUrl + "  to " + contentUri, ioe);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // Ignore exception.
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                // Ignore exception.
            }
        }
    }
}

From source file:com.tesora.dve.common.PELogUtils.java

private static Attributes readManifestFile() throws PEException {
    try {// ww w . ja va2  s  .co m
        Enumeration<URL> resources = PELogUtils.class.getClassLoader().getResources(MANIFEST_FILE_NAME);

        Attributes attrs = new Attributes();
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            if (url.toString().contains(CORE_PROJECT_NAME)) {
                Manifest manifest = new Manifest(url.openStream());
                attrs = manifest.getMainAttributes();
                break;
            }
        }
        return attrs;
    } catch (Exception e) {
        throw new PEException("Error retrieving build manifest", e);
    }
}

From source file:flink.iso8583.parse.ConfigParser.java

/** Creates a message factory from the file located at the specified URL. */
public static MessageFactory createFromUrl(URL url) throws IOException {
    MessageFactory mfact = new MessageFactory();
    InputStream stream = url.openStream();
    try {/*w w  w  .  j a  va 2  s  .  co  m*/
        parse(mfact, stream);
    } finally {
        stream.close();
    }
    return mfact;
}

From source file:com.millcreeksoftware.amliclookup.fcclookup.FccLookupHandler.java

/**
 * Gets the FCC data for the provided call sign.
 * /*from w ww  .j  a  va  2 s  . co m*/
 * @param callSign The call sign to lookup.
 * 
 * @return A populated <code>FccLookupData</code>.
 */
public static FccLookupData getFccData(String callSign) {
    FccLookupData fccLookupData = new FccLookupData();

    URL url;
    try {
        url = new URL(FCC_LOOKUP_BASE_URL + callSign);
        ObjectMapper m = new ObjectMapper();
        JsonNode rootNode = m.readValue(url.openStream(), JsonNode.class);

        String status = rootNode.path("status").textValue();
        if (!"OK".equalsIgnoreCase(status)) {
            return fccLookupData;
        }

        fccLookupData.setStatusOK(true);

        JsonNode licensesNode = rootNode.path("Licenses");
        String lastUpdate = licensesNode.path("lastUpdate").asText();
        fccLookupData.setLastUpdate(lastUpdate);

        JsonNode licenseNode = licensesNode.path("License");
        JsonNode arrayNode = licenseNode.path(0);
        String frn = arrayNode.path("frn").asText();
        fccLookupData.setFrn(frn);

        String statusDesc = arrayNode.path("statusDesc").asText();
        fccLookupData.setStatusDesc(statusDesc);

        String expiredDate = arrayNode.path("expiredDate").asText();
        fccLookupData.setExpireDate(expiredDate);

        String licenseId = arrayNode.path("licenseID").asText();
        fccLookupData.setLicenseId(licenseId);

        fccLookupData.setFccUrl(FFC_MORE_INFO_BASE_URL + licenseId);
    } catch (MalformedURLException e) {
        fccLookupData.setStatusOK(false);
        logger.warn("Error looking up call '" + callSign + "'.", e);
    } catch (JsonParseException e) {
        fccLookupData.setStatusOK(false);
        logger.warn("Error looking up call '" + callSign + "'.", e);
    } catch (JsonMappingException e) {
        fccLookupData.setStatusOK(false);
        logger.warn("Error looking up call '" + callSign + "'.", e);
    } catch (IOException e) {
        fccLookupData.setStatusOK(false);
        logger.warn("Error looking up call '" + callSign + "'.", e);
    }

    return fccLookupData;
}

From source file:net.minecrell.serverlistplus.canary.SnakeYAML.java

@SneakyThrows
public static void load(Plugin plugin) {
    try { // Check if it is already loaded
        Class.forName("org.yaml.snakeyaml.Yaml");
        return;//w  w  w.  j a  v  a  2s  . c om
    } catch (ClassNotFoundException ignored) {
    }

    Path path = Paths.get("lib", SNAKE_YAML_JAR);

    if (Files.notExists(path)) {
        Files.createDirectories(path.getParent());

        plugin.getLogman().info("Downloading SnakeYAML...");

        URL url = new URL(SNAKE_YAML);
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");

        try (ReadableByteChannel source = Channels.newChannel(new DigestInputStream(url.openStream(), sha1));
                FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW,
                        StandardOpenOption.WRITE)) {
            out.transferFrom(source, 0, Long.MAX_VALUE);
        }

        if (!new String(Hex.encodeHex(sha1.digest())).equals(EXPECTED_HASH)) {
            Files.delete(path);
            throw new IllegalStateException(
                    "Downloaded SnakeYAML, but checksum check failed. Please try again later.");
        }

        plugin.getLogman().info("Successfully downloaded!");
    }

    loadJAR(path);
}

From source file:org.jberet.support.io.MongoItemReaderTest.java

static void addTestData(final String dataResource, final String mongoCollection, final int minSizeIfExists)
        throws Exception {
    final DBCollection collection = db.getCollection(mongoCollection);
    if (collection.find().count() >= minSizeIfExists) {
        System.out.printf("The readCollection %s already contains 100 items, skip adding test data.%n",
                mongoCollection);/* w w w . j a v  a  2 s .c  om*/
        return;
    }

    InputStream inputStream = MongoItemReaderTest.class.getClassLoader().getResourceAsStream(dataResource);
    if (inputStream == null) {
        try {
            final URL url = new URI(dataResource).toURL();
            inputStream = url.openStream();
        } catch (final Exception e) {
            System.out.printf("Failed to convert dataResource %s to URL: %s%n", dataResource, e);
        }
    }
    if (inputStream == null) {
        throw new IllegalStateException("The inputStream for the test data is null");
    }

    final JsonFactory jsonFactory = new MappingJsonFactory();
    final JsonParser parser = jsonFactory.createParser(inputStream);
    final JsonNode arrayNode = parser.readValueAs(ArrayNode.class);

    final Iterator<JsonNode> elements = arrayNode.elements();
    final List<DBObject> dbObjects = new ArrayList<DBObject>();
    while (elements.hasNext()) {
        final DBObject dbObject = (DBObject) JSON.parse(elements.next().toString());
        dbObjects.add(dbObject);
    }
    collection.insert(dbObjects);
}

From source file:de.dakror.scpuller.SCPuller.java

public static String getFileContents(URL u) throws IOException {
    String res = "", line = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream()));
    while ((line = br.readLine()) != null) {
        res += line;//from ww w  . j  a v  a2  s  . c o m
    }
    br.close();
    return res;
}