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.erdfelt.android.sdkfido.Build.java

public static String getVersion() {
    if (version == null) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        String resource = String.format("META-INF/maven/%s/%s/pom.properties", GROUP_ID, ARTIFACT_ID);
        URL url = cl.getResource(resource);
        if (url == null) {
            version = "[DEV]";
        } else {//from www.  j  av a  2s  .c  o  m
            InputStream in = null;
            try {
                in = url.openStream();
                Properties props = new Properties();
                props.load(in);
                version = props.getProperty("version");
            } catch (IOException e) {
                LOG.log(Level.WARNING, "Unable to read: " + url, e);
                version = "[UNKNOWN]";
            } finally {
                IOUtils.closeQuietly(in);
            }
        }
    }
    return version;
}

From source file:net.lyonlancer5.mcmp.karasu.util.ModFileUtils.java

static long download(String url, File output) throws IOException {
    URL url1 = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(url1.openStream());
    FileOutputStream fos = new FileOutputStream(output);

    if (!output.exists()) {
        output.getParentFile().mkdirs();
        output.createNewFile();/*from   ww  w.  j a v  a2s . c  om*/
    }

    long f = fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
    fos.close();
    return f;
}

From source file:br.net.fabiozumbi12.RedProtect.hooks.MojangUUIDs.java

public static String getName(String UUID) {
    try {/*from  w  w  w  .  j  a v  a  2s. co  m*/
        URL url = new URL("https://api.mojang.com/user/profiles/" + UUID.replaceAll("-", "") + "/names");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String line = in.readLine();
        if (line == null) {
            return null;
        }
        JSONArray array = (JSONArray) new JSONParser().parse(line);
        HashMap<Long, String> names = new HashMap<Long, String>();
        String name = "";
        for (Object profile : array) {
            JSONObject jsonProfile = (JSONObject) profile;
            if (jsonProfile.containsKey("changedToAt")) {
                names.put((long) jsonProfile.get("changedToAt"), (String) jsonProfile.get("name"));
                continue;
            }
            name = (String) jsonProfile.get("name");
        }
        if (!names.isEmpty()) {
            Long key = Collections.max(names.keySet());
            return names.get(key);
        } else {
            return name;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:Main.java

/**
 * Parse a XML file and return the resulting DOM tree.
 *//*from  w  w w.  j a  va  2s .c  om*/
public static Document readXml(URL xmlUrl) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = newNamespaceAwareFactory();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputStream input = xmlUrl.openStream();
    try {
        return builder.parse(input);
    } finally {
        input.close();
    }
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

/**
 * Opens a URL. It can be a simple URL or one which requires basic
 * authentication.//w  w w .  j  a  v  a  2s. c  o  m
 * <p/>
 * Tries to access the given URL. If http response is either
 * {@code HttpStatus.SC_UNAUTHORIZED} or
 * {@code HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED}, asks for
 * login/password and tries to authenticate into proxy server and/or URL.
 * <p/>
 * This implementation relies on the Apache Http Client due to its
 * capabilities of proxy/http authentication. <br/>
 * Proxy configuration is determined by {@link ProxySelectorRoutePlanner} using the JVM proxy
 * settings by default.
 * <p/>
 * For more information see: <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/} <br/>
 * - {@code http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/conn/ProxySelectorRoutePlanner.html}
 * <p/>
 * There's a very simple <b>cache</b> implementation.
 * Login/Password for each realm are stored in a static {@link Map}.
 * Before asking the user the method verifies if the information is already available in cache.
 *
 * @param url the URL string to be opened.
 * @param monitor {@link ITaskMonitor} which is related to this URL
 *            fetching.
 * @return Returns an {@link InputStream} holding the URL content.
 * @throws IOException Exception thrown when there are problems retrieving
 *             the URL or its content.
 * @throws CanceledByUserException Exception thrown if the user cancels the
 *              authentication dialog.
 */
static InputStream openUrl(String url, ITaskMonitor monitor) throws IOException, CanceledByUserException {

    try {
        return openWithHttpClient(url, monitor);

    } catch (ClientProtocolException e) {
        // If the protocol is not supported by HttpClient (e.g. file:///),
        // revert to the standard java.net.Url.open

        URL u = new URL(url);
        return u.openStream();
    }
}

From source file:com.alibaba.jstorm.utils.LoadConf.java

public static InputStream getConfigFileInputStream(String configFilePath, boolean canMultiple)
        throws IOException {
    if (null == configFilePath) {
        throw new IOException("Could not find config file, name not specified");
    }//w w w . ja  v a  2 s. c o  m

    HashSet<URL> resources = new HashSet<>(findResources(configFilePath));
    if (resources.isEmpty()) {
        File configFile = new File(configFilePath);
        if (configFile.exists()) {
            return new FileInputStream(configFile);
        }
    } else if (resources.size() > 1 && !canMultiple) {
        throw new IOException("Found multiple " + configFilePath + " resources. "
                + "You're probably bundling storm jars with your topology jar. " + resources);
    } else {
        LOG.debug("Using " + configFilePath + " from resources");
        URL resource = resources.iterator().next();
        return resource.openStream();
    }
    return null;
}

From source file:cn.org.once.cstack.utils.TestUtils.java

/**
 * Download from github binaries and deploy file.
 *
 * @param path//  www  .j a  va 2 s  . c o m
 * @return
 * @throws IOException
 */
public static MockMultipartFile downloadAndPrepareFileToDeploy(String remoteFile, String path)
        throws IOException {
    URL url;
    File file = new File(remoteFile);
    try (OutputStream outputStream = new FileOutputStream(file)) {
        url = new URL(path);
        InputStream input = url.openStream();

        int read;
        byte[] bytes = new byte[1024];

        while ((read = input.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
    } catch (IOException e) {
        StringBuilder msgError = new StringBuilder(512);
        msgError.append(remoteFile);
        msgError.append(",");
        msgError.append(path);
        logger.debug(msgError.toString(), e);
    }
    return new MockMultipartFile("file", file.getName(), "multipart/form-data", new FileInputStream(file));

}

From source file:BitLottoVerify.java

public static Map<String, Long> getPaymentsBlockExplorer(String addr) throws Exception {
    URL u = new URL("http://blockexplorer.com/address/" + addr);
    Scanner scan = new Scanner(u.openStream());

    TreeMap<String, Long> map = new TreeMap<String, Long>();

    while (scan.hasNextLine()) {
        String line = scan.nextLine();
        StringTokenizer stok = new StringTokenizer(line, "\"#");
        while (stok.hasMoreTokens()) {
            String token = stok.nextToken();
            if (token.startsWith("/tx/")) {
                String tx = token.substring(4);
                line = scan.nextLine();/* w  w  w. j  a  va  2 s .  c o  m*/
                line = scan.nextLine();
                StringTokenizer stok2 = new StringTokenizer(line, "<>");
                stok2.nextToken();
                double amt = Double.parseDouble(stok2.nextToken());
                long amt_l = (long) Math.round(amt * 1e8);
                map.put(tx, amt_l);

            }
        }
    }
    return map;
}

From source file:com.autentia.tnt.xml.UtilitiesXML.java

/**
 * Este metodo busca un fichero de tipo XML en el classpath crea un objeto 
 * de tipo org.w3c.dom.Document.//from w  ww .j  ava 2 s . com
 * @param fichero: El nombre del fichero a procesar.
 * @return
 * @throws Exception
 */
public static Document file2Document(String fichero) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL urlfichero = loader.getResource(fichero);
    Document XMLDoc = factory.newDocumentBuilder().parse(new InputSource(urlfichero.openStream()));
    return XMLDoc;
}

From source file:com.cloud.utils.PropertiesUtil.java

public static InputStream openStreamFromURL(String path) {
    ClassLoader cl = PropertiesUtil.class.getClassLoader();
    URL url = cl.getResource(path);
    if (url != null) {
        try {//from w ww  .j  a  v  a2  s.  c om
            InputStream stream = url.openStream();
            return stream;
        } catch (IOException ioex) {
            return null;
        }
    }
    return null;
}