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:de.cosmocode.palava.core.Palava.java

/**
 * Creates a new {@link Framework} using the specified module and
 * a properties url./*from  w  w w .  ja v a 2s  . c o  m*/
 * <p>
 *   The loaded properties will be bound using the {@link Settings} annotation.
 * </p>
 * 
 * @since 2.4
 * @param module the application main module
 * @param url the url pointing to the properties file
 * @return a new configured {@link Framework} instance
 * @throws NullPointerException if module or url is null
 * @throws IllegalArgumentException if reading from the specified url failed
 * @throws ConfigurationException if guice configuration failed
 * @throws ProvisionException if providing an instance during creation failed
 */
public static Framework newFramework(Module module, URL url) {
    Preconditions.checkNotNull(module, "Module");
    Preconditions.checkNotNull(url, "URL");
    final InputStream stream;

    try {
        stream = url.openStream();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    try {
        final Properties properties = new Properties();
        properties.load(stream);
        return newFramework(module, properties);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        Closeables.closeQuietly(stream);
    }
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Return the KeyStore by given URL and password
 * /*ww  w  . j a  v  a 2s.  com*/
 * @param url
 * @param password
 * @return KeyStore
 * @throws Exception
 */
public static KeyStore getKeyStore(final URL url, final String password) throws Exception {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:net.sf.jabref.gui.IconTheme.java

/**
 * Read a typical java property url into a Map. Currently doesn't support escaping
 * of the '=' character - it simply looks for the first '=' to determine where the key ends.
 * Both the key and the value is trimmed for whitespace at the ends.
 *
 * @param url    The URL to read information from.
 * @param prefix A String to prefix to all values read. Can represent e.g. the directory
 *               where icon files are to be found.
 * @return A Map containing all key-value pairs found.
 *///w w  w  .  j a v  a  2s . co  m
// FIXME: prefix can be removed?!
private static Map<String, String> readIconThemeFile(URL url, String prefix) {
    Objects.requireNonNull(url, "url");
    Objects.requireNonNull(prefix, "prefix");

    Map<String, String> result = new HashMap<>();

    try (BufferedReader in = new BufferedReader(
            new InputStreamReader(url.openStream(), StandardCharsets.ISO_8859_1))) {
        String line;
        while ((line = in.readLine()) != null) {
            if (!line.contains("=")) {
                continue;
            }

            int index = line.indexOf('=');
            String key = line.substring(0, index).trim();
            String value = prefix + line.substring(index + 1).trim();
            result.put(key, value);
        }
    } catch (IOException e) {
        LOGGER.warn("Unable to read default icon theme.", e);
    }
    return result;
}

From source file:net.sf.nmedit.jsynth.clavia.nordmodular.utils.NmUtils.java

public static NM1ModuleDescriptions parseModuleDescriptions()
        throws ParserConfigurationException, SAXException, IOException, URISyntaxException {
    NmUtils instance = new NmUtils();

    final String file = "/module-descriptions/modules.xml";

    NM1ModuleDescriptions descriptions;//from   w  ww  . j  a  va2s .  c  o  m

    URL resource = instance.getClass().getResource(file);

    InputStream in = new BufferedInputStream(resource.openStream());
    try {
        descriptions = NM1ModuleDescriptions
                .parse(RelativeClassLoader.fromPath(NmUtils.class.getClassLoader(), resource), in);
    } finally {
        in.close();
    }

    return descriptions;
}

From source file:com.opensymphony.xwork2.util.FileManager.java

/**
 * Loads opens the named file and returns the InputStream
 *
 * @param fileUrl    - the URL of the file to open
 * @param openStream - if true, open an InputStream to the file and return it
 * @return an InputStream of the file contents or null
 * @throws IllegalArgumentException if there is no file with the given file name
 *//*from w w  w  . ja va2  s . c  o m*/
public static InputStream loadFile(URL fileUrl, boolean openStream) {
    if (fileUrl == null) {
        return null;
    }

    String fileName = fileUrl.toString();
    InputStream is = null;

    if (openStream) {
        try {
            is = fileUrl.openStream();

            if (is == null) {
                throw new IllegalArgumentException("No file '" + fileName + "' found as a resource");
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("No file '" + fileName + "' found as a resource");
        }
    }

    if (isReloadingConfigs()) {
        Revision revision;

        if (LOG.isDebugEnabled()) {
            LOG.debug("Creating revision for URL: " + fileName);
        }
        if (URLUtil.isJBoss5Url(fileUrl)) {
            revision = JBossFileRevision.build(fileUrl);
        } else if (URLUtil.isJarURL(fileUrl)) {
            revision = JarEntryRevision.build(fileUrl);
        } else {
            revision = FileRevision.build(fileUrl);
        }
        if (revision == null) {
            files.put(fileName, Revision.build(fileUrl));
        } else {
            files.put(fileName, revision);
        }
    }
    return is;
}

From source file:com.aurel.track.item.SendItemEmailBL.java

public static String getItemInfo(WorkItemContext workItemContext, boolean useProjectSpecificID, Locale locale) {
    Integer workItemID = workItemContext.getWorkItemBean().getObjectID();
    String infoHtml = "";
    TWorkItemBean workItemBean = workItemContext.getWorkItemBean();
    Map<String, Object> root = new HashMap<String, Object>();
    root.put("issueNoLabel",
            FieldRuntimeBL.getLocalizedDefaultFieldLabel(SystemFields.INTEGER_ISSUENO, locale));

    String statusDisplay = "";
    IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(SystemFields.INTEGER_STATE);
    if (workItemBean != null) {
        Object state = workItemBean.getAttribute(SystemFields.INTEGER_STATE);
        statusDisplay = fieldTypeRT.getShowValue(state, locale);
    }/*from  w w  w.jav a2 s  . c  o m*/
    root.put("statusDisplay", statusDisplay);
    root.put("synopsis", workItemBean.getSynopsis());
    root.put("workItemID", workItemID);
    String id = "";
    if (useProjectSpecificID) {
        id = ItemBL.getSpecificProjectID(workItemContext);
    } else {
        id = workItemBean.getObjectID().toString();
    }
    root.put("itemID", id);
    root.put("screenBean", ItemBL.loadFullRuntimeScreenBean(workItemContext.getScreenID()));

    Map<String, String> fieldLabels = new HashMap<String, String>();
    Map<String, String> fieldDisplayValues = new HashMap<String, String>();
    Map<Integer, TFieldConfigBean> mapFieldsConfig = workItemContext.getFieldConfigs();
    Iterator<Integer> it = mapFieldsConfig.keySet().iterator();
    while (it.hasNext()) {
        Integer fieldID = it.next();
        TFieldConfigBean cfg = mapFieldsConfig.get(fieldID);
        fieldLabels.put("f_" + fieldID, cfg.getLabel());
        String displayValue = SendItemEmailBL.getFieldDisplayValue(fieldID, workItemContext,
                useProjectSpecificID);
        fieldDisplayValues.put("f_" + fieldID, displayValue);
    }
    root.put("fieldLabels", fieldLabels);
    root.put("fieldDisplayValues", fieldDisplayValues);
    try {
        URL propURL = ApplicationBean.getInstance().getServletContext()
                .getResource("/WEB-INF/classes/template/printItem.ftl");
        InputStream in = propURL.openStream();
        Template fmtemplate = new Template("name", new InputStreamReader(in));
        StringWriter w = new StringWriter();
        try {
            fmtemplate.process(root, w);
        } catch (Exception e) {
            LOGGER.error(
                    "Processing reminder template " + fmtemplate.getName() + " failed with " + e.getMessage());
        }
        w.flush();
        infoHtml = w.toString();
    } catch (Exception ex) {
        LOGGER.error(ExceptionUtils.getStackTrace(ex));
    }
    return infoHtml;
}

From source file:io.apiman.test.common.util.TestUtil.java

/**
 * Loads a test plan from a classpath resource.
 * @param resourcePath//from   w ww. java  2 s  .co m
 * @param cl
 */
public static final TestPlan loadTestPlan(String resourcePath, ClassLoader cl) {
    try {
        URL url = cl.getResource(resourcePath);
        if (url == null)
            throw new RuntimeException("Test Plan not found: " + resourcePath); //$NON-NLS-1$
        JAXBContext jaxbContext = JAXBContext.newInstance(TestPlan.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        TestPlan plan = (TestPlan) jaxbUnmarshaller.unmarshal(url.openStream());
        return plan;
    } catch (Throwable e) {
        throw new RuntimeException(e);
    }
}

From source file:forge.util.FileUtil.java

public static List<String> readFile(final URL url) {
    final List<String> lines = new ArrayList<String>();
    ThreadUtil.executeWithTimeout(new Callable<Void>() {
        @Override/*from  w w w  . jav a2 s .c  o m*/
        public Void call() throws Exception {
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String line;
            while ((line = in.readLine()) != null) {
                lines.add(line);
            }
            return null;
        }
    }, 5000); //abort reading file if it takes longer than 5 seconds
    return lines;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * Validates an XML document, capturing the messages into an XML document that includes
 * any @xtrc values pointing back into the original DOCX file from which the XML was
 * generated. The resulting document can be used to then annotate the original DOCX
 * file with messages bound to the original source paragraphs.
 * @param messageFile The file to hold the XML message log.
 * @param inputUrl The URL of the document to be validated.
 * @param catalogs List of entity resolution catalogs to be used by the parser (as for the Resolver class).
 * @return DOM document containing the log messages. Also saves the messages to the specified file.
 * @throws IOException//from ww w  . j a v a 2s. com
 * @throws ParserConfigurationException
 * @throws Exception
 * @throws SAXException
 * @throws FileNotFoundException
 */
public static Document validateXml(File messageFile, URL inputUrl, String[] catalogs)
        throws IOException, ParserConfigurationException, Exception, SAXException, FileNotFoundException {
    InputSource source = new InputSource(inputUrl.openStream());
    Document logDoc = DomUtil.getNewDom();
    XMLReader reader = SaxUtil.getXMLFormatLoggingXMLReader(log, logDoc, true, catalogs);
    reader.parse(source);
    InputStream logStream = DomUtil.serializeToInputStream(logDoc, "utf-8");
    System.out.println("Creating message file \"" + messageFile.getAbsolutePath() + "\"...");
    OutputStream fos = new FileOutputStream(messageFile);
    IOUtils.copy(logStream, fos);
    return logDoc;
}

From source file:com.ibm.research.rdf.store.sparql11.SparqlParserUtilities.java

public static Query parseSparqlFile(URL sparqlFile, Map<String, String> rdfStorePrefixes) {
    Query q;/*from   ww  w  .j a v  a 2  s .  c  o m*/
    CharStream stream;
    try {
        stream = new ANTLRInputStream(sparqlFile.openStream(), "UTF8");
    } catch (IOException e) {
        log.error("Error opening file " + sparqlFile);
        throw new RuntimeException("Error opening file " + sparqlFile, e);
    }
    q = parseSparql(stream, rdfStorePrefixes);
    return q;
}