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.stacksync.desktop.util.FileUtil.java

public static String getPropertyFromManifest(String manifestPath, String property) {
    try {/*from  w w  w. j av a 2  s  . co m*/
        URLClassLoader cl = (URLClassLoader) FileUtil.class.getClassLoader();

        URL url = cl.findResource(manifestPath);
        Manifest manifest = new Manifest(url.openStream());
        Attributes attr = manifest.getMainAttributes();

        return attr.getValue(property);
    } catch (IOException ex) {
        logger.debug("Exception: ", ex);
        return null;
    }
}

From source file:com.netflix.client.ssl.URLSslContextFactory.java

/**
 * Opens the specified key or trust store using the given password.
 *
 * In case of failure {@link com.netflix.client.ssl.ClientSslSocketFactoryException} is thrown, and wrapps the
 * underlying cause exception. That could be:
 * <ul>/*from  w w w  . ja v  a2  s. c o m*/
 *     <li>KeyStoreException if the JRE doesn't support the standard Java Keystore format, in other words: never</li>
 *     <li>NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found</li>
 *     <li>CertificateException if any of the certificates in the keystore could not be loaded</li>
 *     <li>
 *         IOException if there is an I/O or format problem with the keystore data, if a
 *         password is required but not given, or if the given password was incorrect. If the
 *         error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException.
 *     </li>
 * </ul>
 *
 * @param storeFile the location of the store to load
 * @param password the password protecting the store
 * @return the newly loaded key store
 * @throws ClientSslSocketFactoryException a wrapper exception for any problems encountered during keystore creation.
 */
private static KeyStore createKeyStore(final URL storeFile, final String password)
        throws ClientSslSocketFactoryException {

    if (storeFile == null) {
        return null;
    }

    Preconditions.checkArgument(StringUtils.isNotEmpty(password),
            "Null keystore should have empty password, defined keystore must have password");

    KeyStore keyStore = null;

    try {
        keyStore = KeyStore.getInstance("jks");

        InputStream is = storeFile.openStream();

        try {
            keyStore.load(is, password.toCharArray());
        } catch (NoSuchAlgorithmException e) {
            throw new ClientSslSocketFactoryException(
                    String.format("Failed to create a keystore that supports algorithm %s: %s",
                            SOCKET_ALGORITHM, e.getMessage()),
                    e);
        } catch (CertificateException e) {
            throw new ClientSslSocketFactoryException(String.format(
                    "Failed to create keystore with algorithm %s due to certificate exception: %s",
                    SOCKET_ALGORITHM, e.getMessage()), e);
        } finally {
            try {
                is.close();
            } catch (IOException ignore) { // NOPMD                
            }
        }
    } catch (KeyStoreException e) {
        throw new ClientSslSocketFactoryException(
                String.format("KeyStore exception creating keystore: %s", e.getMessage()), e);
    } catch (IOException e) {
        throw new ClientSslSocketFactoryException(
                String.format("IO exception creating keystore: %s", e.getMessage()), e);
    }

    return keyStore;
}

From source file:webtest.Test1.java

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {//from   w  w  w.  j  av a 2  s .  co m
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1) {
            buffer.append(chars, 0, read);
        }

        return buffer.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.mobile.natal.natalchart.NetworkUtilities.java

/**
 * Read url to string./*w w  w . j  a  v  a2  s.co m*/
 *
 * @param urlString the url.
 * @return the fetched text.
 * @throws Exception if something goes wrong.
 */
public static String readUrl(String urlString) throws Exception {
    URL url = new URL(urlString);
    InputStream inputStream = url.openStream();
    BufferedReader bi = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = bi.readLine()) != null) {
        sb.append(line).append("\n");
    }
    inputStream.close();
    return sb.toString().trim();
}

From source file:org.glowroot.tests.WebDriverSetup.java

private static void downloadAndExtractGeckoDriver(File directory, String downloadFilenameSuffix,
        String downloadFilenameExt, String optionalExt, Archiver archiver) throws IOException {
    // using System.out to make sure user sees why there is a delay here
    System.out.print("Downloading Mozilla geckodriver " + GECKO_DRIVER_VERSION + "...");
    URL url = new URL("https://github.com/mozilla/geckodriver/releases/download/v" + GECKO_DRIVER_VERSION
            + "/geckodriver-v" + GECKO_DRIVER_VERSION + '-' + downloadFilenameSuffix + '.'
            + downloadFilenameExt);/*  w  w  w . ja va2 s  . c  o  m*/
    InputStream in = url.openStream();
    File archiveFile = File.createTempFile("geckodriver-" + GECKO_DRIVER_VERSION + '-',
            '.' + downloadFilenameExt);
    Files.asByteSink(archiveFile).writeFrom(in);
    in.close();
    archiver.extract(archiveFile, directory);
    Files.move(new File(directory, "geckodriver" + optionalExt),
            new File(directory, "geckodriver-" + GECKO_DRIVER_VERSION + optionalExt));
    archiveFile.delete();
    System.out.println(" OK");
}

From source file:com.aurel.track.admin.customize.lists.BlobBL.java

/**
 * Download the icon if exists. If there is no icon set then the default
 * blank icon will be rendered//from ww w .  ja va2s. c om
 * 
 * @param iconKey
 * @param iconName
 * @param request
 * @param reponse
 * @param inline
 */
public static void download(Integer iconKey, String iconName, HttpServletRequest request,
        HttpServletResponse reponse, boolean inline, String defaultIconPath) {
    byte[] imageContent = null;
    if (iconKey != null) {
        TBLOBBean blobBean = loadByPrimaryKey(iconKey);
        if (blobBean != null) {
            imageContent = blobBean.getBLOBValue();
        }
    }
    if (defaultIconPath != null) {
        if (imageContent == null || imageContent.length == 0) {
            try {
                URL defaultIconURL = ApplicationBean.getInstance().getServletContext()
                        .getResource(defaultIconPath);
                if (defaultIconURL != null) {
                    imageContent = IOUtils.toByteArray(defaultIconURL.openStream());
                }
            } catch (IOException e) {
                LOGGER.info("Getting the icon content for " + defaultIconPath + " from URL failed with "
                        + e.getMessage());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
        if (imageContent == null || imageContent.length == 0) {
            InputStream is = ApplicationBean.getInstance().getServletContext()
                    .getResourceAsStream(defaultIconPath);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                byte[] buf = new byte[1024];
                int numBytesRead;
                while ((numBytesRead = is.read(buf)) != -1) {
                    output.write(buf, 0, numBytesRead);
                }
                imageContent = output.toByteArray();
                output.close();
                is.close();
            } catch (IOException e) {
                LOGGER.info("Getting the icon content for " + defaultIconPath
                        + " as resource stream failed with " + e.getMessage());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    }
    if (imageContent != null) {
        download(imageContent, request, reponse, iconName, inline);
    }
}

From source file:menusearch.json.JSONProcessor.java

/**
 * /*  ww w.j av a2  s .  c  om*/
 * @param searchID is the ID of the recipe you would like to search for 
 * @return a string containing one recipe in JSON format.
 * @throws IOException 
 * 
 * This method creates a formated URL that then connects to Yummly and returns a JSON string for the recipeID provided.
 * 
 * RecipeID can be obtained only by doing a general search through yummly.
 */
public static String getRecipeAPI(String searchID) throws IOException {
    BufferedReader reader = null;
    try {
        URL url = new URL("http://api.yummly.com/v1/api/recipe/" + searchID
                + "?_app_id=95a21eb2&_app_key=d703fa9e11ee34f104bc271ec3bbcdb9");
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

From source file:com.krawler.portal.tools.SourceFormatter.java

private static void _readExclusions() throws IOException {
    _exclusions = new Properties();

    ClassLoader classLoader = SourceFormatter.class.getClassLoader();

    String sourceFormatterExclusions = System.getProperty("source-formatter-exclusions",
            "com/liferay/portal/tools/dependencies/" + "source_formatter_exclusions.properties");

    URL url = classLoader.getResource(sourceFormatterExclusions);

    if (url == null) {
        return;/*  w w  w.  j a  v  a 2  s .co  m*/
    }

    InputStream is = url.openStream();

    _exclusions.load(is);

    is.close();
}

From source file:org.kurento.test.grid.GridHandler.java

public static String readContents(String address) throws IOException {
    StringBuilder contents = new StringBuilder(2048);
    BufferedReader br = null;//from w  w  w.  ja v  a2 s  . c o  m
    try {
        URL url = new URL(address);
        br = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = "";
        while (line != null) {
            line = br.readLine();
            contents.append(line);
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }
    return contents.toString();
}

From source file:info.evanchik.eclipse.karaf.core.KarafCorePluginUtils.java

/**
 * Loads a properties file as a resource from the specified {@link Bundle}
 *
 * @param theBundle/*from w  ww.  ja  va  2s. co m*/
 *            the {@link Bundle} to use as the source of the properties file
 * @param propertiesFile
 *            the path, relative to the root of the bundle, to the
 *            properties file
 * @return a {@link Properties} object or null if there was an error
 */
public static Properties loadProperties(final Bundle theBundle, final String propertiesFile) {
    final Properties properties = new Properties();

    final URL entryUrl = theBundle.getEntry(propertiesFile);

    if (entryUrl == null) {
        return null;
    }

    try {
        final InputStream in = entryUrl.openStream();

        properties.load(in);

        in.close();

        return properties;
    } catch (final IOException e) {
        e.printStackTrace();
    }

    return null;
}