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:edu.cornell.med.icb.io.ResourceFinder.java

/**
 * Search for a resource using the thread context class loader. If that fails, search
 * using the class loader that loaded this class.  If that still fails, try one last
 * time with {@link ClassLoader#getSystemResource(String)}.
 * @param resource The resource to search for
 * @return A url representing the resource or {@code null} if the resource was not found
 *///from w  w  w .j  a v a  2 s. co  m
private URL resourceToUrl(final String resource) {
    URL url; // get the configuration from the classpath of the current thread
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Trying to find [" + resource + "] using context class loader " + loader);
    }
    url = loader.getResource(resource);

    if (url == null) {
        // We couldn't find resource - now try with the class loader that loaded this class
        loader = ResourceFinder.class.getClassLoader(); // NOPMD
        if (LOG.isDebugEnabled()) {
            LOG.debug("Trying to find [" + resource + "] using class loader " + loader);
        }
        url = loader.getResource(resource);
    }

    if (url == null) {
        // make a last attempt to get the resource from the system class loader
        if (LOG.isDebugEnabled()) {
            LOG.debug("Trying to find [" + resource + "] using system class loader");
        }
        url = ClassLoader.getSystemResource(resource);
    }
    if (url != null && LOG.isDebugEnabled()) {
        LOG.debug("... found url is [" + url.toString() + "]");
    }
    return url;
}

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

@Test
public void testFindElementByPath_NotExistentElement() throws Exception {
    Path input = Paths.get(ClassLoader.getSystemResource("namespace-with-complex-elements.dict").toURI());

    Dictionary instance = new Dictionary();
    instance.extendDictionary(input);/*from   w  w w.  j  a v  a 2 s.c o  m*/

    String dictPath = "<http://www.trustedcomputinggroup.org/2010/IFMAP/2>access-request+nested-element-dummy";

    DictionarySimpleElement result = instance.findElementByPath(dictPath);

    assertNull(result);
}

From source file:com.aol.advertising.qiao.util.CommonUtils.java

public static Properties loadProperties(String propFile) throws IOException {
    Properties p = new Properties();
    URL url = ClassLoader.getSystemResource(propFile);
    if (url != null)
        p.load(url.openStream());/*from  w ww. j  a  v  a2  s.co  m*/
    return p;
}

From source file:org.wte4j.impl.WordTemplateTest.java

private void checkUpdateContent(WordTemplate<?> wordTemplate, User user, String fileName) throws IOException {
    File file = FileUtils.toFile(ClassLoader.getSystemResource(fileName));

    byte[] expectedContent = FileUtils.readFileToByteArray(file);
    byte[] currentContent = wordTemplate.getPersistentData().getContent();

    assertTrue(Arrays.equals(expectedContent, currentContent));
    assertEquals(user, wordTemplate.getEditor());
    assertNotNull(wordTemplate.getEditedAt());
}

From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationManagerTest.java

/**
 * Make sure the consumer of the mappings is aware that mappings same
 * columns to different methods will not work.
 *///from  w w  w  . j  a v a2s . c  o m
@Test
public void testMappingUniqueness() {
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("ColumnA is mapped more than once to non-unique methods.");

    final String fullLocation = ClassLoader.getSystemResource(testFileDuplicateMappings).getFile();

    // Use a throw away CM to not dirty up other tests.
    final TestProtexConfigurationManager protexCM = new TestProtexConfigurationManager(fullLocation);
    protexCM.getMappings();
}

From source file:org.lockss.crawljax.TestRequestResponse.java

private URL getResource0(String resource) {

    URL url;// www.  j  av a 2s.co m

    //Try with the Thread Context Loader.
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        url = classLoader.getResource(resource);
        if (url != null) {
            return url;
        }
    }

    //Let's now try with the classloader that loaded this class.
    classLoader = this.getClass().getClassLoader();
    if (classLoader != null) {
        url = classLoader.getResource(resource);
        if (url != null) {
            return url;
        }
    }

    //Last ditch attempt. Get the resource from the classpath.
    return ClassLoader.getSystemResource(resource);
}

From source file:org.apache.james.mailbox.elasticsearch.json.MailboxMessageToElasticSearchJsonTest.java

@Test
public void simpleEmailShouldBeWellConvertedToJson() throws IOException {
    MessageToElasticSearchJson messageToElasticSearchJson = new MessageToElasticSearchJson(
            new DefaultTextExtractor(), ZoneId.of("Europe/Paris"));
    MailboxMessage mail = new SimpleMailboxMessage(date, SIZE, BODY_START_OCTET,
            new SharedByteArrayInputStream(
                    IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("eml/mail.eml"))),
            new FlagsBuilder().add(Flags.Flag.DELETED, Flags.Flag.SEEN).add("debian", "security").build(),
            propertyBuilder, MAILBOX_ID);
    mail.setModSeq(MOD_SEQ);//from w w  w .jav  a 2 s .  c om
    mail.setUid(UID);
    assertThatJson(messageToElasticSearchJson.convertToJson(mail,
            ImmutableList.of(new MockMailboxSession("user1").getUser(),
                    new MockMailboxSession("user2").getUser()))).when(IGNORING_ARRAY_ORDER)
                            .when(IGNORING_VALUES)
                            .isEqualTo(IOUtils.toString(ClassLoader.getSystemResource("eml/mail.json")));
}

From source file:org.apache.james.jmap.utils.JsoupHtmlTextExtractorTest.java

@Test
public void toPlainTextShouldWorkWithMoreComplexHTML() throws Exception {
    String html = IOUtils.toString(ClassLoader.getSystemResource("example.html"), StandardCharsets.UTF_8);
    String expectedPlainText = "\n" + "    Why a new Logo?\n" + "\n" + "\n"
            + "    We are happy with our current logo, but for the\n"
            + "        upcoming James Server 3.0 release, we would like to\n"
            + "        give our community the opportunity to create a new image for James.\n" + "\n" + "\n"
            + "\n" + "\n" + "    Don't be shy, take your inkscape and gimp, and send us on\n"
            + "        the James Server User mailing list\n"
            + "        your creations. We will publish them on this page.\n" + "\n" + "\n" + "\n" + "\n"
            + "    We need an horizontal logo (100p height) to be show displayed on the upper\n"
            + "        left corner of this page, an avatar (48x48p) to be used on a Twitter stream for example.\n"
            + "        The used fonts should be redistributable (or commonly available on Windows and Linux).\n"
            + "        The chosen logo should be delivered in SVG format.\n"
            + "        We also like the Apache feather.\n" + "\n" + "\n" + "\n";
    assertThat(textExtractor.toPlainText(html)).isEqualTo(expectedPlainText);
}

From source file:org.kontalk.view.Utils.java

static Image getImage(String fileName) {
    URL imageUrl = ClassLoader.getSystemResource(Kontalk.RES_PATH + fileName);
    if (imageUrl == null) {
        LOGGER.warning("can't find icon image resource");
        return new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    }/*from  w w w .j ava 2s. co m*/
    return Toolkit.getDefaultToolkit().createImage(imageUrl);
}

From source file:org.walkmod.conf.providers.XMLConfigurationProvider.java

/**
 * Load the XML configuration on memory as a DOM structure with SAX.
 * Additional information about elements location is added. Non valid DTDs
 * or XML structures are detected./*from ww  w .  j av  a  2 s. co m*/
 * 
 * @param file
 *            XML configuration
 * @return XML tree
 */
private Document loadDocument(String file) {
    Document doc = null;
    URL url = null;
    File f = new File(file);
    if (f.exists()) {
        try {
            url = f.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new ConfigurationException("Unable to load " + file, e);
        }
    }
    if (url == null) {
        url = ClassLoader.getSystemResource(file);
    }
    InputStream is = null;
    if (url == null) {
        if (errorIfMissing) {
            throw new ConfigurationException("Could not open files of the name " + file);
        } else {
            LOG.info("Unable to locate configuration files of the name " + file + ", skipping");
            return doc;
        }
    }
    try {
        is = url.openStream();
        InputSource in = new InputSource(is);
        in.setSystemId(url.toString());
        doc = DomHelper.parse(in, dtdMappings);
    } catch (Exception e) {
        throw new ConfigurationException("Unable to load " + file, e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            LOG.error("Unable to close input stream", e);
        }
    }
    if (doc != null) {
        LOG.debug("Wallmod configuration parsed");
    }
    return doc;
}