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:io.stallion.utils.ResourceHelpers.java

public static byte[] loadBinaryResource(URL resourceUrl, String pluginName) {

    try {/*from  w w  w.ja v  a2s. c o m*/
        File file = urlToFileMaybe(resourceUrl, pluginName);
        if (file == null) {
            return IOUtils.toByteArray(resourceUrl.openStream());
        } else {
            return FileUtils.readAllBytes(file);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dataconservancy.dcs.integration.main.LineageIT.java

/**
 * Loads properties to set up the test, deposit a DU to establish a lineage, and retrieve the deposited DU.
 *
 * @throws IOException//from   w  w w.jav a 2s  . c om
 * @throws InterruptedException
 * @throws InvalidXmlException
 */
@BeforeClass
public static void loadProperties() throws IOException, InterruptedException, InvalidXmlException {
    // Load properties
    final URL defaultProps = LineageIT.class.getResource("/default.properties");
    assertNotNull("Could not resolve /default.properties from the classpath.", defaultProps);
    assertTrue("default.properties does not exist.", new File(defaultProps.getPath()).exists());
    props.load(defaultProps.openStream());
    baseUrl = interpolate(new StringBuilder("${dcs.baseurl}/"), 0, props).toString();
    lineageUrl = baseUrl + "lineage";

    // Establish a lineage by depositing a single object
    Dcp toDeposit = new Dcp();
    DcsDeliverableUnit du = new DcsDeliverableUnit();
    du.setId(duId);
    du.setTitle("Deliverable Unit Title");
    toDeposit.addEntity(du);

    // Perform the deposit
    DepositBuilder depositBuilder = depositClient.buildDeposit(toDeposit);
    String id = depositBuilder.execute();
    Thread.sleep(10000);
    DepositInfo info = depositClient.getDepositInfo(id);
    assertTrue(info.hasCompleted());
    assertTrue(info.isSuccessful());

    // Get the minted DCS id from the deposit feed, and retrieve the
    // deposited DU
    dcsDuId = getDcsIdFromDepositedId(duId, info);
    assertNotNull("Unable to determine deposited entity id", dcsDuId);
    DcsDeliverableUnit depositedDu = (DcsDeliverableUnit) getEntity(dcsDuId);
    assertNotNull(depositedDu);
    assertNotNull(depositedDu.getLineageId());
    lineageId = depositedDu.getLineageId();
}

From source file:net.erdfelt.android.sdkfido.project.FilteredFileUtil.java

public static void copyWithExpansion(String resourceId, File destFile, Map<String, String> props) {
    URL url = FilteredFileUtil.class.getResource(resourceId);
    if (url == null) {
        LOG.log(Level.WARNING, "Unable to find resourceID: " + resourceId);
        return;/*from   w ww . java  2 s. c o m*/
    }

    InputStream in = null;
    InputStreamReader reader = null;
    BufferedReader buf = null;
    FileWriter writer = null;
    PrintWriter out = null;
    try {
        in = url.openStream();
        reader = new InputStreamReader(in);
        buf = new BufferedReader(reader);
        writer = new FileWriter(destFile);
        out = new PrintWriter(writer);

        PropertyExpander expander = new PropertyExpander(props);
        String line;

        while ((line = buf.readLine()) != null) {
            out.println(expander.expand(line));
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Unable to open input stream for url: " + url, e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(buf);
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(in);
    }
}

From source file:net.erdfelt.android.sdkfido.project.FilteredFileUtil.java

public static String loadExpandedAsString(String resourceId, Map<String, String> props)
        throws OutputProjectException {
    LOG.log(Level.INFO, "Loading resource: " + resourceId);
    if (StringUtils.isBlank(resourceId)) {
        throw new IllegalArgumentException("resourceId cannot be blank");
    }//from   w w w.j a va  2s .com
    URL url = FilteredFileUtil.class.getResource(resourceId);
    if (url == null) {
        throw new OutputProjectException("Unable to find resourceID: " + resourceId);
    }

    InputStream in = null;
    InputStreamReader reader = null;
    BufferedReader buf = null;
    StringWriter writer = null;
    PrintWriter out = null;
    try {
        in = url.openStream();
        reader = new InputStreamReader(in);
        buf = new BufferedReader(reader);
        writer = new StringWriter();
        out = new PrintWriter(writer);

        PropertyExpander expander = new PropertyExpander(props);
        String line;

        while ((line = buf.readLine()) != null) {
            out.println(expander.expand(line));
        }

        out.flush();
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new OutputProjectException("Unable to open input stream for url: " + url, e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(buf);
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(in);
    }
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * /*from  ww w .j av a  2  s .  com*/
 * @param latitude
 * @param longitude
 * @return 
 */
public static HashMap reverse(double latitude, double longitude) {
    HashMap a = new HashMap();
    try {
        //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude));            
        URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng="
                + String.valueOf(latitude) + "," + String.valueOf(longitude));
        URL file_url = new URL(
                url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery()));
        //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream()));
        BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream()));
        String textJson = "", tempJs;
        while ((tempJs = lector.readLine()) != null)
            textJson += tempJs;
        if (textJson == null)
            throw new Exception("Don't found item");
        JSONObject google = ((JSONObject) JSONValue.parse(textJson));
        a.put("status", google.get("status").toString());
        if (a.get("status").toString().equals("OK")) {
            JSONArray results = (JSONArray) google.get("results");
            JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components");
            for (int i = 0; i < address_components.size(); i++) {
                JSONObject items = (JSONObject) address_components.get(i);
                //if(((JSONObject)types.get(0)).get("").toString().equals("country"))
                if (items.get("types").toString().contains("country")) {
                    a.put("country", items.get("long_name").toString());
                    a.put("iso", items.get("short_name").toString());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        a = null;
        System.out.println("Error Google Geocoding: " + ex);
    }
    return a;
}

From source file:com.openteach.diamond.container.Container.java

@SuppressWarnings("unchecked")
private static void initLifecycleListeners() {
    try {/*w w  w.  ja va  2 s .c  om*/
        Enumeration<URL> cUrls = Container.class.getClassLoader().getResources(DIAMOND_LIFECYCLE_FILE);
        while (cUrls.hasMoreElements()) {
            URL url = cUrls.nextElement();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(url.openStream()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    try {
                        Class clazz = Container.class.getClassLoader().loadClass(line.trim());
                        if (LifecycleListener.class.isAssignableFrom(clazz)) {
                            lifecycleListeners.add((LifecycleListener) clazz.newInstance());
                        }
                    } catch (ClassNotFoundException e) {
                        System.err.println("?" + line);
                        e.printStackTrace();
                    }
                    //?
                    break;
                }
            } catch (IOException e) {
                logger.error(e);
            } finally {
                if (null != br) {
                    br.close();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("?diamond!  " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

public static String getUrlContents(String urlString) throws IOException {
    URL url = new URL(urlString);
    if (url == null)
        return null;
    BufferedReader in = null;//from   ww w  . j av a 2 s  .c o m
    try {
        in = new BufferedReader(new InputStreamReader(url.openStream()));

        StringBuilder urlContents = new StringBuilder();
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            urlContents.append(inputLine);
            urlContents.append(NewLine);
            if (urlContents.length() >= READ_THRESHOLD) {
                throw new IOException("Size of the contents at the given url [" + url
                        + "] exceeds threshold of [" + READ_THRESHOLD + "]");
            }
        }
        return urlContents.toString();
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:de.uni_koeln.spinfo.maalr.sigar.SigarWrapper.java

private static void initialize() {
    logger.info("Initializing...");
    String libBase = "/hyperic-sigar-1.6.5/sigar-bin/lib/";
    try {/*from w ww. j a va2 s  . c o m*/
        String prefix = "libsigar";
        if (SystemUtils.IS_OS_WINDOWS) {
            prefix = "sigar";
        }
        String arch = getSystemArch();
        String suffix = getSystemSuffix();
        String resourceName = prefix + "-" + arch + "-" + suffix;

        logger.info("Native library: " + resourceName);

        String resource = libBase + resourceName;
        URL toLoad = SigarWrapper.class.getResource(resource);
        File home = new File(System.getProperty("user.home"));
        File libs = new File(home, ".maalr/libs/sigar");
        libs.mkdirs();
        File tmp = new File(libs, resourceName);
        tmp.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(tmp);
        InputStream in = toLoad.openStream();
        int i;
        while ((i = in.read()) != -1) {
            fos.write(i);
        }
        in.close();
        fos.close();
        logger.info("Library copied to " + tmp.getAbsolutePath());
        String oldPath = System.getProperty("java.library.path");
        System.setProperty("java.library.path", oldPath + SystemUtils.PATH_SEPARATOR + libs.getAbsolutePath());
        logger.info("java.library.path updated: " + System.getProperty("java.library.path"));
        executors = Executors.newScheduledThreadPool(1, new ThreadFactory() {

            public Thread newThread(Runnable r) {
                Thread t = new Thread(r);
                t.setDaemon(true);
                return t;
            }
        });
        logger.info("Initialization completed.");
    } catch (Exception e) {
        logger.error("Failed to initialize!", e);
    }
}

From source file:com.limegroup.gnutella.gui.iTunesMediator.java

private static void createiTunesJavaScript(String scriptName) {
    File fileJS = new File(CommonUtils.getUserSettingsDir(), scriptName);
    if (fileJS.exists()) {
        return;/* www . ja  va2s. co m*/
    }

    URL url = ResourceManager.getURLResource(scriptName);

    InputStream is = null;
    OutputStream out = null;

    try {
        if (url != null) {
            is = new BufferedInputStream(url.openStream());
            out = new FileOutputStream(fileJS);
            IOUtils.copy(is, out);
        }
    } catch (IOException e) {
        LOG.error("Error creating iTunes javascript", e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.mapviewer.business.NetCDFRequestManager.java

/**
 * This functions makes a URL request to one ncWMS server to retrieve the
 * valid times one layer has for an specific day.
 *
 * @param {Layer}layer/*from  w  w  w .  j a  va2s .  c o m*/
 * @param {String}day
 * @return
 */
public static String getLayerTimeSteps(Layer layer, String day) {

    URL ncReq;
    String urlRequest = buildRequest(layer, "GetMetadata", "timesteps");
    urlRequest += "&day=" + day;

    JSONObject timeSteps = new JSONObject();

    try {
        ncReq = new URL(urlRequest);
        ncReq.openConnection();
        InputStreamReader input = new InputStreamReader(ncReq.openStream());
        BufferedReader in = new BufferedReader(input);
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            if (!inputLine.trim().equalsIgnoreCase("")) {// TODO check for errros
                timeSteps = new JSONObject(inputLine);

                //               datesWithData = (JSONObject) layerDetails.get("datesWithData");
                /*
                 * //Iterating over the years for(Enumeration years =
                 * dates.keys(); years.hasMoreElements();){ String year =
                 * (String) years.nextElement(); JSONObject yearJson =
                 * dates.getJSONObject(year); for(Enumeration months =
                 * yearJson.keys(); months.hasMoreElements();){ String month
                 * = (String) months.nextElement(); int x = 1; } }
                 */
            }
        }

    } catch (JSONException | IOException e) {
        System.out.println("Error MapViewer en RedirectServer en generateRedirect" + e.getMessage());
        return "Error getting the layerDetials:" + e.getMessage();
    }
    return timeSteps.toString();
}