Example usage for java.lang ClassLoader getSystemResource

List of usage examples for java.lang ClassLoader getSystemResource

Introduction

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

Prototype

public static URL getSystemResource(String name) 

Source Link

Document

Find a resource of the specified name from the search path used to load classes.

Usage

From source file:de.decoit.simu.cbor.xml.dictionary.DictionaryTest.java

@Test
public void testReplaceDictionary() throws Exception {
    DictionaryNamespace dns = new DictionaryNamespace("dummy-namespace-uri", new UnsignedInteger(20));
    Path input = Paths.get(ClassLoader.getSystemResource("namespace-with-simple-elements.dict").toURI());

    Dictionary instance = new Dictionary();

    assertTrue(instance.getUnmodifiableNamespaces().isEmpty());

    instance.addNamespace(dns);// w w  w .  j  ava  2s.  c o  m

    instance.replaceDictionary(input);

    assertNull(instance.lookupNamespace("dummy-namespace-uri"));
    assertNotNull(instance.lookupNamespace("http://www.trustedcomputinggroup.org/2010/IFMAP/2"));
    assertNotNull(instance.lookupNamespace("http://www.trustedcomputinggroup.org/2010/IFMAP/2")
            .lookupElement("access-request"));
}

From source file:hudson.plugins.doclinks.artifacts.testtools.TestZipBuilder.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    FilePath file = build.getWorkspace().child(filename);
    FilePath dir = file.getParent();/*www.  j  a  va  2s.  co m*/

    if (dir != null && !dir.exists()) {
        dir.mkdirs();
    }

    String seperator = System.getProperty("file.separator");
    String resourceDirName = StringUtils.join(getClass().getName().split("\\."), seperator);
    File resourceDir = null;
    try {
        resourceDir = new File(ClassLoader.getSystemResource(resourceDirName).toURI());
    } catch (URISyntaxException e) {
        listener.getLogger().println("Failed to retrieve contents to zip");
        e.printStackTrace(listener.getLogger());
    }

    OutputStream os = null;
    ZipOutputStream zos = null;

    try {
        os = file.write();
        zos = new ZipOutputStream(os);

        compress(zos, resourceDir, null);
    } finally {
        if (zos != null) {
            zos.close();
        }

        if (os != null) {
            os.close();
        }
    }

    return true;
}

From source file:org.opennms.xmlclient.ClientPropertiesLoader.java

private void loadProperties() {
    properties = new Properties();
    try {//from   w  w  w.j a va 2s  . com

        // try to Load from the startup directory of application (ex. directory containing the jar) 
        String p = getClass().getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
        path = "/" + p.substring(0, p.lastIndexOf("/"));

        java.io.File propfile = new java.io.File(path + "/" + propertiesFilename);
        if (propfile.exists()) {
            log.debug("PropertiesLoader() Trying to load properties file '" + propertiesFilename
                    + "' from directory path:" + path);
            java.io.FileInputStream fis = new java.io.FileInputStream(propfile);
            properties.load(fis);
        } else {
            // try to load from class path 
            log.debug("PropertiesLoader() Properties file not in directory path:'" + path
                    + "' Loading properties file '" + propertiesFilename + "' from classpath");
            URL url = ClassLoader.getSystemResource(propertiesFilename);
            properties.load(url.openStream());
        }

        if (properties.getProperty("opennmsUrl") != null) {
            opennmsUrl = properties.getProperty("opennmsUrl");
        } else
            log.error("PropertiesLoader() 'opennmsUrl' property does not exist in '" + propertiesFilename
                    + "' file. Using default value.");

        if (properties.getProperty("username") != null) {
            username = properties.getProperty("username");
        } else
            log.error("PropertiesLoader() 'username' property does not exist in '" + propertiesFilename
                    + "' file. Using default value.");

        if (properties.getProperty("password") != null) {
            password = properties.getProperty("password");
        } else
            log.error("PropertiesLoader() 'password' property does not exist in '" + propertiesFilename
                    + "' file. Using default value.");

        if (properties.getProperty("foreign_source") != null) {
            foreign_source = properties.getProperty("foreign_source");
        } else
            log.error("PropertiesLoader() 'foreign_source' property does not exist in '" + propertiesFilename
                    + "' file. Using default value.");

    } catch (Throwable e) {
        log.error("PropertiesLoader() unable to load '" + propertiesFilename
                + "' file from classpath or file path '" + path + "'. Using default properties. ");
    }
    log.info("PropertiesLoader() using properties: foreign_source='" + foreign_source + "', opennmsUrl='"
            + opennmsUrl + "', username='" + username + "', password='" + password + "'");
}

From source file:org.jboss.pressgang.ccms.contentspec.client.commands.SetupCommandTest.java

@Before
public void setUp() {
    bindStdOut();//w  w  w  .  j av a 2  s.  com
    command = new SetupCommand(parser, cspConfig, clientConfig);

    rootTestDirectory = FileUtils.toFile(ClassLoader.getSystemResource(""));
}

From source file:org.apache.james.jmap.json.ParsingWritingObjectsTest.java

@Test
public void writingJsonShouldWorkOnSubMessage() throws Exception {
    String expected = IOUtils.toString(ClassLoader.getSystemResource("json/subMessage.json"));

    String json = testee.forWriting().writeValueAsString(SUB_MESSAGE);

    assertThatJson(json).when(IGNORING_ARRAY_ORDER).isEqualTo(expected);

}

From source file:org.n52.sir.IT.ValidatorBindingIT.java

@Test
public void readInValidSensorMLAndValidate() throws IOException {
    File f = new File(ClassLoader.getSystemResource("Requests/testSensor.xml").getFile());
    BufferedReader reader = new BufferedReader(new FileReader(f));
    String s = null;//  w  w  w .ja  v a  2 s .  c  o  m
    StringBuilder builder = new StringBuilder();
    while ((s = reader.readLine()) != null)
        builder.append(s);
    String sensorML = builder.toString();
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/api/check/sensorML");
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    pairs.add(new BasicNameValuePair("sensor", sensorML));
    pairs.add(new BasicNameValuePair("format", "json"));
    post.setEntity(new UrlEncodedFormEntity(pairs));

    HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    StringBuilder result = new StringBuilder();
    reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    while ((s = reader.readLine()) != null)
        result.append(s);
    System.out.println(result.toString());
    StatusResponse sr = new Gson().fromJson(result.toString(), StatusResponse.class);
    assertEquals("invalid", sr.status);
}

From source file:com.cloud.consoleproxy.ConsoleProxy.java

private static void configLog4j() {
    URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
    if (configUrl == null)
        configUrl = ClassLoader.getSystemResource("log4j-cloud.xml");

    if (configUrl == null)
        configUrl = ClassLoader.getSystemResource("conf/log4j-cloud.xml");

    if (configUrl != null) {
        try {//from   ww  w .ja  v a 2  s.  c o  m
            System.out.println("Configure log4j using " + configUrl.toURI().toString());
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }

        try {
            File file = new File(configUrl.toURI());

            System.out.println("Log4j configuration from : " + file.getAbsolutePath());
            DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
        } catch (URISyntaxException e) {
            System.out.println("Unable to convert log4j configuration Url to URI");
        }
        // DOMConfigurator.configure(configUrl);
    } else {
        System.out.println("Configure log4j with default properties");
    }
}

From source file:com.baidu.rigel.biplatform.parser.util.PropertiesUtil.java

public static Properties loadPropertiesFromFile(String file) throws IOException {
    String location = file;//w ww .j  a  v a 2 s  .  c om
    if (StringUtils.isBlank(location)) {
        throw new IllegalArgumentException("file can not be blank.");
    }
    Properties properties = new Properties();

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

    URL url = classLoaderToUse != null ? classLoaderToUse.getResource(location)
            : ClassLoader.getSystemResource(location);

    URLConnection con = url.openConnection();
    InputStream is = con.getInputStream();
    try {
        if (location != null && location.endsWith(".xml")) {
            properties.loadFromXML(is);
        } else {
            properties.load(is);
        }
    } finally {
        IOUtils.close(con);
        IOUtils.closeQuietly(is);
    }

    return properties;
}

From source file:edu.ksu.cis.indus.tools.slicer.SlicerToolHelper.java

/**
 * Loads the configuration in the named file.
 * /* w  w  w .  jav a  2  s  .c o m*/
 * @param configFileName is the name of the configuration file to load; if this is <code>null</code> then the default
 *            configuration file will be loaded.
 * @return the configuration as stored in the named file.
 * @throws IllegalStateException if the named file or the default file cannot be found (in that order) or when there is an
 *             while operating on the file.
 */
public static String loadConfigurationInFile(final String configFileName) {
    InputStream _inStream = null;
    String _result = null;
    final URL _filename;

    if (configFileName == null) {
        LOGGER.warn("Trying to use default configuration.");
        _filename = ClassLoader
                .getSystemResource("edu/ksu/cis/indus/tools/slicer/default_slicer_configuration.xml");
    } else {
        try {
            _filename = new File(configFileName).toURI().toURL();
        } catch (final MalformedURLException _e) {
            LOGGER.warn("The specified path " + configFileName + " does not exist.");
            throw new IllegalArgumentException("The specified path is invalid. - " + configFileName, _e);
        }
    }

    try {
        _inStream = _filename.openStream();
        _result = IOUtils.toString(_inStream);
    } catch (final IOException _e2) {
        LOGGER.error("Could not retrieve a handle to configuration file or an ."
                + "IO error while reading configuration file. ", _e2);
        throw new IllegalStateException(_e2);
    } finally {
        IOUtils.closeQuietly(_inStream);
    }
    return _result;
}

From source file:com.brightcove.test.upload.BatchIntegrationTest.java

private static File findFileInClasspath(String pFileName) throws URISyntaxException {
    URL url = ClassLoader.getSystemResource(pFileName);
    if (url == null) {
        return null;
    }//from  w  w  w . ja  v  a  2  s .  c om
    return new File(url.toURI());

}