Example usage for java.lang ClassLoader getSystemResourceAsStream

List of usage examples for java.lang ClassLoader getSystemResourceAsStream

Introduction

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

Prototype

public static InputStream getSystemResourceAsStream(String name) 

Source Link

Document

Open for reading, a resource of the specified name from the search path used to load classes.

Usage

From source file:com.pinterest.pinlater.backends.redis.RedisQueueMonitorTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    // If there is no local Redis, skip this test.
    Assume.assumeTrue(LocalRedisChecker.isRunning(REDIS_PORT));

    // If there is no local Redis, skip this test.
    Assume.assumeTrue(LocalRedisChecker.isRunning(REDIS_PORT));

    configuration = new PropertiesConfiguration();
    try {//from w ww .  j  a v a  2  s  .com
        configuration.load(ClassLoader.getSystemResourceAsStream("pinlater.redis.test.properties"));
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
    InputStream redisConfigStream = ClassLoader.getSystemResourceAsStream("redis.local.json");

    backend = new PinLaterRedisBackend(configuration, redisConfigStream, "localhost",
            System.currentTimeMillis());
}

From source file:dk.statsbiblioteket.util.i18n.BundleCache.java

/**
 * Create a bundle from the resource specified by {@code localeBundleName}
 * and cache it. Return a reference to the newly created bundle.
 *
 * @param localeBundleName the full resource name as returned by
 *                         {@link #getLocaleBundleName}
 * @return the newly created and cached bundle
 *///  w  ww  . java 2s  . com
private ResourceBundle createBundle(String localeBundleName) {
    if (log.isDebugEnabled()) {
        log.debug("Loading '" + localeBundleName + "'");
    }

    InputStream resourceStream = ClassLoader.getSystemResourceAsStream(localeBundleName);

    if (resourceStream == null) {
        throw new MissingResourceException("No such resource '" + localeBundleName + "'", localeBundleName, "");
    }
    try {
        // The Java 1.6 way is much nicer:
        //ResourceBundle bundle =
        //new PropertyResourceBundle(new InputStreamReader(resourceStream));
        ResourceBundle bundle = new PropertyResourceBundle(new EscapeUTF8Stream(resourceStream));
        cache.put(localeBundleName, bundle);
        return bundle;
    } catch (IOException e) {
        throw new MissingResourceException("Error reading resource '" + localeBundleName + "'",
                localeBundleName, "");
    }
}

From source file:hsa.awp.common.naming.DirectoryTest.java

/**
 * This procedure reads <code>fieldMapping</code> from the properties file
 * and reverses it. This is needed because the properties file is in the
 * format [fieldname]=[ldapname] (more convenient to configure) but we need
 * them in format [ldapname]=[fieldname].
 *
 * @param propertyFile - The properties file to read from.
 *//*from   ww w  .  j a  v  a  2 s. c om*/
private void setupFieldMapping(String propertyFile) {
    // loading the properties file in a temporary object
    Properties tmpProps = new Properties();
    try {
        InputStream in = ClassLoader.getSystemResourceAsStream(propertyFile);
        if (in == null) {
            throw new ConfigurationException("PorpertyFile " + propertyFile + " is not in CLASSPATH");
        }
        tmpProps.load(in);
    } catch (IOException e) {
        throw new ConfigurationException("Could not read configuration file: " + propertyFile, e);
    }

    // now we reverse the properties
    mapping = new Properties();
    for (Entry<Object, Object> currentEntry : tmpProps.entrySet()) {
        mapping.put(currentEntry.getValue(), currentEntry.getKey());
    }
}

From source file:com.pinterest.pinlater.backends.redis.RedisQueueMonitorTest.java

@Override
protected RedisQueueMonitor createQueueMonitor(long jobClaimedTimeoutMillis, long jobSucceededGCTimeoutMillis,
        long jobFailedGCTimeoutMillis) {
    HealthChecker dummyHealthChecker = new HealthChecker("pinlater_redis_test");
    dummyHealthChecker.addServer(LOCALHOST, REDIS_PORT, new DummyHeartBeater(true), 10, // consecutive failures
            10, // consecutive successes
            10, // ping interval secs
            true); // is live initially

    InputStream redisConfigStream = ClassLoader.getSystemResourceAsStream("redis.local.json");
    ImmutableMap<String, RedisPools> shardMap = RedisBackendUtils.buildShardMap(redisConfigStream,
            configuration);/*from w w w .  j  a va 2 s . c o m*/
    return new RedisQueueMonitor(shardMap, 1000, // update max size
            3, // auto retries
            1, // log interval
            jobClaimedTimeoutMillis, jobSucceededGCTimeoutMillis, jobFailedGCTimeoutMillis, 3, // max queue priority
            dummyHealthChecker);
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.parser.PrivateEc2TemplateParserTest.java

@Test
public void testVolumeTemplate() throws IOException, PrivateEc2ParserException {
    InputStream templateStream = ClassLoader.getSystemResourceAsStream("./cfn_templates/volume.template");
    PrivateEc2Template template = ParserUtils.mapJson(PrivateEc2Template.class, templateStream);
    assertNotNull(template);/*from w  w w.j av a  2 s.  c  om*/
    assertNotNull(template);
    assertNotNull(template.getEC2Instance());
    assertNotNull(template.getEC2Instance().getProperties());
    assertNotNull(template.getEC2Instance().getProperties().getVolumes());
    assertEquals(1, template.getEC2Instance().getProperties().getVolumes().size());
    assertNotNull(template.getEC2Instance().getProperties().getVolumes().get(0).getVolumeId());
    assertNotNull("smallVolume",
            template.getEC2Instance().getProperties().getVolumes().get(0).getVolumeId().getValue());
    assertNotNull(template.getEC2Volume("smallVolume"));

}

From source file:org.openengsb.openengsbplugin.tools.ToolsTest.java

@Test
public void testInsertDomNode() throws Exception {
    Document thePom = Tools.parseXMLFromString(
            IOUtils.toString(ClassLoader.getSystemResourceAsStream("licenseCheck/pass/pom.xml")));

    Document d = Tools.newDOM();//from   w  w w . j  ava 2s  .  c o  m
    Node nodeB = d.createElementNS(POM_NS_URI, "b");

    Node importedNode = thePom.importNode(nodeB, true);

    Tools.insertDomNode(thePom, importedNode, "/pom:project/pom:a", NS_CONTEXT);

    String serializedXml = Tools.serializeXML(thePom);
    File generatedFile = Tools.generateTmpFile(serializedXml, ".xml");

    Document generatedPom = Tools.parseXMLFromString(FileUtils.readFileToString(generatedFile));

    Node foundNode = Tools.evaluateXPath("/pom:project/pom:a/pom:b", generatedPom, NS_CONTEXT,
            XPathConstants.NODE, Node.class);

    assertNotNull(foundNode);
    assertTrue(generatedFile.delete());
}

From source file:com.impetus.client.cassandra.config.CassandraPropertyReaderTest.java

/**
 * Test method for/*w  ww. j  av a  2 s . c o m*/
 * {@link com.impetus.client.cassandra.config.CassandraPropertyReader#readProperty()}
 * .
 * 
 * @throws IOException
 */
@Test
public void testReadProperty() throws IOException {
    log.info("running CassandraPropertyReaderTest");
    // reader = new CassandraPropertyReader();
    // reader.read("CassandraCounterTest");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(pu);
    PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(pu);
    // metadata = CassandraPropertyReader.csmd;
    Properties properties = new Properties();
    InputStream inStream = ClassLoader
            .getSystemResourceAsStream(puMetadata.getProperty(PersistenceProperties.KUNDERA_CLIENT_PROPERTY));

    if (inStream != null) {
        properties.load(inStream);
        replication = properties.getProperty(Constants.REPLICATION_FACTOR);
        strategy = properties.getProperty(Constants.PLACEMENT_STRATEGY);
        String dataCenters = properties.getProperty(Constants.DATA_CENTERS);
        if (dataCenters != null) {
            StringTokenizer stk = new StringTokenizer(dataCenters, ",");
            while (stk.hasMoreTokens()) {
                StringTokenizer tokenizer = new StringTokenizer(stk.nextToken(), ":");
                if (tokenizer.countTokens() == 2) {
                    dataCenterToNode.put(tokenizer.nextToken(), tokenizer.nextToken());
                }
            }
        }

        String cf_defs = properties.getProperty(Constants.CF_DEFS);
        if (cf_defs != null) {
            StringTokenizer stk = new StringTokenizer(cf_defs, ",");
            while (stk.hasMoreTokens()) {
                CassandraColumnFamilyProperties familyProperties = new CassandraColumnFamilyProperties();
                StringTokenizer tokenizer = new StringTokenizer(stk.nextToken(), "|");
                if (tokenizer.countTokens() != 0 && tokenizer.countTokens() >= 2) {
                    String columnFamilyName = tokenizer.nextToken();
                    String defaultValidationClass = tokenizer.nextToken();
                    familyProperties.setDefault_validation_class(defaultValidationClass);

                    if (tokenizer.countTokens() != 0) {
                        String comparator = tokenizer.nextToken();

                        familyProperties.setComparator(comparator);

                    }
                    familyToProperties.put(columnFamilyName, familyProperties);
                }
            }
        }

        metadata = CassandraPropertyReader.csmd;
        if (replication != null) {
            Assert.assertNotNull(replication);
            Assert.assertNotNull(metadata.getReplication_factor());

        } else {
            Assert.assertNull(replication);
            Assert.assertNull(metadata.getReplication_factor());
        }
        Assert.assertEquals(replication, metadata.getReplication_factor());

        if (strategy != null) {
            Assert.assertNotNull(strategy);
            Assert.assertNotNull(metadata.getPlacement_strategy());

        } else {
            Assert.assertNull(strategy);
            Assert.assertNull(metadata.getPlacement_strategy());
        }
        Assert.assertEquals(strategy, metadata.getPlacement_strategy());

        if (!familyToProperties.isEmpty()) {
            Assert.assertNotNull(familyToProperties);
            Assert.assertNotNull(metadata.getColumnFamilyProperties());
            Assert.assertFalse(metadata.getColumnFamilyProperties().isEmpty());
        } else {
            Assert.assertTrue(metadata.getColumnFamilyProperties().isEmpty());
        }
        Assert.assertEquals(familyToProperties.size(), metadata.getColumnFamilyProperties().size());

        if (!dataCenterToNode.isEmpty()) {
            Assert.assertNotNull(dataCenterToNode);
            Assert.assertNotNull(metadata.getDataCenters());
            Assert.assertFalse(metadata.getDataCenters().isEmpty());
        } else {
            Assert.assertTrue(metadata.getDataCenters().isEmpty());
        }
        Assert.assertEquals(dataCenterToNode.size(), metadata.getDataCenters().size());
    } else {
        Assert.assertEquals("1", metadata.getReplication_factor());
        Assert.assertEquals(SimpleStrategy.class.getName(), metadata.getPlacement_strategy());
        Assert.assertEquals(0, metadata.getDataCenters().size());
        Assert.assertEquals(0, metadata.getColumnFamilyProperties().size());
    }
}

From source file:de.uzk.hki.da.sb.SIPFactoryTest.java

@Before
public void setUp() {

    new File(pathToResourcesFolder + "destination").mkdir();

    ProgressManager progressManager = mock(ProgressManager.class);

    sipFactory = new SIPFactory();
    sipFactory.setProgressManager(progressManager);
    sipFactory.setMessageWriter(cliMessageWriter);

    setUpLogger();//from w ww .  j  a  v a 2s.  c  o  m

    Properties properties = new Properties();
    try {
        properties.load(new InputStreamReader(
                (ClassLoader.getSystemResourceAsStream("configuration/config.properties"))));
    } catch (FileNotFoundException e1) {
        System.exit(Feedback.GUI_ERROR.toInt());
    } catch (IOException e2) {
        System.exit(Feedback.GUI_ERROR.toInt());
    }
    SIPBuilder.setProperties(properties);
}

From source file:com.github.jcooky.jaal.agent.bytecode.asm.ASM5InjectorTest.java

@Test
public void testInject() throws Throwable {
    InjectorStrategy is = new ProxyInjectorStrategy(new MethodCriteria() {
        @Override// w  w w.ja va2 s  . com
        public boolean isMatch(String className) {
            return true;
        }

        @Override
        public boolean isMatch(String className, String methodName, String signature, long modifiers) {
            return true;
        }
    }, TestFactory.class.getName());

    ASM5Injector injector = new ASM5Injector(is);

    Class<?> cls = classLoader.defineClass(injector.inject(IOUtils.toByteArray(
            ClassLoader.getSystemResourceAsStream(Target.class.getName().replace('.', '/') + ".class"))));

    Object self = cls.newInstance();
    cls.getMethod("methodTarget").invoke(self);

    InvocationHandler invocationHandler = TestFactory.getInvocationHandler();
    verify(invocationHandler).invoke(anyObject(), any(Method.class), any(Object[].class));
}

From source file:org.apache.james.http.jetty.JettyHttpServerFactoryTest.java

@Test
public void shouldThrowOnUnavailableServletName() throws Exception {
    HierarchicalConfiguration configuration = loadConfiguration(
            ClassLoader.getSystemResourceAsStream("unavailableservletname.xml"));
    assertThatThrownBy(() -> new JettyHttpServerFactory().createServers(configuration))
            .isInstanceOf(ConfigurationException.class);
}