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.offbynull.coroutines.instrumenter.testhelpers.TestUtils.java

/**
 * Loads up a ZIP file that's contained in the classpath.
 * @param path path of ZIP resource/*from  w ww .j a v a 2  s .  c om*/
 * @return contents of files within the ZIP
 * @throws IOException if any IO error occurs
 * @throws NullPointerException if any argument is {@code null} or contains {@code null} elements
 * @throws IllegalArgumentException if {@code path} cannot be found, or if zipPaths contains duplicates
 */
public static Map<String, byte[]> readZipFromResource(String path) throws IOException {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL url = cl.getResource(path);
    Validate.isTrue(url != null);

    Map<String, byte[]> ret = new LinkedHashMap<>();

    try (InputStream is = url.openStream(); ZipArchiveInputStream zais = new ZipArchiveInputStream(is)) {
        ZipArchiveEntry entry;
        while ((entry = zais.getNextZipEntry()) != null) {
            ret.put(entry.getName(), IOUtils.toByteArray(zais));
        }
    }

    return ret;
}

From source file:org.jboss.as.test.integration.web.annotationsmodule.WebModuleDeploymentTestCase.java

private static void createTestModule(File testModuleRoot) throws IOException {
    if (testModuleRoot.exists()) {
        throw new IllegalArgumentException(testModuleRoot + " already exists");
    }//w  ww.j a va  2  s . c  o m
    File file = new File(testModuleRoot, "main");
    if (!file.mkdirs()) {
        throw new IllegalArgumentException("Could not create " + file);
    }

    URL url = WebModuleDeploymentTestCase.class.getResource("module.xml");
    if (url == null) {
        throw new IllegalStateException("Could not find module.xml");
    }
    copyFile(new File(file, "module.xml"), url.openStream());

    JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "webTest.jar");
    jar.addClasses(ModuleServlet.class);

    Indexer indexer = new Indexer();
    try (final InputStream resource = ModuleServlet.class
            .getResourceAsStream(ModuleServlet.class.getSimpleName() + ".class")) {
        indexer.index(resource);
    }
    Index index = indexer.complete();
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    IndexWriter writer = new IndexWriter(data);
    writer.write(index);
    jar.addAsManifestResource(new ByteArrayAsset(data.toByteArray()), "jandex.idx");
    FileOutputStream jarFile = new FileOutputStream(new File(file, "webTest.jar"));
    try {
        jar.as(ZipExporter.class).exportTo(jarFile);
    } finally {
        jarFile.flush();
        jarFile.close();
    }

}

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

@BeforeClass
public static void init() throws IOException {
    /* ClassPathXmlApplicationContext appContext =
        new ClassPathXmlApplicationContext(new String[] {
                "depositClientContext.xml", "classpath*:org/dataconservancy/config/applicationContext.xml"});*/

    client = new DefaultHttpClient();//(DefaultHttpClient) appContext.getBean("httpClient");

    final URL defaultProps = IngestTest.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());
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

private static Schema createSchema(Collection<String> schemaUrls) throws SAXException, IOException {
    Logger log = LoggerFactory.getLogger(SLUnmarshaller.class);
    Source[] sources = new Source[schemaUrls.size()];
    Iterator<String> urls = schemaUrls.iterator();
    StringBuilder sb = null;//w  w  w  .  j  a  v  a2  s.  c  om
    if (log.isDebugEnabled()) {
        sb = new StringBuilder();
        sb.append("Created schema using URLs: ");
    }
    for (int i = 0; i < sources.length && urls.hasNext(); i++) {
        String url = urls.next();
        if (url != null && url.startsWith("classpath:")) {
            URL schemaUrl = new URL(null, url, new ClasspathURLStreamHandler());
            sources[i] = new StreamSource(schemaUrl.openStream());
        } else {
            sources[i] = new StreamSource(url);
        }
        if (sb != null) {
            sb.append(url);
            if (urls.hasNext()) {
                sb.append(", ");
            }
        }
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemaFactory.newSchema(sources);
    if (sb != null) {
        log.debug(sb.toString());
    }
    return schema;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * Gets data from {@link URL}//from ww w . ja v a 2  s.  c  o m
 * 
 * @param url
 * @param isBug
 *            specifies whether url refers to the BUG
 * @return
 * @throws IOException
 */
protected static String get(URL url, boolean isBug) throws IOException {
    if (isBug) {
        return URLUtils.readFromStream(url.openStream());
    }
    // commented out line below because this method never calls BUGnet
    // and the token is being phased out -BB 8/21/08
    // URL urlWithToken = URLUtils.appendTokenToURL(url.toString());
    return SSLUtils.getData(url);
}

From source file:info.mtgdb.api.Db.java

private static JSONObject getObject(String url) {
    JSONObject ja;/*www .j  a  v  a 2  s .  co m*/
    try {
        URL ur = new URL(url);
        JSONTokener tokener = new JSONTokener(ur.openStream());
        ja = new JSONObject(tokener);
    } catch (JSONException e) {
        System.err.println("Problem with the JSON?  That isn't good.");
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        System.err.println("Check your URL for correctness.");
        System.err.println("'" + url + "' is malformed for some reason.");
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        System.err.println("Problem opening an input stream from the URL: " + url);
        e.printStackTrace();
        return null;
    }

    return ja;
}

From source file:info.mtgdb.api.Db.java

private static JSONArray getArray(String url) {
    JSONArray ja;//from  w ww  .  j av  a 2s.c  o  m
    try {
        URL ur = new URL(url);
        JSONTokener tokener = new JSONTokener(ur.openStream());
        ja = new JSONArray(tokener);
    } catch (JSONException e) {
        System.err.println("Problem with the JSON?  That isn't good.");
        e.printStackTrace();
        return null;
    } catch (MalformedURLException e) {
        System.err.println("Check your URL for correctness.");
        System.err.println("'" + url + "' is malformed for some reason.");
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        System.err.println("Problem opening an input stream from the URL: " + url);
        e.printStackTrace();
        return null;
    }

    return ja;
}

From source file:cn.ctyun.amazonaws.util.XpathUtils.java

public static Document documentFrom(URL url) throws SAXException, IOException, ParserConfigurationException {
    return documentFrom(url.openStream());
}

From source file:com.arrow.acs.ManifestUtils.java

public static Manifest readManifest(Class<?> clazz) {
    String method = "readManifest";
    String jarFile = null;// ww  w  .j  ava  2 s .  c  o m
    String path = clazz.getProtectionDomain().getCodeSource().getLocation().toString();
    for (String token : path.split("/")) {
        token = token.replace("!", "").toLowerCase().trim();
        if (token.endsWith(".jar")) {
            jarFile = token;
            break;
        }
    }
    LOGGER.logInfo(method, "className: %s, path: %s, jarFile: %s", clazz.getName(), path, jarFile);
    InputStream is = null;
    try {
        if (!StringUtils.isEmpty(jarFile)) {
            Enumeration<URL> enumeration = Thread.currentThread().getContextClassLoader()
                    .getResources(JarFile.MANIFEST_NAME);
            while (enumeration.hasMoreElements()) {
                URL url = enumeration.nextElement();
                for (String token : url.toString().split("/")) {
                    token = token.replace("!", "").toLowerCase();
                    if (token.equals(jarFile)) {
                        LOGGER.logInfo(method, "loading manifest from: %s", url.toString());
                        return new Manifest(is = url.openStream());
                    }
                }
            }
        } else {
            URL url = new URL(path + "/META-INF/MANIFEST.MF");
            LOGGER.logInfo(method, "loading manifest from: %s", url.toString());
            return new Manifest(is = url.openStream());
        }
    } catch (IOException e) {
    } finally {
        IOUtils.closeQuietly(is);
    }
    LOGGER.logError(method, "manifest file not found for: %s", clazz.getName());
    return null;
}

From source file:com.google.android.glass.sample.kittycompass.model.Landmarks.java

/**
 * Reads the text from {@code res/raw/landmarks.json} and returns it as a string.
 */// w  w w  .ja va2s  . co  m
private static String readLandmarksResource() {
    URL landmarksUrl;
    try {
        landmarksUrl = new URL(LANDMARKS_URL);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Landmarks URL is malformed", e);
        return null;
    }
    InputStream is;
    try {
        is = landmarksUrl.openStream();
    } catch (IOException e) {
        Log.e(TAG, "Could not fetch landmarks", e);
        return "";
    }
    StringBuffer buffer = new StringBuffer();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
            buffer.append('\n');
        }
    } catch (IOException e) {
        Log.e(TAG, "Could not read landmarks resource", e);
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close landmarks resource stream", e);
            }
        }
    }

    return buffer.toString();
}