Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

In this page you can find the example usage for java.lang ClassLoader getResourceAsStream.

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:nl.denhaag.tw.comparators.gui.ReportWriter.java

private static String readFromClasspath(String name) throws IOException {
    ClassLoader classLoader = (ClassLoader) Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream(name);
    StringBuilder emailContent = new StringBuilder();
    InputStreamReader fileReader = new InputStreamReader(is);
    BufferedReader bFileReader = new BufferedReader(fileReader);
    String line = null;/*from   w w  w . j a v  a2s .c om*/
    while ((line = bFileReader.readLine()) != null) {
        emailContent.append(line + "\n");
    }
    String result = emailContent.toString();
    bFileReader.close();
    return result;
}

From source file:cool.pandora.modeller.ModellerClient.java

public static InputStream getFile(final String fileName) {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    return classloader.getResourceAsStream(fileName);
}

From source file:com.networknt.light.server.LightServer.java

/**
 * This replay is to initialize database when the db is newly created. It load rules, forms and pages
 * and certain setup that need to make the applications working. To replay the entire event schema,
 * you have to call it from the Db Admin interface.
 *
 *///from  w w  w  . j  a  v a2 s.co  m
static private void replayEvent() {

    // need to replay from a file instead if the file exist. Otherwise, load from db and replay.
    // in this case, we need to recreate db.

    StringBuilder sb = new StringBuilder("");

    //Get file from resources folder
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("initdb.json");
    try (Scanner scanner = new Scanner(is)) {
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            sb.append(line).append("\n");
        }
        scanner.close();

        ObjectMapper mapper = ServiceLocator.getInstance().getMapper();
        if (sb.length() > 0) {
            // if you want to generate the initdb.json from your dev env, then you should make this
            // file as empty in server resources folder and load all objects again.
            List<Map<String, Object>> events = mapper.readValue(sb.toString(),
                    new TypeReference<List<HashMap<String, Object>>>() {
                    });

            // replay event one by one.
            for (Map<String, Object> event : events) {
                RuleEngine.getInstance().executeRule(Util.getEventRuleId(event), event);
            }
        }
    } catch (Exception e) {
        logger.error("Exception:", e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.ExperimentStarter.java

/**
 * Method which executes Groovy script provided in the pathToScript.
 * //from   ww w .j  av a  2s.  co  m
 * @param pathToScript
 *            path to Groovy script.
 */
public static void start(String pathToScript)
        throws InstantiationException, IllegalAccessException, IOException {
    ClassLoader parent = ExperimentStarter.class.getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);

    StringWriter writer = new StringWriter();
    IOUtils.copy(parent.getResourceAsStream(pathToScript), writer, "UTF-8");
    Class<?> groovyClass = loader.parseClass(writer.toString());
    GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
    Object[] a = {};
    groovyObject.invokeMethod("run", a);
    loader.close();
}

From source file:at.ac.tuwien.ifs.lupu.LangDetFilterFactory.java

public static synchronized void loadData() throws LangDetectException {
    LOG.log(Level.ALL, "in loadData");
    if (loaded) {
        return;/*from   ww w.  ja  v  a  2 s.c om*/
    }
    loaded = true;
    List<String> profileData = new ArrayList<>();
    Charset encoding = Charset.forName("UTF-8");
    for (String language : profileLanguages) {
        LOG.log(Level.ALL, "langdetect-profiles/{0}", language);
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        InputStream stream = loader.getResourceAsStream("langdetect-profiles/" + language);

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, encoding))) {
            profileData.add(new String(IOUtils.toCharArray(reader)));
        } catch (IOException ex) {
            Logger.getLogger(LangDetFilterFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    DetectorFactory.loadProfile(profileData);
    DetectorFactory.setSeed(0);
}

From source file:be.fedict.eid.dss.sp.servlet.PkiServlet.java

public static KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws Exception {

    LOG.debug("get SP private key entry");

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    KeyStore keyStore = KeyStore.getInstance("jks");
    InputStream keystoreStream = classLoader.getResourceAsStream("sp.jks");
    keyStore.load(keystoreStream, "secret".toCharArray());

    return (KeyStore.PrivateKeyEntry) keyStore.getEntry("sp",
            new KeyStore.PasswordProtection("secret".toCharArray()));
}

From source file:net.ontopia.utils.PropertyUtils.java

public static Properties loadPropertiesFromClassPath(String resource) throws IOException {
    // Load properties from classpath
    ClassLoader cloader = PropertyUtils.class.getClassLoader();
    Properties properties = new Properties();
    InputStream istream = cloader.getResourceAsStream(resource);
    if (istream == null)
        return null;
    properties.load(istream);//from  www  .  jav  a2 s. co m
    return properties;
}

From source file:ClassUtils.java

/**
 * Load a properties file from the classpath.
 * /*ww  w .jav  a 2s.  com*/
 * @param name Name of the properties file
 * @throws IOException If the properties file could not be loaded
 */
public static InputStream getResourceAsStream(String name) throws IOException {
    ClassLoader cl = getClassLoader();
    InputStream is = null;
    is = cl.getResourceAsStream(name);
    if (is == null) {
        throw new IOException("Unable to load " + " " + name);
    }

    return is;
}

From source file:com.mgmtp.perfload.core.common.util.PropertiesUtils.java

/**
 * Loads properties as map from the given classpath resource using the current context
 * classloader. This method delegates to {@link #loadProperties(Reader)}.
 * /*from  w  ww.java 2s .  c  o  m*/
 * @param resource
 *            the resource
 * @param encoding
 *            the encoding to use
 * @param exceptionIfNotFound
 *            if {@code true}, an {@link IllegalStateException} is thrown if the resource cannot
 *            be loaded; otherwise an empty map is returned
 * @return the map
 */
public static PropertiesMap loadProperties(final String resource, final String encoding,
        final boolean exceptionIfNotFound) throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Reader reader = null;
    try {
        InputStream is = cl.getResourceAsStream(resource);
        if (is == null) {
            if (exceptionIfNotFound) {
                throw new IOException("InputStream is null. Properties not found: " + resource);
            }
            return new PropertiesMap();
        }
        reader = new InputStreamReader(is, encoding);
        return loadProperties(reader);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:ClassUtils.java

/**
 * Load a properties file from the classpath.
 * /*w w  w. j  a  va2 s  .c  o  m*/
 * @param name Name of the properties file
 * @throws IOException If the properties file could not be loaded
 */
public static Properties getResourceAsProperties(String name) throws IOException {
    ClassLoader cl = getClassLoader();
    InputStream is = null;
    is = cl.getResourceAsStream(name);
    if (is == null) {
        throw new IOException("Unable to load " + " " + name);
    }
    Properties props = new Properties();
    props.load(is);

    return props;
}