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:com.sworddance.util.CUtilities.java

private static InputStream getResourceAsStream(Object searchRoot, String fileName, boolean optional,
        List<String> searchPaths) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (String searchPath : searchPaths) {
        InputStream resource = null;
        if (searchRoot != null) {
            resource = searchRoot.getClass().getResourceAsStream(searchPath);
        }/*from w ww  .ja v  a  2s.  c  o  m*/

        if (resource == null && contextClassLoader != null) {
            resource = contextClassLoader.getResourceAsStream(searchPath);
        }
        if (resource == null) {
            resource = ClassLoader.getSystemResourceAsStream(searchPath);
        }
        if (resource != null) {
            return resource;
        }
    }
    if (!optional) {
        if (fileName != null) {
            throw new ApplicationNullPointerException(fileName, " not found in ", join(searchPaths, ","),
                    " java.class.path=", System.getProperty("java.class.path"), " java.library.path=",
                    System.getProperty("java.library.path"), " searchRoot =", getClassSafely(searchRoot));
        } else {
            throw new ApplicationNullPointerException("No listed file found ", join(searchPaths, ","),
                    " java.class.path=", System.getProperty("java.class.path"), " java.library.path=",
                    System.getProperty("java.library.path"), " searchRoot =", getClassSafely(searchRoot));
        }
    } else {
        return null;
    }
}

From source file:com.vangent.hieos.services.xds.bridge.mapper.CDAToXDSMapperTest.java

/**
 * This method will test the business logic w/in the mapper
 *
 *
 * @throws Exception/*from w  w  w  .  jav  a2  s.c om*/
 */
@Test
public void createReplaceVariablesTest() throws Exception {

    ContentParserConfig cfg = JUnitHelper.createCDAToXDSContentParserConfig();
    ContentParser gen = new ContentParser();

    CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);

    ClassLoader cl = getClass().getClassLoader();
    InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);

    assertNotNull(xmlis);

    byte[] xml = Io.getBytesFromInputStream(xmlis);

    assertNotNull(xml);
    assertTrue(xml.length > 0);

    Document doc = new Document();

    CodedValue type = new CodedValue();
    type.setCode("51855-5");
    type.setCodeSystem("2.16.840.1.113883.6.1");
    type.setCodeSystemName("LOINC");

    doc.setType(type);

    CodedValue format = new CodedValue();

    format.setCode("urn:ihe:pcc:xds-ms:2007");
    format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
    format.setCodeSystemName("XDS");

    doc.setFormat(format);
    doc.setContent(xml);

    Map<String, String> repl = mapper.createReplaceVariables(doc);

    logger.debug(DebugUtils.toPrettyString(repl));

    // 1.2.36.1.2001.1003.0.8003611234567890
    assertEquals("", repl.get(ContentVariableName.AuthorPersonRoot.toString()));
    assertEquals("1.2.36.1.2001.1003.0.8003611234567890",
            repl.get(ContentVariableName.AuthorPersonExtension.toString()));

    // "1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"
    assertEquals("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478",
            repl.get(ContentVariableName.PatientIdRoot.toString()));
    assertEquals("", repl.get(ContentVariableName.PatientIdExtension.toString()));
    assertEquals("6fa11e467880478^^^&1.3.6.1.4.1.21367.2005.3.7&ISO",
            repl.get(ContentVariableName.PatientIdCX.toString()));

    // "1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"
    assertEquals("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478",
            repl.get(ContentVariableName.SourcePatientIdRoot.toString()));
    assertEquals("", repl.get(ContentVariableName.SourcePatientIdExtension.toString()));
    assertEquals("6fa11e467880478^^^&1.3.6.1.4.1.21367.2005.3.7&ISO",
            repl.get(ContentVariableName.SourcePatientIdCX.toString()));
}

From source file:monitoring.tools.AppTweak.java

private void loadProperties() throws Exception {
    logger.debug("Loading properties");
    Properties prop = new Properties();
    try {/*from  ww w .j a v a  2s . c  o m*/
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream input = classLoader.getResourceAsStream("config.properties");
        prop.load(input);
        token = prop.getProperty("appTweakToken");
        logger.debug("Properties loaded successfully");
    } catch (Exception e) {
        throw new IOException("There was an unexpected error loading the properties file.");
    }
}

From source file:com.mgmtp.jfunk.core.config.JFunkBaseModule.java

/**
 * Provides the version of perfLoad as specified in the Maven pom.
 * /*from  w  ww.j  ava  2 s .  c  o m*/
 * @return the version string
 */
@Provides
@Singleton
@JFunkVersion
protected String providePerfLoadVersion() {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream is = loader.getResourceAsStream("com/mgmtp/jfunk/common/version.txt");
    try {
        return IOUtils.toString(is, "UTF-8");
    } catch (IOException ex) {
        throw new IllegalStateException("Could not read jFunk version.", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:de.decidr.test.database.factories.EntityFactory.java

/**
 * Returns the contents of a file that resides in "resources/"
 * /*from  w  w w. jav a 2s  .  c om*/
 * @param fileName
 *            file name without path
 * @return raw bytes of file
 */
public byte[] getFileBytes(String fileName) {
    if (!fileName.startsWith("/")) {
        fileName = "/" + fileName;
    }

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

    InputStream inStream = loader.getResourceAsStream("files" + fileName);

    loader.getClass();

    if (inStream == null) {
        throw new RuntimeException("Cannot open file " + fileName);
    }

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {
        IOUtils.copy(inStream, outStream);
        inStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return outStream.toByteArray();
}

From source file:org.apache.nutch.webapp.common.PluginResourceLoader.java

public InputStream getResourceAsStream(String name) {
    Iterator i = classloaders.iterator();

    while (i.hasNext()) {
        ClassLoader loader = (ClassLoader) i.next();
        InputStream retVal = loader.getResourceAsStream(name);
        if (retVal != null) {
            return retVal;
        }/*from w ww.  j  a  v a  2 s. c  o m*/
    }
    return null;
}

From source file:com.tacitknowledge.util.migration.jdbc.DistributedJdbcMigrationLauncherFactory.java

/**
 * Loads the configuration from the migration config properties file.
 *
 * @param launcher   the launcher to configure
 * @param systemName the name of the system
 * @param propFile   the name of the properties file on the classpath
 * @throws MigrationException if an unexpected error occurs
 *///  w w  w.  ja  va2s .c  o m
private void configureFromMigrationProperties(DistributedJdbcMigrationLauncher launcher, String systemName,
        String propFile) throws MigrationException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream(propFile);
    if (is != null) {
        try {
            Properties props = new Properties();
            props.load(is);

            configureFromMigrationProperties(launcher, systemName, props, propFile);
        } catch (IOException e) {
            throw new MigrationException("Error reading in migration properties file", e);
        } finally {
            try {
                is.close();
            } catch (IOException ioe) {
                throw new MigrationException("Error closing migration properties file", ioe);
            }
        }
    } else {
        throw new MigrationException("Unable to find migration properties file '" + propFile + "'");
    }
}

From source file:org.apache.synapse.commons.util.MiscellaneousUtil.java

/**
 * Loads the properties from a given property file path
 * //from w  w  w .  j a v a 2s .  c  o m
 * @param filePath
 *            Path of the property file
 * @return Properties loaded from given file
 */
public static Properties loadProperties(String filePath) {

    Properties properties = new Properties();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    if (log.isDebugEnabled()) {
        log.debug("Loading a file '" + filePath + "' from classpath");
    }

    InputStream in = null;

    //if we reach to this assume that the we may have to looking to the customer provided external location for the 
    //given properties
    if (System.getProperty(CONF_LOCATION) != null) {
        try {
            in = new FileInputStream(System.getProperty(CONF_LOCATION) + File.separator + filePath);
        } catch (FileNotFoundException e) {
            String msg = "Error loading properties from a file at from the System defined location: "
                    + filePath;
            log.warn(msg);
        }
    }

    if (in == null) {
        //if can not find with system path definition looking to the class path for the given property file
        in = cl.getResourceAsStream(filePath);
    }

    if (in == null) {

        if (log.isDebugEnabled()) {
            log.debug("Unable to load file  '" + filePath + "'");
        }

        filePath = "conf" + File.separatorChar + filePath;
        if (log.isDebugEnabled()) {
            log.debug("Loading a file '" + filePath + "' from classpath");
        }

        in = cl.getResourceAsStream(filePath);
        if (in == null) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to load file  '" + filePath + "'");
            }
        }

    }
    if (in != null) {
        try {
            properties.load(in);
        } catch (IOException e) {
            handleException("Error loading properties from a file at : " + filePath, e);
        }
    }
    return properties;
}

From source file:br.com.sicoob.cro.cop.util.JobXMLLoader.java

/**
 * Le o arquivo {@code jobXMLName} e cria os objetos para o processamento.
 *
 * @throws BatchStartException para algum erro de leitura e inicializacao.
 *//*from w w  w.  j a  v a  2  s.c o m*/
public void loadJSL() throws BatchStartException {
    try {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = tccl.getResourceAsStream(PREFIX.concat(this.jobXMlName.concat(XML_SUFFIX)));

        if (Validation.isNull(inputStream)) {
            throw new BatchStartException(
                    BatchPropertiesUtil.getInstance().getMessage(FILENOTFOUND, this.jobXMlName));
        }

        SAXBuilder builder = new SAXBuilder();
        Document document = (Document) builder.build(inputStream);
        Element rootNode = document.getRootElement();

        this.job = new Job(rootNode.getAttributeValue(ID), Job.Mode.ASYNC);
        loadSteps(rootNode);

        // valida se o job pode est completo
        if (Validation.notNull(this.job.getId()) && Validation.notNull(this.job.getSteps())
                && this.job.getSteps().size() > 0) {
            LOG.info(BatchPropertiesUtil.getInstance().getMessage(BatchKeys.BATCH_LOADER_SUCCESS.getKey(),
                    this.job.getId()));
        } else {
            throw new BatchStartException(BatchPropertiesUtil.getInstance()
                    .getMessage(BatchKeys.BATCH_LOADER_FAIL.getKey(), this.job.getId()));
        }
    } catch (Exception excecao) {
        LOG.fatal(excecao);
        throw new BatchStartException(excecao);
    }
}

From source file:com.vangent.hieos.services.xds.bridge.mapper.CDAToXDSMapperTest.java

/**
 * Method description//from   w  ww .  j  a  va 2s. c o m
 *
 *
 * @throws Exception
 */
@Test
public void mapTest() throws Exception {

    ContentParserConfig cfg = JUnitHelper.createCDAToXDSContentParserConfig();
    ContentParser gen = new ContentParser();

    CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);

    ClassLoader cl = getClass().getClassLoader();
    InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);

    assertNotNull(xmlis);

    String xml = Io.getStringFromInputStream(xmlis);

    assertNotNull(xml);
    assertTrue(StringUtils.isNotBlank(xml));

    Document doc = new Document();

    CodedValue type = new CodedValue();
    type.setCode("51855-5");
    type.setCodeSystem("2.16.840.1.113883.6.1");
    type.setCodeSystemName("LOINC");

    doc.setType(type);

    CodedValue format = new CodedValue();

    format.setCode("urn:ihe:pcc:xds-ms:2007");
    format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
    format.setCodeSystemName("XDS");

    doc.setFormat(format);
    doc.setContent(xml.getBytes());

    SubjectIdentifier patientId = SubjectIdentifierUtils
            .createSubjectIdentifier("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478", null);

    XDSPnRMessage pnr = mapper.map(patientId, doc);

    assertNotNull(pnr);

    String pnrstr = DebugUtils.toPrettyString(pnr.getElement());

    logger.debug(pnrstr);

    Pattern pattern = Pattern.compile("\\{.*?\\}");
    Matcher matcher = pattern.matcher(pnrstr);
    StringBuilder sb = new StringBuilder();

    while (matcher.find()) {

        sb.append(matcher.group());
        sb.append("\n");
    }

    // assertEquals("Found unset tokens: " + sb.toString(), 0, sb.length());

    //      JUnitHelper.createXConfigInstance();
    //
    //      String schemaLocation =
    //          String.format(
    //              "%s/../../config/schema/v3/XDS.b_DocumentRepository.xsd",
    //              System.getProperty("user.dir"));
    //
    //      assertTrue("File " + schemaLocation + " not exist.",
    //              new File(schemaLocation).exists());
    //
    //      XMLSchemaValidator schemaValidator =
    //          new XMLSchemaValidator(schemaLocation);
    //
    //      //schemaValidator.validate(pnrstr);
}