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:gemlite.core.internal.support.system.ServerConfigHelper.java

private synchronized static void initConfig0(String envFile) {
    try {/*w  w  w. ja  v a  2s.c  o m*/
        Enumeration<URL> envs = ServerConfigHelper.class.getClassLoader().getResources(envFile);
        List<URL> list = new ArrayList<>();
        while (envs.hasMoreElements()) {
            list.add(envs.nextElement());
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            URL url = list.get(i);
            System.out.println("Load env from:" + url);
            Properties prop = new Properties();
            prop.load(url.openStream());
            serverConfig.putAll(prop);
        }
        // String url=ServerConfigHelper.class.getClassLoader().getResource(envFile).toString();
        // System.out.println("Load env from:"+url);
        // serverConfig.load(ServerConfigHelper.class.getClassLoader().getResourceAsStream(envFile));
    } catch (IOException e) {
        e.printStackTrace();
        initlized.set(false);
    }
    List<Object> names = new ArrayList<>(serverConfig.keySet());
    Collections.sort(names, new Comparator<Object>() {

        @Override
        public int compare(Object o1, Object o2) {
            return o1.toString().compareTo(o2.toString());
        }
    });
    Iterator<Object> it = names.iterator();
    while (it.hasNext()) {
        String key = it.next().toString();
        // String value = serverConfig.getProperty(key);
        String value = OptionConverter.findAndSubst(key, serverConfig);
        if (NAMES.contains(key))
            processENV(key, value);
        else
            System.out.println(key + ":" + value);
        System.setProperty(key, value);
    }

    if (System.getProperty("BINDIP") == null && System.getenv("BINDIP") != null)
        setProperty(ITEMS.BINDIP.name(), System.getenv("BINDIP"));

    String bindip = getConfig(ITEMS.BINDIP);
    boolean localhost = bindip.equalsIgnoreCase("localhost");
    if (localhost) {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            bindip = addr.getHostAddress();
            setProperty(ITEMS.BINDIP.name(), bindip);
            System.out.println("BINDIP changed to : " + bindip);
            String locators = getConfig(ITEMS.LOCATORS);
            locators = locators.replaceAll("localhost", bindip);
            setProperty(ITEMS.LOCATORS.name(), locators);
            System.out.println("LOCATORS changed to : " + locators);
        } catch (UnknownHostException e) {
            initlized.set(false);
            System.err.println("Unkonw host!");
        }
    }

    processLocators();
    // log
    // PropertyConfigurator.configure(ServerConfigHelper.class.getClassLoader().getResource(log4jFile));

    WorkPathHelper.verifyPath("log");
}

From source file:cz.lbenda.gui.controls.TextAreaFrmController.java

/** Create new instance return main node and controller of this node and sub-nodes */
public static Tuple2<Parent, TextAreaFrmController> createNewInstance() {
    URL resource = TextAreaFrmController.class.getResource(FXML_RESOURCE);
    try {/*from   w w  w .  j a va2  s.c  o m*/
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(resource);
        loader.setBuilderFactory(new JavaFXBuilderFactory());
        Parent node = loader.load(resource.openStream());
        TextAreaFrmController controller = loader.getController();
        return new Tuple2<>(node, controller);
    } catch (IOException e) {
        LOG.error("Problem with reading FXML", e);
        throw new RuntimeException("Problem with reading FXML", e);
    }
}

From source file:eu.aniketos.ncvm.impl.Tests.java

/**
 * Load a complete text file into a string for use by the testing process.
 * @param file the pathname of the file to read in.
 * @return the contents of the file./*from   ww  w . j  a  v  a  2 s  .  c  o  m*/
 * @throws IOException generated if there is a problem while attempting to read from the file.
 */
private static String LoadTestFile(String file) throws IOException {
    String contents = "";
    BundleContext context = Activator.getContext();
    System.out.println("Reading test file: " + file);
    URL configURL = context.getBundle().getEntry(file);
    if (configURL != null) {
        BufferedReader input = new BufferedReader(new InputStreamReader(configURL.openStream()));
        try {
            // Read in each user
            contents += input.readLine();
            String line = "";
            while (line != null) {
                line = input.readLine();
                if (line != null) {
                    contents += line;
                }
            }
        } finally {
            input.close();
        }
    }

    return contents;
}

From source file:com.griddynamics.jagger.JaggerLauncher.java

public static void loadBootProperties(URL directory, String environmentPropertiesLocation,
        Properties environmentProperties) throws IOException {
    URL bootPropertiesFile = new URL(directory, environmentPropertiesLocation);
    System.setProperty(ENVIRONMENT_PROPERTIES, environmentPropertiesLocation);
    environmentProperties.load(bootPropertiesFile.openStream());

    String defaultBootPropertiesLocation = environmentProperties.getProperty(DEFAULT_ENVIRONMENT_PROPERTIES);
    if (defaultBootPropertiesLocation == null) {
        defaultBootPropertiesLocation = DEFAULT_ENVIRONMENT_PROPERTIES_LOCATION;
    }// w  w w.j av a2s  . co m
    URL defaultBootPropertiesFile = new URL(directory, defaultBootPropertiesLocation);
    Properties defaultBootProperties = new Properties();
    defaultBootProperties.load(defaultBootPropertiesFile.openStream());
    for (String name : defaultBootProperties.stringPropertyNames()) {
        if (!environmentProperties.containsKey(name)) {
            environmentProperties.setProperty(name, defaultBootProperties.getProperty(name));
        }
    }

    Properties properties = System.getProperties();
    for (Enumeration<String> enumeration = (Enumeration<String>) properties.propertyNames(); enumeration
            .hasMoreElements();) {
        String key = enumeration.nextElement();
        environmentProperties.put(key, properties.get(key));
    }

    System.setProperty(ENVIRONMENT_PROPERTIES, environmentPropertiesLocation);
    System.setProperty(DEFAULT_ENVIRONMENT_PROPERTIES, defaultBootPropertiesLocation);
}

From source file:io.apiman.gateway.test.junit.servlet.ServletGatewayTestServer.java

/**
 * Initialize the DB with the apiman gateway DDL.
 * @param connection//from   w  w w. ja va 2s  .c  om
 */
private static void initDB(Connection connection) throws Exception {
    ClassLoader cl = ServletGatewayTestServer.class.getClassLoader();
    URL resource = cl.getResource("ddls/apiman-gateway_h2.ddl");
    try (InputStream is = resource.openStream()) {
        DdlParser ddlParser = new DdlParser();
        List<String> statements = ddlParser.parse(is);
        for (String sql : statements) {
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.execute();
        }
    }
}

From source file:com.github.jrh3k5.mojo.flume.io.ArchiveUtils.java

/**
 * Un-GZIP a file.//from   ww  w. java2 s. c o m
 * 
 * @param toUnzip
 *            A {@link URL} representing the GZIP file to be unzipped.
 * @param toFile
 *            A {@link File} representing the location to which the unzipped file should be placed.
 * @throws IOException
 *             If any errors occur during the unzipping.
 * @see #gzipFile(File, File)
 */
public static void gunzipFile(URL toUnzip, File toFile) throws IOException {
    if (toFile.exists() && !toFile.isFile()) {
        throw new IllegalArgumentException("Destination file " + toFile
                + " exists, but is not a file and, as such, cannot be written to.");
    }

    GZIPInputStream zipIn = null;
    FileOutputStream fileOut = null;
    try {
        zipIn = new GZIPInputStream(toUnzip.openStream());
        fileOut = new FileOutputStream(toFile);
        IOUtils.copy(zipIn, fileOut);
    } finally {
        IOUtils.closeQuietly(fileOut);
        IOUtils.closeQuietly(zipIn);
    }
}

From source file:com.revo.deployr.rbroker.example.util.DeployRUtil.java

public static RData simulateGeneratedData(Logger log) {

    RData df = null;/*from   www.j ava 2s. c  o  m*/
    try {

        URL url = new URL("http://astrostatistics.psu.edu/datasets/HIP_star.dat");
        InputStream is = url.openStream();
        RDataTable table = RDataFactory.createDataTable(is, "\\s+", true, true);
        df = table.asDataFrame("hip");

    } catch (Exception ex) {
        log.warn("Simulate generated data failed, ex=" + ex);
    } finally {
        return df;
    }

}

From source file:de.uzk.hki.da.sb.restfulService.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * //from  w  w w.  j  a  va 2 s . c o  m
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {

    String path = fileName.substring(0, fileName.lastIndexOf("/"));
    File dir = new File(Configuration.getTempDirPath() + "/" + path);
    dir.mkdirs();

    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }

    return inputFile.getAbsolutePath();
}

From source file:architecture.common.model.factory.ModelTypeFactory.java

private static List<ModelList> parseLegacyXmlFile(List<ModelList> list) throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> enumeration = cl.getResources(IF_PLUGIN_PATH);
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);/* ww  w .j a  va 2  s.co  m*/
    XMLReader xmlreader = factory.newSAXParser().getXMLReader();
    ImplFactoryParsingHandler handler = new ImplFactoryParsingHandler();
    xmlreader.setContentHandler(handler);
    xmlreader.setDTDHandler(handler);
    xmlreader.setEntityResolver(handler);
    xmlreader.setErrorHandler(handler);
    System.out.println("Model Enum:");
    do {
        if (!enumeration.hasMoreElements())
            break;
        URL url = (URL) enumeration.nextElement();
        System.out.println(" - " + url);
        try {
            xmlreader.parse(new InputSource(url.openStream()));
            ModelList factorylist = new ModelList();
            factorylist.rank = handler.rank;
            factorylist.modelTypes.addAll(handler.getModels());
            list.add(factorylist);
        } catch (Exception exception) {
        }
    } while (true);

    return list;
}

From source file:com.tc.util.ProductInfo.java

static InputStream getData(String name) {
    CodeSource codeSource = ProductInfo.class.getProtectionDomain().getCodeSource();
    if (codeSource != null && codeSource.getLocation() != null) {
        URL source = codeSource.getLocation();

        if (source.getProtocol().equals("file") && source.toExternalForm().endsWith(".jar")) {
            URL res;
            try {
                res = new URL("jar:" + source.toExternalForm() + "!" + name);
                InputStream in = res.openStream();
                if (in != null) {
                    return in;
                }//  w ww .j  a v a 2  s . c  o m
            } catch (MalformedURLException e) {
                throw new AssertionError(e);
            } catch (IOException e) {
                // must not be embedded in this jar -- resolve via loader path
            }
        } else if (source.getProtocol().equals("file") && (new File(source.getPath()).isDirectory())) {
            File local = new File(source.getPath(), name);

            if (local.isFile()) {
                try {
                    return new FileInputStream(local);
                } catch (FileNotFoundException e) {
                    throw new AssertionError(e);
                }
            }
        }
    }

    return ProductInfo.class.getResourceAsStream(name);
}