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:cz.hobrasoft.pdfmu.Main.java

private static void loadPomProperties() {
    ClassLoader classLoader = Main.class.getClassLoader();
    InputStream in = classLoader.getResourceAsStream(POM_PROPERTIES_RESOURCE_NAME);
    if (in != null) {
        try {/*w  ww.ja v  a 2 s.c  om*/
            POM_PROPERTIES.load(in);
        } catch (IOException ex) {
            logger.severe(String.format("Could not load the POM properties file: %s", ex));
        }
        try {
            in.close();
        } catch (IOException ex) {
            logger.severe(String.format("Could not close the POM properties file: %s", ex));
        }
    } else {
        logger.severe("Could not open the POM properties file.");
    }
}

From source file:cz.hobrasoft.pdfmu.Main.java

private static void loadLegalNotice() {
    ClassLoader classLoader = Main.class.getClassLoader();
    InputStream in = classLoader.getResourceAsStream(LEGAL_NOTICE_RESOURCE_NAME);
    if (in != null) {
        try {//www  . j av  a  2  s  . com
            legalNotice = IOUtils.toString(in, US_ASCII);
        } catch (IOException ex) {
            logger.severe(String.format("Could not load the legal notice file: %s", ex));
        }
        try {
            in.close();
        } catch (IOException ex) {
            logger.severe(String.format("Could not close the legal notice file: %s", ex));
        }
    } else {
        logger.severe("Could not open the legal notice file.");
    }
}

From source file:com.alibaba.wasp.zookeeper.ZKConfig.java

/**
 * Make a Properties object holding ZooKeeper config equivalent to zoo.cfg.
 * If there is a zoo.cfg in the classpath, simply read it in. Otherwise parse
 * the corresponding config options from the Wasp XML configs and generate
 * the appropriate ZooKeeper properties.
 * @param conf Configuration to read from.
 * @return Properties holding mappings representing ZooKeeper zoo.cfg file.
 */// ww w  .j  a v a 2s.co m
public static Properties makeZKProps(Configuration conf) {
    // First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
    // it and grab its configuration properties.
    ClassLoader cl = FQuorumPeer.class.getClassLoader();
    final InputStream inputStream = cl.getResourceAsStream(FConstants.ZOOKEEPER_CONFIG_NAME);
    if (inputStream != null) {
        try {
            return parseZooCfg(conf, inputStream);
        } catch (IOException e) {
            LOG.warn("Cannot read " + FConstants.ZOOKEEPER_CONFIG_NAME + ", loading from XML files", e);
        }
    }

    // Otherwise, use the configuration options from Wasp's XML files.
    Properties zkProperties = new Properties();

    // Directly map all of the wasp.zookeeper.property.KEY properties.
    for (Entry<String, String> entry : conf) {
        String key = entry.getKey();
        if (key.startsWith(FConstants.ZK_CFG_PROPERTY_PREFIX)) {
            String zkKey = key.substring(FConstants.ZK_CFG_PROPERTY_PREFIX_LEN);
            String value = entry.getValue();
            // If the value has variables substitutions, need to do a get.
            if (value.contains(VARIABLE_START)) {
                value = conf.get(key);
            }
            zkProperties.put(zkKey, value);
        }
    }

    // If clientPort is not set, assign the default.
    if (zkProperties.getProperty(FConstants.CLIENT_PORT_STR) == null) {
        zkProperties.put(FConstants.CLIENT_PORT_STR, FConstants.DEFAULT_ZOOKEPER_CLIENT_PORT);
    }

    // Create the server.X properties.
    int peerPort = conf.getInt("wasp.zookeeper.peerport", 2888);
    int leaderPort = conf.getInt("wasp.zookeeper.leaderport", 3888);

    final String[] serverHosts = conf.getStrings(FConstants.ZOOKEEPER_QUORUM, FConstants.LOCALHOST);
    for (int i = 0; i < serverHosts.length; ++i) {
        String serverHost = serverHosts[i];
        String address = serverHost + ":" + peerPort + ":" + leaderPort;
        String key = "server." + i;
        zkProperties.put(key, address);
    }

    return zkProperties;
}

From source file:org.apache.falcon.unit.FalconUnit.java

private static void setupOozieConfigs() throws IOException {
    sysProps = new HashMap<>();
    String oozieHomeDir = OOZIE_HOME_DIR;
    String oozieConfDir = oozieHomeDir + "/conf";
    String oozieHadoopConfDir = oozieConfDir + "/hadoop-conf";
    String oozieActionConfDir = oozieConfDir + "/action-conf";
    String oozieLogsDir = oozieHomeDir + "/logs";
    String oozieDataDir = oozieHomeDir + "/data";

    LocalFileSystem fs = new LocalFileSystem();
    fs.mkdirs(new Path(oozieHomeDir));
    fs.mkdirs(new Path(oozieConfDir));
    fs.mkdirs(new Path(oozieHadoopConfDir));
    fs.mkdirs(new Path(oozieActionConfDir));
    fs.mkdirs(new Path(oozieLogsDir));
    fs.close();/* w w w.  j a v a  2s  .  c om*/

    setSystemProperty("oozie.home.dir", oozieHomeDir);
    setSystemProperty("oozie.data.dir", oozieDataDir);
    setSystemProperty("oozie.action.conf", oozieActionConfDir);
    setSystemProperty("oozie.log.dir", oozieLogsDir);
    setSystemProperty("oozie.log4j.file", "localoozie-log4j.properties");
    setSystemProperty("oozielocal.log", "oozieLogsDir/oozielocal.log");

    Configuration oozieSiteConf = new Configuration(false);
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream oozieSiteInputStream = classLoader.getResourceAsStream(OOZIE_SITE_XML);
    XConfiguration configuration = new XConfiguration(oozieSiteInputStream);
    Properties props = configuration.toProperties();
    for (String propName : props.stringPropertyNames()) {
        oozieSiteConf.set(propName, props.getProperty(propName));
    }
    oozieSiteInputStream.close();

    InputStream oozieDefaultInputStream = classLoader.getResourceAsStream(OOZIE_DEFAULT_XML);
    configuration = new XConfiguration(oozieDefaultInputStream);
    String classes = configuration.get(Services.CONF_SERVICE_CLASSES);
    oozieSiteConf.set(Services.CONF_SERVICE_CLASSES,
            classes.replaceAll("org.apache.oozie.service.ShareLibService,", ""));
    File target = new File(oozieConfDir, OOZIE_SITE_XML);
    FileOutputStream outStream = null;
    try {
        outStream = new FileOutputStream(target);
        oozieSiteConf.writeXml(outStream);
    } finally {
        if (outStream != null) {
            outStream.close();
        }
    }
    oozieDefaultInputStream.close();

    CurrentUser.authenticate(System.getProperty("user.name"));
}

From source file:org.opendaylight.ovsdb.integrationtest.northbound.OvsdbNorthboundV2IT.java

@Parameterized.Parameters(name = "ApiTest{index}:{0}")
public static List<Object[]> getData() throws FileNotFoundException {
    ClassLoader classloader = OvsdbNorthboundV2IT.class.getClassLoader();
    InputStream input = classloader.getResourceAsStream("northbound.yaml");
    Yaml yaml = new Yaml();
    List<Map<String, Object>> object = (List<Map<String, Object>>) yaml.load(input);
    List<Object[]> parameters = Lists.newArrayList();

    for (Map<String, Object> o : object) {
        Object[] l = o.values().toArray();
        parameters.add(l);//w  w  w. j av  a2s.  co m
        break;
    }

    return parameters;

}

From source file:ResourcesUtils.java

/**
 * Returns a resource on the classpath as a Stream object
 * //  w  ww . j  a  v  a2  s  .  c  o  m
 * @param loader
 *            The classloader used to load the resource
 * @param resource
 *            The resource to find
 * @throws IOException
 *             If the resource cannot be found or read
 * @return The resource
 */
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
    InputStream in = null;
    if (loader != null) {
        in = loader.getResourceAsStream(resource);
    }
    if (in == null) {
        in = ClassLoader.getSystemResourceAsStream(resource);
    }
    if (in == null) {
        throw new IOException("Could not find resource " + resource);
    }
    return in;
}

From source file:com.hangum.tadpole.engine.initialize.TadpoleSystemInitializer.java

/**
 * system  .//from   w  w w.j a  v  a 2 s. c o  m
 * 
 * 1. ??  ? ?, ?? . 2. ??    ?? .
 * 
 * @throws Exception
 */
public static boolean initSystem() throws Exception {

    // move to driver file
    if (!TadpoleApplicationContextManager.isSystemInitialize())
        initJDBCDriver();

    // Is SQLite?
    if (!ApplicationArgumentUtils.isDBServer()) {
        if (!new File(DEFAULT_DB_FILE_LOCATION + DB_NAME).exists()) {
            if (logger.isInfoEnabled())
                logger.info("Createion Engine DB. Type is SQLite.");
            ClassLoader classLoader = TadpoleSystemInitializer.class.getClassLoader();
            InputStream is = classLoader
                    .getResourceAsStream("com/hangum/tadpole/engine/initialize/TadpoleEngineDBEngine.sqlite");

            byte[] dataByte = new byte[1024];
            int len = 0;

            FileOutputStream fos = new FileOutputStream(DEFAULT_DB_FILE_LOCATION + DB_NAME);
            while ((len = is.read(dataByte)) > 0) {
                fos.write(dataByte, 0, len);
            }

            fos.close();
            is.close();
        }
    }

    return TadpoleApplicationContextManager.getSystemAdmin() == null ? false : true;
}

From source file:com.espertech.esperio.db.config.ConfigurationDBAdapter.java

/**
 * Returns an input stream from an application resource in the classpath.
 * <p>/*w  w w.  j ava  2s . c  o m*/
 * The method first removes the '/' character from the resource name if
 * the first character is '/'.
 * <p>
 * The lookup order is as follows:
 * <p>
 * If a thread context class loader exists, use <tt>Thread.currentThread().getResourceAsStream</tt>
 * to obtain an InputStream.
 * <p>
 * If no input stream was returned, use the <tt>Configuration.class.getResourceAsStream</tt>.
 * to obtain an InputStream.
 * <p>
 * If no input stream was returned, use the <tt>Configuration.class.getClassLoader().getResourceAsStream</tt>.
 * to obtain an InputStream.
 * <p>
 * If no input stream was returned, throw an Exception.
 *
 * @param resource to get input stream for
 * @return input stream for resource
 */
protected static InputStream getResourceAsStream(String resource) {
    String stripped = resource.startsWith("/") ? resource.substring(1) : resource;

    InputStream stream = null;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        stream = classLoader.getResourceAsStream(stripped);
    }
    if (stream == null) {
        stream = ConfigurationDBAdapter.class.getResourceAsStream(resource);
    }
    if (stream == null) {
        stream = ConfigurationDBAdapter.class.getClassLoader().getResourceAsStream(stripped);
    }
    if (stream == null) {
        throw new RuntimeException(resource + " not found");
    }
    return stream;
}

From source file:gov.va.vinci.leo.tools.LeoUtils.java

/**
 * Load the config file(s).//from  ww  w.  j  av  a 2 s.com
 *
 * @param environment name of the environment to load
 * @param configFilePaths paths the config files to load, local or remote
 * @return ConfigObject with accumulated variables representing the environment
 * @throws IOException if there is a problem reading the config files
 */
public static ConfigObject loadConfigFile(String environment, String... configFilePaths) throws IOException {
    ConfigSlurper slurper = new ConfigSlurper(environment);
    ConfigObject config = new ConfigObject();
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    for (String filePath : configFilePaths) {
        InputStream in = cl.getResourceAsStream(filePath);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        IOUtils.copy(in, out);
        String resourceAsString = out.toString();
        config.merge(slurper.parse(resourceAsString));
    }
    return config;
}

From source file:org.alfresco.grid.GridProperties.java

/**
 * Helper method to reduce the code duplication.
 * Reads the properties file(s) for the hub/node configuration and returns it as an {@link String} array
 *
 * @param role {@link String} The role for the grid. Can be hub or node.
 * @return An array of {@link String} property keys and values
 * @throws Exception Throws an {@link IOException} if the properties file cannot be found or
 * An {@link Exception} if property key has an invalid format
 *///  w  ww.  j  a v  a 2s . c o  m
private static String[] getProperties(String role, int... gridPort) {
    if (role == null || role.isEmpty()) {
        throw new IllegalArgumentException("Role for the grid is required");
    }
    List<String> propertyKeysAndValues = new ArrayList<String>();
    Properties properties = new Properties();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    // Load the properties
    String propertyPath = PROPERTY_FOLDER + role + PROPERTY_SUFFIX;
    try {
        properties.load(loader.getResourceAsStream(propertyPath));
    } catch (IOException e) {
        throw new RuntimeException(String.format("Unable to load main property file %s", propertyPath), e);
    }
    // Load the local properties to override the existing ones
    String localPropertyPath = PROPERTY_FOLDER + role + PROPERTY_LOCAL_SUFFIX;
    InputStream localProperty = loader.getResourceAsStream(localPropertyPath);
    if (localProperty != null) {
        try {
            properties.load(localProperty);
        } catch (IOException e) {
            logger.error(String.format("Unable to load local property file: %s ", localPropertyPath), e);
        }
    }
    if (gridPort.length > 0) {
        properties.setProperty("hub.url.port", String.valueOf(gridPort[0]));
    }

    Set<Object> keys = properties.keySet();
    for (Object object : keys) {
        String key = (String) object;
        if (key.startsWith(PROPERTY_PREFIX)) {
            String parameter = key.split(PROPERTY_PREFIX)[1];
            if (StringUtils.isBlank(parameter)) {
                throw new RuntimeException("The property '" + key + "' does not have a valid format.");
            }
            String propertyKey = CMD_PARAMETER_PREFIX + parameter;
            String propertyValue = StrSubstitutor.replace(properties.getProperty(key), properties);
            propertyKeysAndValues.add(propertyKey);
            propertyKeysAndValues.add(propertyValue);
        }
    }
    return propertyKeysAndValues.toArray(new String[propertyKeysAndValues.size()]);
}