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.fizzed.blaze.internal.DependencyHelper.java

static public List<Dependency> alreadyBundled() {
    String resourceName = "/com/fizzed/blaze/bundled.txt";

    URL url = DependencyHelper.class.getResource(resourceName);

    if (url == null) {
        throw new BlazeException(
                "Unable to find resource " + resourceName + ". Maybe not packaged as jar correctly?");
    }//from   w w w  . jav a 2 s .c o  m

    List<Dependency> dependencies = new ArrayList<>();

    try (InputStream is = url.openStream()) {
        List<String> lines = IOUtils.readLines(is, "UTF-8");
        for (String line : lines) {
            line = line.trim();
            if (!line.equals("")) {
                if (line.contains("following files have been resolved")) {
                    // skip
                } else {
                    String d = cleanMavenDependencyLine(line);
                    dependencies.add(Dependency.parse(d));
                }
            }
        }
    } catch (IOException e) {
        throw new BlazeException("Unable to detect bundled dependencies", e);
    }

    return dependencies;
}

From source file:org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil.java

private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (null == keystoreFile) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }// w ww .j  av a2  s .  co  m
    URI keystoreUri = keystoreFile.toURI();
    URL keystoreUrl = keystoreUri.toURL();
    KeyStore keystore = KeyStore.getInstance(keyStoreType);
    InputStream is = null;
    try {
        is = keystoreUrl.openStream();
        keystore.load(is, null == password ? null : password.toCharArray());
    } finally {
        if (null != is) {
            is.close();
        }
    }
    return keystore;
}

From source file:io.apiman.manager.api.jdbc.JdbcMetricsAccessorTest.java

/**
 * Initialize the DB with the apiman gateway DDL.
 * @param connection/*from  ww  w  . j  a  v  a2  s.c om*/
 */
private static void initDB(Connection connection) throws Exception {
    ClassLoader cl = JdbcMetricsAccessorTest.class.getClassLoader();
    URL resource = cl.getResource("ddls/apiman-gateway_h2.ddl");
    try (InputStream is = resource.openStream()) {
        System.out.println("=======================================");
        System.out.println("Initializing database.");
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements) {
            System.out.println(sql);
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.execute();
        }
        System.out.println("=======================================");
    }

    System.out.println("--------------------------------------");
    System.out.println("Adding test data to the database.");
    resource = cl.getResource("JdbcMetricsAccessorTest/bulk-data.ddl");
    try (InputStream is = resource.openStream()) {
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements) {
            System.out.println(sql);
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.execute();
        }
    }
    System.out.println("--------------------------------------");
}

From source file:net.oauth.example.provider.core.SampleOAuthProvider.java

public static synchronized void loadConsumers(ServletConfig config) throws IOException {
    Properties p = consumerProperties;
    if (p == null) {
        p = new Properties();
        String resourceName = "/" + SampleOAuthProvider.class.getPackage().getName().replace(".", "/")
                + "/provider.properties";
        URL resource = SampleOAuthProvider.class.getClassLoader().getResource(resourceName);
        if (resource == null) {
            throw new IOException("resource not found: " + resourceName);
        }/*w ww  .  j  a v  a  2s.c  o  m*/
        InputStream stream = resource.openStream();
        try {
            p.load(stream);
        } finally {
            stream.close();
        }
    }
    consumerProperties = p;

    // for each entry in the properties file create a OAuthConsumer
    for (Map.Entry prop : p.entrySet()) {
        String consumer_key = (String) prop.getKey();
        // make sure it's key not additional properties
        if (!consumer_key.contains(".")) {
            String consumer_secret = (String) prop.getValue();
            if (consumer_secret != null) {
                String consumer_description = (String) p.getProperty(consumer_key + ".description");
                String consumer_callback_url = (String) p.getProperty(consumer_key + ".callbackURL");
                // Create OAuthConsumer w/ key and secret
                OAuthConsumer consumer = new OAuthConsumer(consumer_callback_url, consumer_key, consumer_secret,
                        null);
                consumer.setProperty("name", consumer_key);
                consumer.setProperty("description", consumer_description);
                ALL_CONSUMERS.put(consumer_key, consumer);
            }
        }
    }

}

From source file:fll.xml.XMLUtils.java

/**
 * Get all challenge descriptors build into the software.
 *///w w w.  ja v  a2s.  c o m
public static Collection<URL> getAllKnownChallengeDescriptorURLs() {
    final String baseDir = "fll/resources/challenge-descriptors/";

    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final URL directory = classLoader.getResource(baseDir);
    if (null == directory) {
        LOGGER.warn("base dir for challenge descriptors not found");
        return Collections.emptyList();
    }

    final Collection<URL> urls = new LinkedList<URL>();
    if ("file".equals(directory.getProtocol())) {
        try {
            final URI uri = directory.toURI();
            final File fileDir = new File(uri);
            final File[] files = fileDir.listFiles();
            if (null != files) {
                for (final File file : files) {
                    if (file.getName().endsWith(".xml")) {
                        try {
                            final URL fileUrl = file.toURI().toURL();
                            urls.add(fileUrl);
                        } catch (final MalformedURLException e) {
                            LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e);
                        }
                    }
                }
            }
        } catch (final URISyntaxException e) {
            LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e);
        }
    } else if (directory.getProtocol().equals("jar")) {
        final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource();
        if (null != src) {
            final URL jar = src.getLocation();

            JarInputStream zip = null;
            try {
                zip = new JarInputStream(jar.openStream());

                JarEntry ze = null;
                while ((ze = zip.getNextJarEntry()) != null) {
                    final String entryName = ze.getName();
                    if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) {
                        // add 1 to baseDir to skip past the path separator
                        final String challengeName = entryName.substring(baseDir.length());

                        // check that the file really exists and turn it into a URL
                        final URL challengeUrl = classLoader.getResource(baseDir + challengeName);
                        if (null != challengeUrl) {
                            urls.add(challengeUrl);
                        } else {
                            // TODO could write the resource out to a temporary file if
                            // needed
                            // then mark the file as delete on exit
                            LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: "
                                    + entryName);
                        }
                    }
                }

                zip.close();
            } catch (final IOException e) {
                LOGGER.error("Error reading jar file at: " + jar.toString(), e);
            } finally {
                IOUtils.closeQuietly(zip);
            }

        } else {
            LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors");
        }
    } else {
        throw new UnsupportedOperationException("Cannot list files for URL " + directory);

    }

    return urls;

}

From source file:io.jenkins.blueocean.config.JenkinsJSExtensions.java

private synchronized static void refreshCache(List<PluginWrapper> latestPlugins) {
    if (!latestPlugins.equals(pluginCache)) {
        pluginCache.clear();/*w  w w.j av  a 2 s.com*/
        pluginCache.addAll(latestPlugins);
        refreshCache(pluginCache);
    }
    for (PluginWrapper pluginWrapper : pluginCache) {
        //skip if not active
        if (!pluginWrapper.isActive()) {
            continue;
        }
        //skip probing plugin if already read
        if (jsExtensionCache.get(pluginWrapper.getLongName()) != null) {
            continue;
        }
        try {
            Enumeration<URL> dataResources = pluginWrapper.classLoader
                    .getResources("jenkins-js-extension.json");
            boolean hasDefinedExtensions = false;

            while (dataResources.hasMoreElements()) {
                URL dataRes = dataResources.nextElement();

                LOGGER.debug("Reading 'jenkins-js-extension.json' from '{}'.", dataRes);

                try (InputStream dataResStream = dataRes.openStream()) {
                    Map<String, Object> extensionData = mapper.readValue(dataResStream, Map.class);

                    String pluginId = getGav(extensionData);
                    if (pluginId != null) {
                        // Skip if the plugin name specified on the extension data does not match the name
                        // on the PluginWrapper for this iteration. This can happen for e.g. aggregator
                        // plugins, in which case you'll be seeing extension resources on it's dependencies.
                        // We can skip these here because we will process those plugins themselves in a
                        // future/past iteration of this loop.
                        if (!pluginId.equals(pluginWrapper.getShortName())) {
                            continue;
                        }
                    } else {
                        LOGGER.error(String.format("Plugin %s JS extension has missing hpiPluginId",
                                pluginWrapper.getLongName()));
                        continue;
                    }

                    List<Map> extensions = (List<Map>) extensionData.get(PLUGIN_EXT);
                    if (extensions != null) {
                        for (Map extension : extensions) {
                            try {
                                String type = (String) extension.get("type");
                                if (type != null) {
                                    BlueExtensionClassContainer extensionClassContainer = Jenkins.getInstance()
                                            .getExtensionList(BlueExtensionClassContainer.class).get(0);
                                    Map classInfo = (Map) mergeObjects(extensionClassContainer.get(type));
                                    List classInfoClasses = (List) classInfo.get("_classes");
                                    classInfoClasses.add(0, type);
                                    extension.put("_class", type);
                                    extension.put("_classes", classInfoClasses);
                                }
                            } catch (Exception e) {
                                LOGGER.error(
                                        "An error occurred when attempting to read type information from jenkins-js-extension.json from: "
                                                + dataRes,
                                        e);
                            }
                        }
                    }

                    extensionData.put(PLUGIN_VER, pluginWrapper.getVersion());
                    jsExtensionCache.put(pluginId, mergeObjects(extensionData));
                    hasDefinedExtensions = true;
                }
            }

            if (!hasDefinedExtensions) {
                // Manufacture an entry for all plugins that do not have any defined
                // extensions. This adds some info about the plugin that the UI might
                // need access to e.g. the plugin version.
                Map<String, Object> extensionData = new LinkedHashMap<>();
                extensionData.put(PLUGIN_ID, pluginWrapper.getShortName());
                extensionData.put(PLUGIN_VER, pluginWrapper.getVersion());
                extensionData.put(PLUGIN_EXT, Collections.emptyList());
                jsExtensionCache.put(pluginWrapper.getShortName(), mergeObjects(extensionData));
            }
        } catch (IOException e) {
            LOGGER.error(String.format("Error locating jenkins-js-extension.json for plugin %s",
                    pluginWrapper.getLongName()));
        }
    }
}

From source file:DiskIO.java

/**
 * General use columba resource InputStream getter.
 * /*from   w  ww. ja v  a2  s  .  c o m*/
 * @param path
 *            the full path and filename of the resource requested. If
 *            <code>path</code> begins with "#" it is resolved against the
 *            program's standard resource folder after removing "#"
 * @return an InputStream to read the resource data, or <b>null </b> if the
 *         resource could not be obtained
 * @throws java.io.IOException
 *             if there was an error opening the input stream
 */
public static InputStream getResourceStream(String path) throws java.io.IOException {
    URL url;

    if ((url = getResourceURL(path)) == null) {
        return null;
    }
    return url.openStream();
}

From source file:net.jmhertlein.alphonseirc.MSTDeskEngRunner.java

private static int fetchMaxXKCD() {
    URL xkcdURL;
    try {//w  ww  .j av a 2s.  c  o  m
        xkcdURL = new URL(XKCD_URL);
    } catch (MalformedURLException ex) {
        Logger.getLogger(AlphonseBot.class.getName()).log(Level.SEVERE, null, ex);
        return 0;
    }

    JSONObject json;
    try (Scanner scan = new Scanner(xkcdURL.openStream())) {
        scan.useDelimiter("\\A");
        json = new JSONObject(scan.next());
    } catch (IOException ex) {
        Logger.getLogger(AlphonseBot.class.getName()).log(Level.SEVERE, null, ex);
        return 0;
    }

    return json.getInt("num");
}

From source file:eu.betaas.taas.taasvmmanager.configuration.TaaSVMMAnagerConfiguration.java

private static void downloadBaseImages() {
    URL website;
    ReadableByteChannel rbc;/* w w w  .  j a  v a 2 s.  co  m*/
    FileOutputStream fos;
    logger.info("Downloading default VM images.");
    try {
        website = new URL(baseImagesURL);
        rbc = Channels.newChannel(website.openStream());
        fos = new FileOutputStream(baseImagesPath);
        logger.info("Downloading base image from " + baseImagesURL);
        //new DownloadUpdater(baseComputeImageX86Path, baseImagesURL).start();
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    } catch (MalformedURLException e) {
        logger.error("Error downloading images: bad URL.");
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error("Error downloading images: IO exception.");
        logger.error(e.getMessage());
    }
    logger.info("Completed!");
}

From source file:io.apiman.gateway.test.junit.servlet.ServletGatewayTestServer.java

/**
 * Loads the config file.// w ww  .  j  av a 2 s. c  o m
 * @param configFile
 */
private static Properties loadConfigFile(String configFile) {
    // Try loading as a URL first.
    try {
        URL url = new URL(configFile);
        try (InputStream is = url.openStream()) {
            Properties props = new Properties();
            props.load(is);
            return props;
        }
    } catch (IOException e) {
        // Move on to the next type.
        System.out.println("Tried to load config file as a URL but failed: " + configFile);
    }

    // Now try loading as a resource.
    ClassLoader cl = ServletGatewayTestServer.class.getClassLoader();
    URL resource = cl.getResource(configFile);
    if (resource == null) {
        resource = cl.getResource("test-configs/" + configFile);
    }
    try {
        try (InputStream is = resource.openStream()) {
            Properties props = new Properties();
            props.load(is);
            return props;
        }
    } catch (Exception e) {
        // Move on to the next type.
        System.out.println("Tried to load config file as a resource but failed: " + configFile);
    }

    throw new RuntimeException("Failed to load referenced config: " + configFile);
}