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.nesscomputing.httpclient.internal.HttpClientTrustManagerFactory.java

@Nonnull
private static KeyStore loadKeystore(@Nonnull String location, @Nonnull String keystoreType,
        @Nonnull String keystorePassword) throws GeneralSecurityException, IOException {
    final KeyStore keystore = KeyStore.getInstance(keystoreType);
    URL keystoreUrl;
    if (StringUtils.startsWithIgnoreCase(location, "classpath:")) {
        keystoreUrl = Resources.getResource(HttpClientTrustManagerFactory.class, location.substring(10));
    } else {//from w w  w . j a  v a  2  s .c  o  m
        keystoreUrl = new URL(location);
    }
    keystore.load(keystoreUrl.openStream(), keystorePassword.toCharArray());
    return keystore;
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFUtil.java

/**
 * Check if an ODF package is self-contained, i.e. content files don't have
 * OLE objects linked to external files//w  w w  .j a  v a  2s .c o m
 * 
 * @param odfUrl
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static boolean isSelfContained(URL odfUrl)
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    InputStream odfInputStream = odfUrl.openStream();
    List zipEntries = getZipEntriesAsList(odfInputStream);

    odfInputStream = odfUrl.openStream();
    ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
    ZipEntry zipEntry;

    XPathFactory factory = XPathFactory.newInstance();
    /* Maybe a bit overkill, but implementations can use other prefixes */
    ODFNamespaceContext namespaceContext = new ODFNamespaceContext();

    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expression = xpath.compile("//draw:object/@xlink:href|" + "//draw:object-ole/@xlink:href|"
            + "//draw:image/@xlink:href|" + "//draw:floating-frame/@xlink:href");

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (isContentFile(zipEntry)) {
            /* TODO: pure SAX is probably more memory-efficient */
            Document content = ODFUtil.loadDocument(odfZipInputStream);
            NodeList nodes = (NodeList) expression.evaluate(content, XPathConstants.NODESET);
            return checkNodes(nodes, zipEntries);
        }
    }
    return true;
}

From source file:com.cedarsoft.serialization.neo4j.test.utils.AbstractNeo4jSerializerTest2.java

@Nonnull
public static <T> Entry<? extends T> create(@Nonnull T object, @Nullable URL expected) {
    if (expected == null) {
        throw new IllegalStateException("No resource found for <" + object + ">");
    }/* w w w  .  j av a  2 s  . co m*/

    try {
        return new Entry<T>(object, IOUtils.toByteArray(expected.openStream()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:uk.dsxt.voting.common.utils.PropertiesHelper.java

public static String getResourceString(String name, String encoding) {
    if (name == null || name.isEmpty())
        return "";
    try {//from  w ww.  ja  v a 2  s . c o  m
        final File resourceFile = getConfFile(name);
        if (resourceFile.exists()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(resourceFile.getPath()));
                log.debug("getResourceString. Resource ({}) found: {}", name, resourceFile.getAbsolutePath());
                return new String(encoded, Charset.forName(encoding));
            } catch (IOException e) {
                log.warn("getResourceString. Couldn't read resource from file: {}. error={}",
                        resourceFile.getAbsolutePath(), e.getMessage());
            }
        }

        log.info("getResourceString. Loading resource from jar: {}", name);
        final URL resource = getResource(name);
        if (resource == null) {
            log.warn("getResourceString. Couldn't load resource from jar file: {}.", name);
            return "";
        }
        return IOUtils.toString(resource.openStream(), Charset.forName(encoding));
    } catch (Exception e) {
        log.error("getResourceString. Couldn't read a resource file.", e);
    }
    return "";
}

From source file:gate.corpora.twitter.Population.java

/**
 * /*  w w  w  .jav  a  2  s . c  om*/
 * @param corpus
 * @param inputUrl
 * @param encoding
 * @param contentKeys
 * @param featureKeys
 * @param tweetsPerDoc 0 = put them all in one document; otherwise the number per document
 * @throws ResourceInstantiationException
 */
public static void populateCorpus(final Corpus corpus, URL inputUrl, String encoding, List<String> contentKeys,
        List<String> featureKeys, int tweetsPerDoc) throws ResourceInstantiationException {
    try {
        InputStream input = inputUrl.openStream();
        List<String> lines = IOUtils.readLines(input, encoding);
        IOUtils.closeQuietly(input);

        // TODO: sort this out so it processes one at a time instead of reading the
        // whole hog into memory

        // For now, we assume the streaming API format (concatenated maps, not in a list)
        List<Tweet> tweets = TweetUtils.readTweetStrings(lines, contentKeys, featureKeys);

        int digits = (int) Math.ceil(Math.log10(tweets.size()));
        int tweetCounter = 0;
        Document document = newDocument(inputUrl, tweetCounter, digits);
        StringBuilder content = new StringBuilder();
        Map<PreAnnotation, Integer> annotandaOffsets = new HashMap<PreAnnotation, Integer>();

        for (Tweet tweet : tweets) {
            if ((tweetsPerDoc > 0) && (tweetCounter > 0) && ((tweetCounter % tweetsPerDoc) == 0)) {
                closeDocument(document, content, annotandaOffsets, corpus);
                document = newDocument(inputUrl, tweetCounter, digits);
                content = new StringBuilder();
                annotandaOffsets = new HashMap<PreAnnotation, Integer>();
            }

            int startOffset = content.length();
            content.append(tweet.getString());
            for (PreAnnotation preAnn : tweet.getAnnotations()) {
                annotandaOffsets.put(preAnn, startOffset);
            }

            content.append('\n');
            tweetCounter++;
        } // end of Tweet loop

        if (content.length() > 0) {
            closeDocument(document, content, annotandaOffsets, corpus);
        } else {
            Factory.deleteResource(document);
        }

        if (corpus.getDataStore() != null) {
            corpus.getDataStore().sync(corpus);
        }

    } catch (Exception e) {
        throw new ResourceInstantiationException(e);
    }
}

From source file:pl.lewica.util.FileUtil.java

public static boolean fetchAndSaveImage(String sourceUrl, String destinationPath, boolean overwrite)
        throws IOException {
    File destinationFile = new File(destinationPath);
    if (destinationFile.exists() && !overwrite) {
        return false;
    }/*from  w ww.  j av  a  2  s.co m*/

    BufferedInputStream bis = null;
    FileOutputStream fos = null;

    try {
        URL url = new URL(sourceUrl);
        // See http://stackoverflow.com/questions/3498643/dalvik-message-default-buffer-size-used-in-bufferedinputstream-constructor-it/7516554#7516554
        int bufferSize = 8192;
        bis = new BufferedInputStream(url.openStream(), bufferSize);
        ByteArrayBuffer bab = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            bab.append((byte) current);
        }

        fos = new FileOutputStream(destinationFile);
        fos.write(bab.toByteArray());
        fos.close();
    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close file output stream for " + sourceUrl);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close buffered input stream for " + sourceUrl);
            }
        }
    }

    return true;
}

From source file:com.hortonworks.amstore.view.AmbariStoreHelper.java

public static void downloadFile(String url, String localFilePath) {

    try {/*  w  w  w .j  av a 2  s . c  o  m*/
        URL website = new URL(url);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        // unix specific
        FileOutputStream fos = new FileOutputStream(localFilePath);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
    } catch (java.net.MalformedURLException e) {
    } catch (java.io.FileNotFoundException e) {
    } catch (java.io.IOException e) {
    }
}

From source file:com.turt2live.hurtle.uuid.UUIDServiceProvider.java

/**
 * Gets the known username history of a UUID. All dates are in UTC.
 * This returns a map of player names and when they were last seen (the
 * approximate date they stopped using that name).
 *
 * @param uuid the uuid to lookup, cannot be null
 *
 * @return a map of names and dates (UTC), or an empty map for invalid input or unknown/non-existent history
 *//*from   w w w .ja v a  2 s.  c  om*/
public static Map<String, Date> getHistory(UUID uuid) {
    if (uuid == null)
        return new HashMap<>();
    try {
        URL url = new URL("http://uuid.turt2live.com/history/" + uuid.toString().replaceAll("-", ""));
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
        String parsed = "";
        String line;
        while ((line = reader.readLine()) != null)
            parsed += line;
        reader.close();

        Map<String, Date> map = new HashMap<>();
        Object o = JSONValue.parse(parsed);
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            Object namesObj = jsonObject.get("names");
            if (namesObj instanceof JSONArray) {
                JSONArray names = (JSONArray) namesObj;
                for (Object name : names) {
                    o = name;
                    if (o instanceof JSONObject) {
                        JSONObject json = (JSONObject) o;

                        Object nameObj = json.get("name");
                        Object dateObj = json.get("last-seen");
                        if (nameObj instanceof String && dateObj instanceof String) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                            format.setTimeZone(TimeZone.getTimeZone("UTC"));
                            try {
                                Date date = format.parse((String) dateObj);
                                map.put((String) nameObj, date);
                            } catch (ParseException e) {
                                System.out.println("Could not parse " + dateObj + ": " + e.getMessage());
                            }
                        }
                    }
                }
            }
        }
        return map;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}

From source file:com.teleca.jamendo.util.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(JamendoApplication.TAG, "File exists - nothing to do");
        return;//from  ww w.  j  av a  2  s  .  c om
    }

    String albumUrl = mPlaylistEntry.getAlbum().getImage();
    if (albumUrl == null) {
        Log.w(JamendoApplication.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(JamendoApplication.TAG, "download Cover IOException");
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        Log.v(JamendoApplication.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(JamendoApplication.TAG, "Album cover saved to sd");

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

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

    }
}

From source file:com.atlassw.tools.eclipse.checkstyle.builder.PackageNamesLoader.java

/**
 * Returns the default list of package names.
 * /*from  www . j ava2s.  co  m*/
 * @param aClassLoader the class loader that gets the default package names.
 * @return the default list of package names.
 * @throws CheckstylePluginException if an error occurs.
 */
public static List<String> getPackageNames(ClassLoader aClassLoader) throws CheckstylePluginException {

    if (sPackages == null) {
        sPackages = new ArrayList<String>();

        PackageNamesLoader nameLoader = null;

        try {
            nameLoader = new PackageNamesLoader();
            final InputStream stream = aClassLoader.getResourceAsStream(DEFAULT_PACKAGES);
            InputSource source = new InputSource(stream);
            nameLoader.parseInputSource(source);
        } catch (ParserConfigurationException e) {
            CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES); //$NON-NLS-1$
        } catch (SAXException e) {
            CheckstylePluginException.rethrow(e, "unable to parse " + DEFAULT_PACKAGES + " - " //$NON-NLS-1$ //$NON-NLS-2$
                    + e.getMessage());
        } catch (IOException e) {
            CheckstylePluginException.rethrow(e, "unable to read " + DEFAULT_PACKAGES); //$NON-NLS-1$
        }

        // load custom package files
        try {
            Enumeration<URL> packageFiles = aClassLoader.getResources("checkstyle_packages.xml"); //$NON-NLS-1$

            while (packageFiles.hasMoreElements()) {

                URL aPackageFile = packageFiles.nextElement();
                InputStream iStream = null;

                try {

                    iStream = new BufferedInputStream(aPackageFile.openStream());
                    InputSource source = new InputSource(iStream);
                    nameLoader.parseInputSource(source);
                } catch (SAXException e) {
                    LimyEclipsePluginUtils.log(e);
                    //                        CheckstyleLog.log(e, "unable to parse " + aPackageFile.toExternalForm() //$NON-NLS-1$
                    //                                + " - " + e.getLocalizedMessage()); //$NON-NLS-1$
                } catch (IOException e) {
                    LimyEclipsePluginUtils.log(e);
                    //                        CheckstyleLog.log(e, "unable to read " + aPackageFile.toExternalForm()); //$NON-NLS-1$
                } finally {
                    IOUtils.closeQuietly(iStream);
                }
            }
        } catch (IOException e1) {
            CheckstylePluginException.rethrow(e1);
        }
    }

    return sPackages;
}