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.google.dart.tools.core.utilities.io.FileUtilities.java

/**
 * Copy the contents of the given input file to the given output file.
 * /* w  w  w . ja v a2 s. c o  m*/
 * @param input the input file from which the contents are to be read
 * @param output the output file to which the contents are to be written
 * @throws IOException if the files cannot be either read or written
 */
public static void copyFile(URL input, File output) throws IOException {
    copyFile(input.openStream(), new FileOutputStream(output));
}

From source file:com.surenpi.autotest.suite.SuiteRunnerLauncher.java

/**
* @param urlList/*w  ww.ja  va  2 s  .  co m*/
* @throws IOException 
* @throws UnsupportedEncodingException 
*/
private static void runnerRead(List<URL> urlList) throws UnsupportedEncodingException, IOException {
    InputStream inputA = SuiteRunnerLauncher.class.getResourceAsStream("/");
    if (inputA == null) {
        return;
    }

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputA));
    String line = null;
    while ((line = reader.readLine()) != null) {
        URL itemUrl = SuiteRunnerLauncher.class.getResource("/" + line);
        if (itemUrl == null) {
            continue;
        }
        String path = URLDecoder.decode(itemUrl.getFile(), "utf-8");
        if (!path.endsWith(".xml")) {
            continue;
        }

        try (InputStream input = itemUrl.openStream()) {
            byte[] content = IOUtils.toByteArray(input);
            if (SuiteUtils.isSuiteXml(content)) {
                urlList.add(itemUrl);
            }
        }
    }
}

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

@BeforeClass
public static void loadProperties() throws IOException {
    final URL defaultProps = ManualDepositIT.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:net.oauth.v2.example.provider.core.SampleOAuth2Provider.java

public static synchronized void loadConsumers() throws IOException {
    Properties p = consumerProperties;
    if (p == null) {
        p = new Properties();
        String resourceName = "" + SampleOAuth2Provider.class.getPackage().getName().replace(".", "/")
                + "/provider.properties";
        URL resource = SampleOAuth2Provider.class.getClassLoader().getResource(resourceName);
        if (resource == null) {
            throw new IOException("resource not found: " + resourceName);
        }/*w  ww  . j  a va2 s .  co  m*/
        InputStream stream = resource.openStream();
        try {
            p.load(stream);
        } finally {
            stream.close();
        }
    }
    consumerProperties = p;

    // for each entry in the properties file create a OAuthConsumer
    for (Map.Entry prop : p.entrySet()) {
        String consumer_key = (String) prop.getKey();
        // make sure it's key not additional properties
        if (!consumer_key.contains(".")) {
            String consumer_secret = (String) prop.getValue();
            if (consumer_secret != null) {
                String consumer_description = (String) p.getProperty(consumer_key + ".description");
                String consumer_callback_url = (String) p.getProperty(consumer_key + ".callbackURL");
                // Create OAuthConsumer w/ key and secret
                OAuth2Client client = new OAuth2Client(consumer_callback_url, consumer_key, consumer_secret);
                client.setProperty("name", consumer_key);
                client.setProperty("description", consumer_description);
                ALL_CLIENTS.put(consumer_key, client);
            }
        }
    }

}

From source file:de.thingweb.desc.ThingDescriptionParser.java

public static Thing fromURL(URL url) throws JsonParseException, IOException {

    InputStream is = new BufferedInputStream(url.openStream());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int b;/*from   w w w. ja  v a 2 s .co  m*/
    while ((b = is.read()) != -1) {
        baos.write(b);
    }
    return fromBytes(baos.toByteArray());
}

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

/**
 * return list of signers for the document available via the given
 * URL./*from  w  w  w. j a  v  a2s  . c  om*/
 *
 * @param odfUrl
 * @return list of X509 certificates
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws MarshalException
 * @throws XMLSignatureException
 */
public static List<X509Certificate> getSigners(URL odfUrl) throws IOException, ParserConfigurationException,
        SAXException, MarshalException, XMLSignatureException {
    List<X509Certificate> signers = new LinkedList<X509Certificate>();
    if (null == odfUrl) {
        throw new IllegalArgumentException("odfUrl is null");
    }
    ZipInputStream odfZipInputStream = new ZipInputStream(odfUrl.openStream());
    ZipEntry zipEntry;

    while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
        if (ODFUtil.isSignatureFile(zipEntry)) {
            Document documentSignatures = ODFUtil.loadDocument(odfZipInputStream);
            NodeList signatureNodeList = documentSignatures.getElementsByTagNameNS(XMLSignature.XMLNS,
                    "Signature");

            for (int idx = 0; idx < signatureNodeList.getLength(); idx++) {
                Node signatureNode = signatureNodeList.item(idx);
                X509Certificate signer = getVerifiedSignatureSigner(odfUrl, signatureNode);
                if (null == signer) {
                    LOG.debug("JSR105 says invalid signature");
                } else {
                    signers.add(signer);
                }
            }
            return signers;
        }
    }
    LOG.debug("no signature file present");
    return signers;
}

From source file:com.zotoh.maedr.device.HttpIOTrait.java

/**
 * @param createContext//  w  ww .j av a  2 s.  c  o m
 * @param sslType
 * @param key
 * @param pwd
 * @return
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableEntryException
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws IOException
 * @throws KeyManagementException
 */
protected static Tuple cfgSSL(boolean createContext, String sslType, URL key, String pwd)
        throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException, CertificateException,
        IOException, KeyManagementException {

    boolean jks = key.getFile().endsWith(".jks");
    InputStream inp = key.openStream();
    CryptoStore s;

    try {
        s = jks ? new JKSStore() : new PKCSStore();
        s.init(pwd);
        s.addKeyEntity(inp, pwd);
    } finally {
        StreamUte.close(inp);
    }

    SSLContext c = null;
    if (createContext) {
        c = SSLContext.getInstance(sslType);
        c.init(s.getKeyManagerFactory().getKeyManagers(), s.getTrustManagerFactory().getTrustManagers(),
                Crypto.getInstance().getSecureRandom());
    }

    return new Tuple(s, c);
}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }//from  w  w w  .  ja v  a  2s .  c  om

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpHandler(system, master));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * Reads a private key form a url//from ww  w  . j a  va  2 s.c  om
 *
 * @param privateKeyUrl the url containing the private key
 * @return the read private key
 *
 * @throws IOException if any.
 * @throws GeneralSecurityException
 *                             if any.
 */
@Nullable
public static RSAPrivateKey readPrivateKey(@Nullable URL privateKeyUrl)
        throws IOException, GeneralSecurityException {
    //If a null url is given - just return null
    if (privateKeyUrl == null) {
        return null;
    }

    //We have an url --> return it
    DataInputStream in = new DataInputStream(privateKeyUrl.openStream());
    try {
        byte[] keyBytes = IOUtils.toByteArray(in);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes);
        return (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
    } finally {
        in.close();
    }
}

From source file:de.renew.workflow.connector.internal.cases.ScenarioCompatibilityHelper.java

public static boolean ensureBackwardsCompatibility(final ScenarioHandlingProjectNature nature) {
    // FIXME: this is dirty fix only for this release 2.3
    // should be implemented in other way, we just do not have any time now
    try {// w ww .  j  a va2s .  co m
        if (nature == null
                || !nature.getProject().hasNature("org.kalypso.kalypso1d2d.pjt.Kalypso1D2DProjectNature")) //$NON-NLS-1$
            return true;

        // FIXME: the whole code here does not belong to this place -> this is a hidden dependency to 1d2d: bad!
        // TODO: instead implement an extension point mechanism
        final ProjectTemplate[] lTemplate = EclipsePlatformContributionsExtensions
                .getProjectTemplates("org.kalypso.kalypso1d2d.pjt.projectTemplate"); //$NON-NLS-1$
        try {
            // FIXME: this very probably does not work correctly or any more at all!

            /* Unpack project from template */
            final File destinationDir = nature.getProject().getLocation().toFile();
            final URL data = lTemplate[0].getData();
            final String location = data.toString();
            final String extension = FilenameUtils.getExtension(location);
            if ("zip".equalsIgnoreCase(extension)) //$NON-NLS-1$
            {
                // TODO: this completely overwrite the old project content, is this intended?
                ZipUtilities.unzip(data.openStream(), destinationDir, false);
            } else {
                final URL fileURL = FileLocator.toFileURL(data);
                final File dataDir = FileUtils.toFile(fileURL);
                if (dataDir == null) {
                    return false;
                }

                // FIXME: this only fixes the basic scenario, is this intended?

                final IOFileFilter lFileFilter = new WildcardFileFilter(new String[] { "wind.gml" }); //$NON-NLS-1$
                final IOFileFilter lDirFilter = TrueFileFilter.INSTANCE;
                final Collection<?> windFiles = FileUtils.listFiles(destinationDir, lFileFilter, lDirFilter);

                if (dataDir.isDirectory() && (windFiles == null || windFiles.size() == 0)) {
                    final WildcardFileFilter lCopyFilter = new WildcardFileFilter(
                            new String[] { "*asis", "models", "wind.gml" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    FileUtils.copyDirectory(dataDir, destinationDir, lCopyFilter);
                } else {
                    return true;
                }
            }
        } catch (final Throwable t) {
            t.printStackTrace();
            return false;
        }

        nature.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (final CoreException e) {
        // FIXME: this is no error handling; the users are not informed and will stumble over following errors caued by
        // this problem

        WorkflowConnectorPlugin.getDefault().getLog().log(e.getStatus());
        e.printStackTrace();
        return false;
    }

    return true;
}