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:ru.emdev.ldap.util.EmDevSchemaLdifExtractor.java

/**
 * Gets the DBFILE resource from within a jar off the base path.  If another jar
 * with such a DBFILE resource exists then an error will result since the resource
 * is not unique across all the jars./*from  w ww .  j av a  2s .c  o m*/
 *
 * @param resourceName the file name of the resource to load
 * @param resourceDescription human description of the resource
 * @return the InputStream to read the contents of the resource
 * @throws IOException if there are problems reading or finding a unique copy of the resource
 */
public static InputStream getUniqueResourceAsStream(String resourceName, String resourceDescription)
        throws IOException {
    resourceName = BASE_PATH + resourceName;
    URL result = getUniqueResource(resourceName, resourceDescription);
    return result.openStream();
}

From source file:com.tuplejump.stargate.cassandra.CassandraUtils.java

static URL getStorageConfigURL() throws ConfigurationException {
    String configUrl = System.getProperty("cassandra.config");
    if (configUrl == null)
        configUrl = DEFAULT_CONFIGURATION;

    URL url;
    try {// www.  j av  a 2  s .c om
        url = new URL(configUrl);
        url.openStream().close(); // catches well-formed but bogus URLs
    } catch (Exception e) {
        ClassLoader loader = DatabaseDescriptor.class.getClassLoader();
        url = loader.getResource(configUrl);
        if (url == null)
            throw new ConfigurationException("Cannot locate " + configUrl);
    }

    return url;
}

From source file:Main.java

public static void writeUrlToFileNIO(String urlToRead, String folderToWrite, String fileName)
        throws MalformedURLException, IOException {
    URL urlIn = new URL(urlToRead);
    File folderOut = Paths.get(folderToWrite).toFile();
    if (!(folderOut.exists() || folderOut.mkdirs())) {
        throw new RuntimeException("could not create folder " + folderToWrite);
    }/*from   w w w  . j a  v a  2s. c  om*/
    Path pathOut = Paths.get(folderToWrite, fileName);
    try (ReadableByteChannel in = Channels.newChannel(new BufferedInputStream(urlIn.openStream()));
            WritableByteChannel out = Files.newByteChannel(pathOut, CREATE, WRITE);) {
        transfer(in, out);
    }
}

From source file:net.dian1.player.download.DownloadTask.java

private static void downloadCover(DownloadJob job) {

    PlaylistEntry mPlaylistEntry = job.getPlaylistEntry();
    String mDestination = job.getDestination();
    String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination);
    File file = new File(path + "/" + "cover.jpg");
    // check if cover already exists
    if (file.exists()) {
        Log.v(Dian1Application.TAG, "File exists - nothing to do");
        return;/*from ww  w.j  a  v  a2s  .  com*/
    }

    String albumUrl = mPlaylistEntry.getAlbum().getImage();
    if (albumUrl == null) {
        Log.w(Dian1Application.TAG, "album Url = null. This should not happened");
        return;
    }
    albumUrl = albumUrl.replace("1.100", "1.500");

    InputStream stream = null;
    URL imageUrl;
    Bitmap bmp = null;

    // download cover
    try {
        imageUrl = new URL(albumUrl);

        try {
            stream = imageUrl.openStream();
            bmp = BitmapFactory.decodeStream(stream);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.v(Dian1Application.TAG, "download Cover IOException");
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        Log.v(Dian1Application.TAG, "download CoverMalformedURLException");
        e.printStackTrace();
    }

    // save cover to album directory
    if (bmp != null) {

        try {
            file.createNewFile();
            OutputStream outStream = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();

            Log.v(Dian1Application.TAG, "Album cover saved to sd");

        } catch (FileNotFoundException e) {
            Log.w(Dian1Application.TAG, "FileNotFoundException");

        } catch (IOException e) {
            Log.w(Dian1Application.TAG, "IOException");
        }

    }
}

From source file:com.aurel.track.dbase.JobScheduler.java

/**
 * @param application//from   w w  w  .j  a  v  a 2  s  .c om
 * @param torqueConfig
 * 
 * This will instantiate and configure a Quartz scheduler. Database related
 * configuration items are taken from the Torque configuration such as not
 * to duplicate JDBC URLs, database type, user, and password entries.
 * Some properties can be configured in file /WEB-INF/Quartz.properties,
 * for example configuration parameters for clustering.
 * 
 */
public static void init(ServletContext application, PropertiesConfiguration torqueConfig) {

    Properties qcfg = null;
    servletContext = application;
    try {
        URL quartzURL = application.getResource("/WEB-INF/Quartz.properties");
        qcfg = new Properties();
        InputStream in = quartzURL.openStream();
        qcfg.load(in);
        in.close();
    } catch (Exception e) {
        LOGGER.error("Getting the Quartz.properties failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (qcfg == null) {
        LOGGER.error("qcfg is null");
        return;
    }
    quartzProperties = qcfg;
}

From source file:net.roboconf.agent.internal.misc.UserDataUtils.java

/**
 * Configures the agent from VMWare./*from w  w w . jav  a 2  s  .c  o  m*/
 * @param logger a logger
 * @return the agent's data, or null if they could not be parsed
 */
public static AgentProperties findParametersForVmware(Logger logger) {

    File propertiesFile = new File("/tmp/roboconf.properties");
    try {
        int retries = 30;
        while ((!propertiesFile.exists() || !propertiesFile.canRead()) && retries-- > 0) {
            logger.fine("Agent tries to read properties file " + propertiesFile + ": trial #" + (30 - retries));
            try {
                Thread.sleep(2000);

            } catch (InterruptedException e) {
                throw new IOException("Can't read properties file: " + e);
            }
        }

        AgentProperties result = AgentProperties.readIaasProperties(Utils.readPropertiesFile(propertiesFile));

        /*
         * HACK for specific IaaS configurations (using properties file in a VMWare-like manner)
         * Try to pick IP address... in the case we are on OpenStack or any IaaS with amazon-compatible API
         * Some configurations (with floating IPs) do not provide network interfaces exposing public IPs !
         */
        InputStream in = null;
        try {
            URL userDataUrl = new URL("http://169.254.169.254/latest/meta-data/public-ipv4");
            in = userDataUrl.openStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            Utils.copyStreamSafely(in, os);
            String ip = os.toString("UTF-8");
            if (!AgentUtils.isValidIP(ip)) {
                // Failed retrieving public IP: try private one instead
                Utils.closeQuietly(in);
                userDataUrl = new URL("http://169.254.169.254/latest/meta-data/local-ipv4");
                in = userDataUrl.openStream();
                os = new ByteArrayOutputStream();

                Utils.copyStreamSafely(in, os);
                ip = os.toString("UTF-8");
            }

            if (AgentUtils.isValidIP(ip))
                result.setIpAddress(os.toString("UTF-8"));

        } catch (IOException e) {
            Utils.logException(logger, e);
        } finally {
            Utils.closeQuietly(in);
        }
        /* HACK ends here (see comment above). Removing it is harmless on classical VMWare configurations. */

        return result;

    } catch (IOException e) {
        logger.fine("Agent failed to read properties file " + propertiesFile);
        return null;
    }
}

From source file:org.dataconservancy.dcs.integration.main.ContainerStartIT.java

@BeforeClass
public static void loadProperties() throws IOException {
    final URL defaultProps = ContainerStartIT.class.getResource("/default.properties");
    assertNotNull("Could not resolve /default.properties from the classpath.", defaultProps);
    assertTrue("default.properties does not exist.", new File(defaultProps.getPath()).exists());
    props.load(defaultProps.openStream());
}

From source file:com.t3.persistence.FileUtil.java

public static byte[] getBytes(URL url) throws IOException {
    try (InputStream is = url.openStream()) {
        return getBytes(is);
    }/*w ww. j  a  va 2  s.c  om*/
}

From source file:io.fabric8.camel.tooling.util.CamelNamespaces.java

private static void loadSchemas(SchemaFinder loader) throws SAXException, IOException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    XsdDetails[] xsds = new XsdDetails[] {
            new XsdDetails("camel-spring.xsd", "http://camel.apache.org/schema/spring/camel-spring.xsd",
                    CamelEndpointFactoryBean.class),
            new XsdDetails("camel-blueprint.xsd",
                    "http://camel.apache.org/schema/blueprint/camel-blueprint.xsd",
                    org.apache.camel.blueprint.CamelEndpointFactoryBean.class) };

    List<Source> sources = new ArrayList<Source>(xsds.length);

    for (XsdDetails xsdd : xsds) {
        URL url = loader.findSchema(xsdd);
        if (url != null) {
            sources.add(new StreamSource(url.openStream(), xsdd.getUri()));
        } else {/*  ww  w.  j av a2 s.  c  om*/
            System.out.println("Warning could not find local resource " + xsdd.getPath() + " on classpath");
            sources.add(new StreamSource(xsdd.getUri()));
        }
    }

    _schema = factory.newSchema(sources.toArray(new Source[sources.size()]));
}

From source file:io.apiman.servers.gateway_h2.Starter.java

/**
 * Loads properties from a file and puts them into system properties.
 *///from   w w  w.j a v  a2  s .  co  m
@SuppressWarnings({ "unchecked" })
protected static void loadProperties() {
    URL configUrl = Starter.class.getClassLoader().getResource("gateway_h2-apiman.properties");
    if (configUrl == null) {
        throw new RuntimeException(
                "Failed to find properties file (see README.md): gateway_h2-apiman.properties");
    }
    InputStream is = null;
    try {
        is = configUrl.openStream();
        Properties props = new Properties();
        props.load(is);
        Enumeration<String> names = (Enumeration<String>) props.propertyNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = props.getProperty(name);
            System.setProperty(name, value);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}