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:net.rim.ejde.internal.util.RIAUtils.java

public static void initDLLs() {
    IPath dllStoreLocation = ContextManager.PLUGIN.getStateLocation().append("installDlls"); //$NON-NLS-1$
    File dllStoreFile = dllStoreLocation.toFile();

    if (!dllStoreFile.exists())
        dllStoreFile.mkdir();//w  w w  . j  av  a 2  s. co m

    InputStream inputStream;
    OutputStream outputStream;
    File dllFile;
    byte[] buf;
    int numbytes;
    URL bundUrl;

    for (String dllFileName : dllNames) {
        inputStream = null;
        outputStream = null;

        try {
            dllFile = dllStoreLocation.append(dllFileName).toFile();
            Bundle bundle = ContextManager.PLUGIN.getBundle();
            if (!dllFile.exists() || bundle.getLastModified() > dllFile.lastModified()) {
                bundUrl = bundle.getResource(dllFileName);

                if (bundUrl == null)
                    continue;

                inputStream = bundUrl.openStream();
                outputStream = new FileOutputStream(dllFile);
                buf = new byte[4096];
                numbytes = 0;

                while ((numbytes = inputStream.read(buf)) > 0)
                    outputStream.write(buf, 0, numbytes);
            }
        } catch (IOException t) {
            _log.error(t.getMessage(), t);
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();

                if (outputStream != null)
                    outputStream.close();
            } catch (IOException t) {
                _log.error(t.getMessage(), t);
            }
        }
    } // end for
}

From source file:com.log4ic.compressor.utils.HttpUtils.java

/**
 * //from  ww  w .jav a 2 s  .c  om
 *
 * @param httpUrl
 * @return
 * @throws java.io.IOException
 */
public static String requestFile(String httpUrl) {
    URL url = null;
    try {
        url = new URL(httpUrl);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    if (url == null) {
        return null;
    }
    InputStream in = null;
    InputStreamReader streamReader = null;
    BufferedReader reader = null;
    try {
        in = url.openStream();
        streamReader = new InputStreamReader(in);
        reader = new BufferedReader(streamReader);
        String lineCode;
        StringBuilder pageCodeBuffer = new StringBuilder();
        while ((lineCode = reader.readLine()) != null) {
            pageCodeBuffer.append(lineCode);
            pageCodeBuffer.append("\n");
        }

        return pageCodeBuffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (streamReader != null) {
            try {
                streamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }//from   w  w  w.ja  va  2 s .  com
    System.out.println("Initializing key store");
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java

/** Looks up the long definition text from the/ECGOntology at Bioportal for the specfied tree node ID.
 * //from w  w w .  j a va  2 s .  co m
 * @param treeNodeID - the id to look up, as supplied by the OntologyTree popup.
 * @return - long definition text
 */

public static String annotationXMLLookup(String restURL) {
    String definition = "WARNING TEST FILLER From BrokerServiceImpl.java";
    String label = "TEST LABEL";
    String sReturn = "";

    URL url;
    try {
        url = new URL(restURL);

        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputLine;
        boolean isDescriptionFollowing = false;
        StringBuffer buff = null;

        while ((inputLine = in.readLine()) != null) {

            String regex = "^\\s+<label>\\w+</label>$";
            boolean bLabel = inputLine.matches(regex);
            if (bLabel) {
                label = inputLine.trim();
            }

            if (isDescriptionFollowing) { // <label>
                if (inputLine.length() != 0) {
                    if (inputLine.indexOf("</definitions>") > -1) {
                        isDescriptionFollowing = false;
                        break;
                    } else {
                        buff.append(inputLine);
                    }
                }
            } else {
                if (inputLine.indexOf("<definitions>") > -1) {
                    isDescriptionFollowing = true;
                    buff = new StringBuffer();
                }
            }
        }
        in.close();

        if (buff.length() > 0) {
            definition = buff.substring(0);
            definition = definition.replace("/n", "");
            definition = definition.replace("<string>", "");
            definition = definition.replace("</string>", "");
            definition = definition.trim();
        } else {
            definition = "Detailed definition not available.";
        }
        sReturn = label + definition;

    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return sReturn;
}

From source file:com.intel.cryptostream.utils.NativeCodeLoader.java

/**
 * Get the cryptostream version by reading pom.properties embedded in jar.
 * This version data is used as a suffix of a dll file extracted from the
 * jar.//from   www .  java 2s  . c o m
 * 
 * @return the version string
 */
public static String getVersion() {
    URL versionFile = NativeCodeLoader.class
            .getResource("/META-INF/maven/com.intel.cryptostream/cryptostream/pom.properties");
    if (versionFile == null)
        versionFile = NativeCodeLoader.class.getResource("/com/intel/cryptostream/VERSION");

    String version = "unknown";
    try {
        if (versionFile != null) {
            Properties versionData = new Properties();
            versionData.load(versionFile.openStream());
            version = versionData.getProperty("version", version);
            if (version.equals("unknown"))
                version = versionData.getProperty("VERSION", version);
            version = version.trim().replaceAll("[^0-9M\\.]", "");
        }
    } catch (IOException e) {
        System.err.println(e);
    }
    return version;
}

From source file:de.tbuchloh.kiskis.KisKis.java

/**
 * a hack for Java Web Start. The dictionary is delivered in a Jar and needs to be unpacked into the directory.
 *///w ww . j a  v a  2s .c  o m
private static void installCracklibDict() {
    final File dir = new File(Settings.getCracklibDict());
    if (!Dictionary.exists(dir.getName())) {
        final File absoluteDir = new File(System.getProperty("java.io.tmpdir"), "kiskis-dictionary");
        LOG.info("The dictionary " + dir + " does not exist. Creating tmp dictionary dir="
                + absoluteDir.getAbsolutePath());
        absoluteDir.mkdirs();

        // we need to install the dictionary
        final String[] resources = { "cracklib.pwi", "cracklib.hwm", "cracklib.pwd" };
        try {
            for (final String s : resources) {
                final String resourceName = "/" + s;
                final URL url = KisKis.class.getResource(resourceName);
                if (url == null) {
                    throw new KisKisException("The resource name " + resourceName + " does not exist!");
                }

                LOG.info("Getting url=" + url);

                final File target = new File(absoluteDir, s);
                try {
                    FileProcessor.copyStream(url.openStream(), new FileOutputStream(target));
                    LOG.info("File " + target + " created.");
                } catch (final IOException e) {
                    throw new KisKisException("Could not copy " + url + " to " + target, e);
                }
            }

            Settings.setCracklibDict(absoluteDir.getAbsolutePath());
        } catch (final KisKisException e) {
            LOG.error("Could not install dictionary in file system", e);
        }
    } else {
        LOG.info("The dictionary does already exist. Skipping ...");
    }
}

From source file:com.intel.chimera.utils.NativeCodeLoader.java

/**
 * Gets the version by reading pom.properties embedded in jar.
 * This version data is used as a suffix of a dll file extracted from the
 * jar./*from  w w  w .ja  v a2  s.c om*/
 * 
 * @return the version string
 */
public static String getVersion() {
    URL versionFile = NativeCodeLoader.class
            .getResource("/META-INF/maven/com.intel.chimera/chimera/pom.properties");
    if (versionFile == null)
        versionFile = NativeCodeLoader.class.getResource("/com/intel/chimera/VERSION");

    String version = "unknown";
    try {
        if (versionFile != null) {
            Properties versionData = new Properties();
            versionData.load(versionFile.openStream());
            version = versionData.getProperty("version", version);
            if (version.equals("unknown"))
                version = versionData.getProperty("VERSION", version);
            version = version.trim().replaceAll("[^0-9M\\.]", "");
        }
    } catch (IOException e) {
        System.err.println(e);
    }
    return version;
}

From source file:eu.medsea.mimeutil.detector.MagicMimeMimeDetector.java

private static void initMagicRules() {
    InputStream in = null;//  w  w  w . j  a  va  2 s .  com

    // Try to locate a magic.mime file locate by system property magic-mime
    try {
        String fname = System.getProperty("magic-mime");
        if (fname != null && fname.length() != 0) {
            in = new FileInputStream(fname);
            if (in != null) {
                parse("-Dmagic-mime=" + fname, new InputStreamReader(in));
            }
        }
    } catch (Exception e) {
        log.error("Failed to parse custom magic mime file defined by system property -Dmagic-mime ["
                + System.getProperty("magic-mime") + "]. File will be ignored.", e);
    } finally {
        in = closeStream(in);
    }

    // Try to locate a magic.mime file(s) on the classpath

    // Get an enumeration of all files on the classpath with this name. They could be in jar files as well
    try {
        Enumeration en = MimeUtil.class.getClassLoader().getResources("magic.mime");
        while (en.hasMoreElements()) {
            URL url = (URL) en.nextElement();
            in = url.openStream();
            if (in != null) {
                try {
                    parse("classpath:[" + url + "]", new InputStreamReader(in));
                } catch (Exception ex) {
                    log.error("Failed to parse magic.mime rule file [" + url
                            + "] on the classpath. File will be ignored.", ex);
                }
            }

        }
    } catch (Exception e) {
        log.error("Problem while processing magic.mime files from classpath. Files will be ignored.", e);
    } finally {
        in = closeStream(in);
    }

    // Now lets see if we have one in the users home directory. This is
    // named .magic.mime as opposed to magic.mime
    try {
        File f = new File(System.getProperty("user.home") + File.separator + ".magic.mime");
        if (f.exists()) {
            in = new FileInputStream(f);
            if (in != null) {
                try {
                    parse(f.getAbsolutePath(), new InputStreamReader(in));
                } catch (Exception ex) {
                    log.error(
                            "Failed to parse .magic.mime file from the users home directory. File will be ignored.",
                            ex);
                }
            }
        }
    } catch (Exception e) {
        log.error(
                "Problem while processing .magic.mime file from the users home directory. File will be ignored.",
                e);
    } finally {
        in = closeStream(in);
    }

    // Now lets see if we have an environment variable named MAGIC set. This
    // would normally point to a magic or magic.mgc file.
    // As we don't use these file types we will look to see if there is also
    // a magic.mime file at this location for us to use.
    try {
        String name = System.getProperty("MAGIC");
        if (name != null && name.length() != 0) {
            // Strip the .mgc from the end if it's there and add the .mime
            // extension
            if (name.indexOf('.') < 0) {
                name = name + ".mime";
            } else {
                // remove the mgc extension
                name = name.substring(0, name.indexOf('.') - 1) + "mime";
            }
            File f = new File(name);
            if (f.exists()) {
                in = new FileInputStream(f);
                if (in != null) {
                    try {
                        parse(f.getAbsolutePath(), new InputStreamReader(in));
                    } catch (Exception ex) {
                        log.error(
                                "Failed to parse magic.mime file from directory located by environment variable MAGIC. File will be ignored.",
                                ex);
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error(
                "Problem while processing magic.mime file from directory located by environment variable MAGIC. File will be ignored.",
                e);
    } finally {
        in = closeStream(in);
    }

    // Parse the UNIX magic(5) magic.mime files. Since there can be
    // multiple, we have to load all of them.
    // We save, how many entries we have now, in order to fall back to our
    // default magic.mime that we ship,
    // if no entries were read from the OS.

    int mMagicMimeEntriesSizeBeforeReadingOS = mMagicMimeEntries.size();
    Iterator it = magicMimeFileLocations.iterator();
    while (it.hasNext()) {
        parseMagicMimeFileLocation((String) it.next());
    }

    if (mMagicMimeEntriesSizeBeforeReadingOS == mMagicMimeEntries.size()) {
        // Use the magic.mime that we ship
        try {
            String resource = "eu/medsea/mimeutil/magic.mime";
            in = MimeUtil.class.getClassLoader().getResourceAsStream(resource);
            if (in != null) {
                try {
                    parse("resource:" + resource, new InputStreamReader(in));
                } catch (Exception ex) {
                    log.error("Failed to parse internal magic.mime file.", ex);
                }
            }
        } catch (Exception e) {
            log.error("Problem while processing internal magic.mime file.", e);
        } finally {
            in = closeStream(in);
        }
    }
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * /*from ww w. ja  v a2  s .  c om*/
 * @param property
 * @param defaultValue
 * @return
 * @throws PropertyFileLoadException
 */
public static void setProperty(String propertyName, String propertyValue) throws CaCISWebException {

    URL propsUrl = CaCISUtil.class.getClassLoader().getResource(CaCISWebConstants.COM_PROPERTIES_FILE_NAME);
    File propertiesFile = new File(propsUrl.getPath());

    if (properties == null || propertiesFile.lastModified() > lastModified) {
        properties = new Properties();

        try {
            properties.load(propsUrl.openStream());
            properties.setProperty(propertyName, propertyValue);
            FileOutputStream fileOutputStream = new FileOutputStream(new File(propsUrl.getPath()));
            properties.store(fileOutputStream, "Updated Property: " + propertyName);
        } catch (FileNotFoundException ex) {
            throw new CaCISWebException(
                    String.format("The properties file %s does not exist or is not readable|writable",
                            propertiesFile.getAbsolutePath()),
                    ex);
        } catch (IOException ex) {
            throw new CaCISWebException(String.format(
                    "An error was encountered while attempting to read|write the properties file %s",
                    propertiesFile.getAbsolutePath()), ex);
        }
    }
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * //from   ww  w .j  a  va2  s. c o m
 * @param property
 * @param defaultValue
 * @return
 * @throws PropertyFileLoadException
 */
public static String getProperty(String property, String defaultValue) throws CaCISWebException {

    URL propsUrl = CaCISUtil.class.getClassLoader().getResource(CaCISWebConstants.COM_PROPERTIES_FILE_NAME);
    File propertiesFile = new File(propsUrl.getPath());

    if (properties == null || propertiesFile.lastModified() > lastModified) {
        properties = new Properties();

        try {
            properties.load(propsUrl.openStream());
        } catch (FileNotFoundException ex) {
            throw new CaCISWebException(
                    String.format("The properties file %s does not exist or is not readable",
                            propertiesFile.getAbsolutePath()),
                    ex);
        } catch (IOException ex) {
            throw new CaCISWebException(
                    String.format("An error was encountered while attempting to read the properties file %s",
                            propertiesFile.getAbsolutePath()),
                    ex);
        }
    }

    log.debug(property + " = " + properties.getProperty(property, defaultValue));

    return properties.getProperty(property, defaultValue);
}