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:pl.edu.agh.iosr.lsf.dao.DatabaseHelper.java

public String regenerateDB() {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    try (Connection c = source.getConnection()) {
        List<String> tables = new ArrayList<String>();

        try (ResultSet rs = c.getMetaData().getTables(null, null, "%", null)) {
            while (rs.next()) {
                tables.add(rs.getString(3));
            }/*from  ww  w  .  j ava 2  s  .c  o m*/
        }
        try (Statement s = c.createStatement()) {
            for (String t : tables) {
                s.execute("drop table " + t);
            }
        }
        ClassLoader cl = QueryExecutor.class.getClassLoader();

        new QueryExecutor().execute(c, cl.getResourceAsStream("createDB.sql"), pw);

        try (ResultSet rs = c.getMetaData().getTables(null, null, "%", null)) {
            while (rs.next()) {
                pw.println(rs.getString(3) + "<br/>");
            }
        }

    } catch (SQLException | IOException e) {

        e.printStackTrace(pw);

    }

    return sw.toString();
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.Converter.java

/**
 * Saves the html document to a file with .html extension
 *
 * @param document JDOM Document representing the HTML
 * @return written HTML File object/*  ww  w . ja  v  a 2 s .  co  m*/
 */
private File saveHtmlFile(Document document) {
    Path tempFilepath = null;

    Path tempDirPath = formulaConverter.getTempDirPath();

    ClassLoader classLoader = getClass().getClassLoader();
    InputStream mainCssIs = classLoader.getResourceAsStream(MAIN_CSS_FILENAME);

    logger.debug("Copying main.css file to temp dir: " + tempDirPath.toAbsolutePath().toString());
    try {
        Files.copy(mainCssIs, tempDirPath.resolve(MAIN_CSS_FILENAME));
    } catch (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        logger.error("could not copy main.css file to temp dir!");
    }

    tempFilepath = tempDirPath.resolve("latex2mobi.html");

    logger.debug("tempFile created at: " + tempFilepath.toAbsolutePath().toString());
    try {
        Files.write(tempFilepath, new XMLOutputter().outputString(document).getBytes(Charset.forName("UTF-8")));

        if (debugMarkupOutput) {
            logger.info("Debug markup will be generated.");
        }

    } catch (IOException e) {
        logger.error("Error writing HTML to temp dir!");
        logger.error(e.getMessage(), e);
    }

    return tempFilepath.toFile();
}

From source file:org.apache.hadoop.chukwa.hicc.HiccWebServer.java

public void populateDir(List<String> files, Path path) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (String source : files) {
        String name = source.substring(source.indexOf(File.separator));
        Path dest = new Path(path.toString() + File.separator + name);
        InputStream is = contextClassLoader.getResourceAsStream(source);
        StringBuilder sb = new StringBuilder();
        String line = null;//from   w ww .  j av  a 2 s .com

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            FSDataOutputStream out = fs.create(dest);
            out.write(sb.toString().getBytes());
            out.close();
        } catch (IOException e) {
            log.error("Error writing file: " + dest.toString());
        }
    }
}

From source file:org.apache.nifi.processors.ccda.ExtractCCDAAttributes.java

protected void loadMappings() {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    Properties mappings = new Properties();
    try (InputStream is = classloader.getResourceAsStream("mapping.properties")) {
        mappings.load(is);//from  w w w .j  a v  a  2 s  .c  o  m
        // each child element is key#value and multiple elements are separated by @
        for (String property : mappings.stringPropertyNames()) {
            String[] variables = StringUtils.split(mappings.getProperty(property), FIELD_SEPARATOR);
            Map<String, String> map = new LinkedHashMap<String, String>();
            for (String variable : variables) {
                String[] keyvalue = StringUtils.split(variable, KEY_VALUE_SEPARATOR);
                map.put(keyvalue[0], keyvalue[1]);
            }
            processMap.put(property, map);
        }

    } catch (IOException e) {
        getLogger().error("Failed to load mappings", e);
        throw new ProcessException("Failed to load mappings", e);
    }

}

From source file:com.lrs.enviroment.Metadata.java

private void loadFromDefault() {
    InputStream input = null;// w w w  .  j  ava  2  s.  co m
    try {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        input = classLoader.getResourceAsStream(FILE);
        if (input == null) {
            input = classLoader.getResourceAsStream(FILE);
        }
        if (input != null) {
            loadProperties(input);
        }

        input = classLoader.getResourceAsStream(BUILD_INFO_FILE);
        if (input != null) {
            loadAndMerge(input);
        } else {
            // try WAR packaging resolve
            input = classLoader.getResourceAsStream("../../" + BUILD_INFO_FILE);
            if (input != null) {
                loadAndMerge(input);
            }
        }
        afterLoading();
    } catch (Exception e) {
        throw new RuntimeException("Cannot load application metadata:" + e.getMessage(), e);
    } finally {
        closeQuietly(input);
    }
}

From source file:net.anthavio.vinbudin.OAuthController.java

private Properties load(String name) {
    String property = System.getProperty(name, name);

    try {//from ww  w . j av  a  2 s .c  o  m
        InputStream stream;
        File file = new File(property);
        if (file.exists()) {
            stream = new FileInputStream(file);
        } else {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            stream = loader.getResourceAsStream(property);
            if (stream == null) {
                throw new IllegalArgumentException("Properties resource not found: " + property);
            }
        }

        Properties properties = new Properties();
        properties.load(stream);
        return properties;
    } catch (IOException iox) {
        throw new IllegalStateException("Properties resource " + property + " failed to load", iox);
    }
}

From source file:access.deploy.geoserver.PiazzaEnvironment.java

/**
 * Creates the Piazza Postgres vector data store
 *///from   w  w w.j  a v  a  2  s  .c  o  m
private void createPostgresStore() {
    // Get Request XML
    ClassLoader classLoader = getClass().getClassLoader();
    InputStream inputStream = null;
    String dataStoreBody = null;
    try {
        inputStream = classLoader.getResourceAsStream("templates" + File.separator + "createDataStore.xml");
        dataStoreBody = IOUtils.toString(inputStream);
    } catch (Exception exception) {
        LOGGER.error("Error reading GeoServer Data Store Template.", exception);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception exception) {
            LOGGER.error("Error closing GeoServer Data Store Template Stream.", exception);
        }
    }
    // Create Workspace
    if (dataStoreBody != null) {
        // Insert the credential data into the template
        dataStoreBody = dataStoreBody.replace("$DB_USER", postgresServiceKeyUser);
        dataStoreBody = dataStoreBody.replace("$DB_PASSWORD", postgresServiceKeyPassword);
        dataStoreBody = dataStoreBody.replace("$DB_PORT", postgresPort);
        dataStoreBody = dataStoreBody.replace("$DB_NAME", postgresDatabase);
        dataStoreBody = dataStoreBody.replace("$DB_HOST", postgresHost);

        // POST Data Store to GeoServer
        authHeaders.setContentType(MediaType.APPLICATION_XML);
        HttpEntity<String> request = new HttpEntity<>(dataStoreBody, authHeaders.get());
        String uri = String.format("%s/rest/workspaces/piazza/datastores",
                accessUtilities.getGeoServerBaseUrl());
        try {
            pzLogger.log(String.format("Creating Piazza Data Store to %s", uri), Severity.INFORMATIONAL,
                    new AuditElement(ACCESS, "tryCreateGeoServerDataStore", uri));
            restTemplate.exchange(uri, HttpMethod.POST, request, String.class);
        } catch (HttpClientErrorException | HttpServerErrorException exception) {
            String error = String.format("HTTP Error occurred while trying to create Piazza Data Store: %s",
                    exception.getResponseBodyAsString());
            LOGGER.info(error, exception);
            pzLogger.log(error, Severity.WARNING);
            determineExit();
        } catch (Exception exception) {
            String error = String.format(
                    "Unexpected Error occurred while trying to create Piazza Data Store: %s",
                    exception.getMessage());
            LOGGER.error(error, exception);
            pzLogger.log(error, Severity.ERROR);
            determineExit();
        }
    } else {
        pzLogger.log("Could not create GeoServer Data Store. Could not load Request XML from local Resources.",
                Severity.ERROR);
    }
}

From source file:ispyb.common.util.Constants.java

public static Properties getPropertiesNew() {

    String resourceName = "ISPyB.properties"; // could also be a constant
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Properties props = new Properties();
    try (InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
        props.load(resourceStream);/*from ww w  .  j a v  a  2s. c om*/
    } catch (IOException e) {
        e.printStackTrace();
    }

    return props;
}

From source file:com.liferay.portal.model.ExtletModelHintsImpl.java

public void read(ClassLoader classLoader, String resourceName) throws Exception {
    if (_log.isDebugEnabled()) {
        _log.debug("Loading " + resourceName);
    }/*from w w w  .j  a va2 s  .com*/
    read(classLoader, classLoader.getResourceAsStream(resourceName));
}

From source file:com.atypon.wayf.guice.WayfGuiceModule.java

@Provides
@Named("samlEntity")
@Singleton//from ww  w  . ja  v a2  s  .co m
public IdentityProviderDao provideSamlEntityDao(DbExecutor dbExecutor) throws Exception {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    Properties properties = new Properties();
    properties.load(classLoader.getResourceAsStream("dao/saml-entity-dao-db.properties"));

    return new IdentityProviderDaoDbImpl(properties.getProperty("saml-entity.dao.db.create"),
            properties.getProperty("saml-entity.dao.db.read"),
            properties.getProperty("saml-entity.dao.db.filter"), dbExecutor, SamlEntity.class);
}