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:gov.sbs.blame.BlamePlugin.java

@Override
protected void executeReport(Locale locale) throws MavenReportException {

    try {//from  w  ww .j ava  2  s. c  om
        File pmdFile = new File("target/pmd.xml");
        if (!pmdFile.exists()) {
            getLog().error("Could not find the PMD XML file located in [root]/target.  Did you run PMD first?");
            return;
        }

        Map<String, List<PmdViolation>> pmdViolations = getPmdViolations(pmdFile);

        ClassLoader classLoader = this.getClass().getClassLoader();
        for (String fileName : STATIC_REPORT_FILE_NAMES) {

            FileUtils.copyInputStreamToFile(classLoader.getResourceAsStream(fileName),
                    new File(getReportDirectory() + "/site/images", fileName));

        }

        List<PmdViolation> allGuiltyParties = new ArrayList<PmdViolation>();
        for (String key : pmdViolations.keySet()) {
            allGuiltyParties.addAll(pmdViolations.get(key));
        }

        createEmbeddedReportPage(locale, generateHtml(allGuiltyParties));
    } catch (Exception ex) {
        getLog().error(ex);
    }
}

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

@Provides
@Named("openAthensEntity")
@Singleton/*from   w  w w.  j  a  va 2  s  .  c o  m*/
public IdentityProviderDao provideOpenAthensEntityDao(DbExecutor dbExecutor) throws Exception {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    Properties properties = new Properties();

    properties.load(classLoader.getResourceAsStream("dao/open-athens-entity-dao-db.properties"));

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

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

@Provides
@Named("oauthEntity")
@Singleton//from   ww  w .  j a  v a 2 s.  co  m
public IdentityProviderDao provideOauthEntityDao(DbExecutor dbExecutor) throws Exception {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    Properties properties = new Properties();

    properties.load(classLoader.getResourceAsStream("dao/oauth-entity-dao-db.properties"));

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

From source file:com.varaneckas.hawkscope.util.IconFactory.java

/**
 * Gets icon with plugin's classloader//  w  ww .  ja  va  2  s  .c  o m
 * 
 * @param name Icon name with extension
 * @return icon
 */
public Image getPluginIcon(final String name, final ClassLoader classLoader) {
    if (resourcePool.containsKey(name)) {
        return resourcePool.get(name);
    }
    final Image i = new Image(display, classLoader.getResourceAsStream("icons/" + name));
    resourcePool.put(name, i);
    return i;
}

From source file:com.npower.dm.util.PropertyMessageResources.java

/**
 * Load the messages associated with the specified Locale key.  For this
 * implementation, the <code>config</code> property should contain a fully
 * qualified package and resource name, separated by periods, of a series
 * of property resources to be loaded from the class loader that created
 * this PropertyMessageResources instance.  This is exactly the same name
 * format you would use when utilizing the
 * <code>java.util.PropertyResourceBundle</code> class.
 *
 * @param localeKey Locale key for the messages to be retrieved
 *//*from  w ww.  j a  v a2s  . c  om*/
protected synchronized void loadLocale(String localeKey) {

    if (log.isTraceEnabled()) {
        log.trace("loadLocale(" + localeKey + ")");
    }

    // Have we already attempted to load messages for this locale?
    if (locales.get(localeKey) != null) {
        return;
    }

    locales.put(localeKey, localeKey);

    // Set up to load the property resource for this locale key, if we can
    String name = config.replace('.', '/');
    if (localeKey.length() > 0) {
        name += "_" + localeKey;
    }

    name += ".properties";
    InputStream is = null;
    Properties props = new Properties();

    // Load the specified property resource
    if (log.isTraceEnabled()) {
        log.trace("  Loading resource '" + name + "'");
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    is = classLoader.getResourceAsStream(name);
    if (is != null) {
        try {
            props.load(is);

        } catch (IOException e) {
            log.error("loadLocale()", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("loadLocale()", e);
            }
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("  Loading resource completed");
    }

    // Copy the corresponding values into our cache
    if (props.size() < 1) {
        return;
    }

    synchronized (messages) {
        Iterator<Object> names = props.keySet().iterator();
        while (names.hasNext()) {
            String key = (String) names.next();
            if (log.isTraceEnabled()) {
                log.trace("  Saving message key '" + messageKey(localeKey, key));
            }
            messages.put(messageKey(localeKey, key), props.getProperty(key));
        }
    }

}

From source file:net.sf.navigator.util.PropertyMessageResources.java

/**
 * Load the messages associated with the specified Locale key.  For this
 * implementation, the <code>config</code> property should contain a fully
 * qualified package and resource name, separated by periods, of a series
 * of property resources to be loaded from the class loader that created
 * this PropertyMessageResources instance.  This is exactly the same name
 * format you would use when utilizing the
 * <code>java.util.PropertyResourceBundle</code> class.
 *
 * @param localeKey Locale key for the messages to be retrieved
 *//*from www  .  j a  v a  2s .  com*/
protected synchronized void loadLocale(String localeKey) {

    if (log.isTraceEnabled()) {
        log.trace("loadLocale(" + localeKey + ")");
    }

    // Have we already attempted to load messages for this locale?
    if (locales.get(localeKey) != null) {
        return;
    }

    locales.put(localeKey, localeKey);

    // Set up to load the property resource for this locale key, if we can
    String name = config.replace('.', '/');
    if (localeKey.length() > 0) {
        name += "_" + localeKey;
    }

    name += ".properties";
    InputStream is = null;
    Properties props = new Properties();

    // Load the specified property resource
    if (log.isTraceEnabled()) {
        log.trace("  Loading resource '" + name + "'");
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    is = classLoader.getResourceAsStream(name);
    if (is != null) {
        try {
            props.load(is);

        } catch (IOException e) {
            log.error("loadLocale()", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                log.error("loadLocale()", e);
            }
        }
    }

    if (log.isTraceEnabled()) {
        log.trace("  Loading resource completed");
    }

    // Copy the corresponding values into our cache
    if (props.size() < 1) {
        return;
    }

    synchronized (messages) {
        Iterator names = props.keySet().iterator();
        while (names.hasNext()) {
            String key = (String) names.next();
            if (log.isTraceEnabled()) {
                log.trace("  Saving message key '" + messageKey(localeKey, key));
            }
            messages.put(messageKey(localeKey, key), props.getProperty(key));
        }
    }

}

From source file:org.apache.hadoop.crypto.key.kms.server.MiniKMS.java

public void start() throws Exception {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    System.setProperty(KMSConfiguration.KMS_CONFIG_DIR, kmsConfDir);
    File aclsFile = new File(kmsConfDir, "kms-acls.xml");
    if (!aclsFile.exists()) {
        InputStream is = cl.getResourceAsStream("mini-kms-acls-default.xml");
        OutputStream os = new FileOutputStream(aclsFile);
        IOUtils.copy(is, os);//from   w w  w  . jav  a2s  .  c  o  m
        is.close();
        os.close();
    }
    File coreFile = new File(kmsConfDir, "core-site.xml");
    if (!coreFile.exists()) {
        Configuration core = new Configuration();
        Writer writer = new FileWriter(coreFile);
        core.writeXml(writer);
        writer.close();
    }
    File kmsFile = new File(kmsConfDir, "kms-site.xml");
    if (!kmsFile.exists()) {
        Configuration kms = new Configuration(false);
        kms.set(KMSConfiguration.KEY_PROVIDER_URI,
                "jceks://file@" + new Path(kmsConfDir, "kms.keystore").toUri());
        kms.set("hadoop.kms.authentication.type", "simple");
        Writer writer = new FileWriter(kmsFile);
        kms.writeXml(writer);
        writer.close();
    }
    System.setProperty("log4j.configuration", log4jConfFile);
    jetty = createJettyServer(keyStore, keyStorePassword, inPort);

    // we need to do a special handling for MiniKMS to work when in a dir and
    // when in a JAR in the classpath thanks to Jetty way of handling of webapps
    // when they are in the a DIR, WAR or JAR.
    URL webXmlUrl = cl.getResource("kms-webapp/WEB-INF/web.xml");
    if (webXmlUrl == null) {
        throw new RuntimeException("Could not find kms-webapp/ dir in test classpath");
    }
    boolean webXmlInJar = webXmlUrl.getPath().contains(".jar!/");
    String webappPath;
    if (webXmlInJar) {
        File webInf = new File("target/" + UUID.randomUUID().toString() + "/kms-webapp/WEB-INF");
        webInf.mkdirs();
        new File(webInf, "web.xml").delete();
        InputStream is = cl.getResourceAsStream("kms-webapp/WEB-INF/web.xml");
        OutputStream os = new FileOutputStream(new File(webInf, "web.xml"));
        IOUtils.copy(is, os);
        is.close();
        os.close();
        webappPath = webInf.getParentFile().getAbsolutePath();
    } else {
        webappPath = cl.getResource("kms-webapp").getPath();
    }
    WebAppContext context = new WebAppContext(webappPath, "/kms");
    if (webXmlInJar) {
        context.setClassLoader(cl);
    }
    jetty.addHandler(context);
    jetty.start();
    kmsURL = new URL(getJettyURL(jetty), "kms");
}

From source file:com.flozano.socialauth.SocialAuthConfig.java

/**
 * Loads the application configuration from the given file
 * /*  w  w  w .  ja  va  2 s .  c o  m*/
 * @param fileName
 *            the file name which contains the application configuration
 *            properties
 * @throws Exception
 */
public void load(final String fileName) throws Exception {
    if (!isConfigLoaded) {
        LOG.debug("Loading application configuration from file " + fileName);
        ClassLoader loader = SocialAuthConfig.class.getClassLoader();
        try {
            InputStream in = loader.getResourceAsStream(fileName);
            load(in);
        } catch (NullPointerException ne) {
            throw new FileNotFoundException(fileName + " file is not found in your class path");
        }
    }
}

From source file:org.alfresco.custom.constraint.AbsDBConstrainst.java

/**
 * Set the default parameters when necessary
 *///from   w w  w.jav a 2  s  .co m
private void setDefaultParameters() {

    if (properties == null) {
        logger.debug("Load the properties data");
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream in = loader.getResourceAsStream("alfresco-global.properties");
        properties = new Properties();
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // set database driver
    if (driver == null || driver.trim().isEmpty()) {
        driver = properties.getProperty("db.driver");
    }

    // set database user
    if (user == null || user.trim().isEmpty()) {
        user = properties.getProperty("db.username");
    }

    // set database password
    if (pwd == null || pwd.trim().isEmpty()) {
        pwd = properties.getProperty("db.password");
    }

    // set database URL
    if (url == null || url.trim().isEmpty()) {
        url = properties.getProperty("db.url");

        if (url.contains("${db.name}")) {
            String dbName = properties.getProperty("db.name");
            url = url.replace("${db.name}", dbName);
        }
    }

}

From source file:backup.namenode.NameNodeBackupServicePlugin.java

private ClassLoader getClassLoader() throws Exception {
    LOG.info("Looking for {} in classpath", HDFS_BACKUP_STATUS_RESOURCES_ZIP);
    InputStream inputStream = findInClassPath();
    if (inputStream == null) {
        ClassLoader classLoader = getClass().getClassLoader();
        LOG.info("Looking for {} in default classloader", HDFS_BACKUP_STATUS_RESOURCES_ZIP);
        inputStream = classLoader.getResourceAsStream("/" + HDFS_BACKUP_STATUS_RESOURCES_ZIP);
        if (inputStream == null) {
            LOG.info("Checking jvm property {}", HDFS_BACKUP_STATUS_RESOURCES_ZIP_PROP);
            String filePath = System.getProperty(HDFS_BACKUP_STATUS_RESOURCES_ZIP_PROP);
            if (filePath != null) {
                inputStream = new FileInputStream(filePath);
            }//from   w  w w . j  a va2  s .  c  om
            if (inputStream == null) {
                LOG.info("Checking env property {}", HDFS_BACKUP_STATUS_RESOURCES_ZIP_ENV);
                filePath = System.getProperty(HDFS_BACKUP_STATUS_RESOURCES_ZIP_ENV);
                if (filePath != null) {
                    inputStream = new FileInputStream(filePath);
                }
            }
        }
    }

    if (inputStream == null) {
        LOG.info("{} not found", HDFS_BACKUP_STATUS_RESOURCES_ZIP);
        return null;
    } else {
        try {
            return getClassLoader(inputStream);
        } finally {
            inputStream.close();
        }
    }
}