Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

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

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Parameterized.Parameters
public static Collection<Object[]> data() {
    final Configuration config = getBaseConfig();

    final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    final String truststorePath = new File(classLoader.getResource("local127.truststore").getFile())
            .getAbsolutePath();//from  w  w w  . j  a va2s.  c o m
    final String keystorePath = new File(classLoader.getResource("local127.keystore").getFile())
            .getAbsolutePath();

    final Configuration sslConfig = new Configuration(config);
    sslConfig.setBoolean(SecurityOptions.SSL_REST_ENABLED, true);
    sslConfig.setString(SecurityOptions.SSL_REST_TRUSTSTORE, truststorePath);
    sslConfig.setString(SecurityOptions.SSL_REST_TRUSTSTORE_PASSWORD, "password");
    sslConfig.setString(SecurityOptions.SSL_REST_KEYSTORE, keystorePath);
    sslConfig.setString(SecurityOptions.SSL_REST_KEYSTORE_PASSWORD, "password");
    sslConfig.setString(SecurityOptions.SSL_REST_KEY_PASSWORD, "password");

    final Configuration sslRestAuthConfig = new Configuration(sslConfig);
    sslRestAuthConfig.setBoolean(SecurityOptions.SSL_REST_AUTHENTICATION_ENABLED, true);

    return Arrays.asList(new Object[][] { { config }, { sslConfig }, { sslRestAuthConfig } });
}

From source file:pt.webdetails.cdv.bean.factory.CoreBeanFactory.java

protected ConfigurableApplicationContext getSpringBeanFactory(String config) {
    try {//from w  w w .  ja  va 2 s . co  m
        final ClassLoader cl = this.getClass().getClassLoader();
        URL url = cl.getResource(config);
        if (url != null) {
            logger.debug("Found spring file @ " + url); //$NON-NLS-1$
            return new ClassPathXmlApplicationContext(config) {
                @Override
                protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {

                    beanDefinitionReader.setBeanClassLoader(cl);
                }

                @Override
                protected void prepareBeanFactory(ConfigurableListableBeanFactory clBeanFactory) {
                    super.prepareBeanFactory(clBeanFactory);
                    clBeanFactory.setBeanClassLoader(cl);
                }

                /**
                 * Critically important to override this and return the desired
                 * CL
                 **/
                @Override
                public ClassLoader getClassLoader() {
                    return cl;
                }
            };
        }
    } catch (Exception e) {
        logger.fatal("Error loading " + CDV_SPRING_BEAN, e);
    }
    logger.fatal(
            "Spring definition file does not exist. There should be a <plugin_name>.spring.xml file on the classpath ");
    return null;
}

From source file:com.arsdigita.util.parameter.ResourceParameter.java

protected Object unmarshal(String value, final ErrorList errors) {
    File file = new File(value);

    if (!file.exists()) {
        // it is not a standard file so lets try to see if it
        // is a resource
        if (value.startsWith("/")) {
            value = value.substring(1);//  w  w w.  ja v a  2  s  . co  m
        }

        ClassLoader cload = Thread.currentThread().getContextClassLoader();
        URL url = cload.getResource(value);
        InputStream stream = cload.getResourceAsStream(value);
        if (stream == null && isRequired()) {
            s_log.error(value + " is not a valid file and is required");

            final ParameterError error = new ParameterError(this, "Resource not found");
            errors.add(error);
        }
        return stream;
    } else {
        try {
            return new FileInputStream(file);
        } catch (FileNotFoundException ioe) {
            // we know the file exists so this should not
            // be an issue
            s_log.error(value + " is not a valid file and is required", ioe);

            errors.add(new ParameterError(this, ioe));

            return null;
        }
    }
}

From source file:com.iata.ndc.trial.controllers.DefaultController.java

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws JAXBException, ClientProtocolException, ClientException, IOException {

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("AirShopping.xml").getFile());
    JAXBContext jaxbContext = JAXBContext.newInstance(AirShoppingRQ.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    AirShoppingRQ request = (AirShoppingRQ) jaxbUnmarshaller.unmarshal(file);
    NdcClient client = new NdcClient("http://iata.api.mashery.com/athena/api", "jhttds6eh5bgq92zvqnruehx");
    List<FlightConnection> response = new AirShoppingResonseMapper()
            .mapAirShoppingResponse(client.airShopping(request));

    return "index";
}

From source file:com.yahoo.ads.pb.util.LoggingConfigure.java

@Override
public void resetConfiguration() {
    ClassLoader cl = getClass().getClassLoader();
    LogManager.resetConfiguration();
    URL log4jprops = cl.getResource("log4j.properties");
    if (log4jprops != null) {
        PropertyConfigurator.configure(log4jprops);
    }//from   w  ww. ja  v  a  2 s.  c om
}

From source file:gate.util.Files.java

/**
 * Get a resource from the GATE ClassLoader.  The return value is a
 * {@link java.net.URL} that can be used to retrieve the contents of the
 * resource./*  www  .ja v a2s  . c  o  m*/
 */
public static URL getResource(String resourceName) {
    // Strip any leading '/'
    if (resourceName.charAt(0) == '/') {
        resourceName = resourceName.substring(1);
    }

    ClassLoader gcl = Gate.getClassLoader();
    if (gcl == null) {
        // if the GATE ClassLoader has not been initialised yet (i.e. this
        // method was called before Gate.init) then fall back to the current
        // classloader
        return Files.class.getClassLoader().getResource(resourceName);
    } else {
        // if we can, get the resource through the GATE ClassLoader to allow
        // loading of resources from plugin JARs as well as gate.jar
        return gcl.getResource(resourceName);
    }
}

From source file:io.servicecomb.config.archaius.sources.TestYAMLConfigurationSource.java

@Test
public void testPullFroGivenURL() throws Exception {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL test1URL = loader.getResource("test1.yaml");
    URL test2URL = loader.getResource("test2.yaml");
    System.setProperty("cse.configurationSource.additionalUrls",
            test1URL.toString() + "," + test2URL.toString());
    MicroserviceConfigurationSource configSource = yamlConfigSource();
    PollResult result = configSource.poll(true, null);
    Map<String, Object> configMap = result.getComplete();

    assertEquals(3, configSource.getConfigModels().size());
    assertNotNull(configMap);//from  w  ww  .  ja  va  2  s . c  om
    assertEquals(31, configMap.size());
    assertNotNull(configMap.get("trace.handler.sampler.percent"));
    assertEquals(0.5, configMap.get("trace.handler.sampler.percent"));

    System.getProperties().remove("cse.configurationSource.additionalUrls");
}

From source file:com.baeldung.file.FileOperationsTest.java

@Test
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
    String expectedData = "Hello World from fileTest.txt!!!";

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("fileTest.txt").getFile());
    String data = FileUtils.readFileToString(file);

    Assert.assertEquals(expectedData, data.trim());
}

From source file:org.ambraproject.configuration.ConfigurationTest.java

protected void setUp() throws ConfigurationException {
    ConfigurationStore store = ConfigurationStore.getInstance();
    ClassLoader loader = getClass().getClassLoader();

    log.debug("Log file location: {}", loader.getResource("").getFile());

    System.setProperty(ConfigurationStore.JOURNAL_TEMPLATE_DIR, loader.getResource("").getFile());
    store.loadConfiguration(loader.getResource("ambra/configuration/defaults-dev.xml"));

    conf = store.getConfiguration();//from www.ja  va 2s .  c  o  m
    /*
     * We want to use a test version of global-defaults.
     * However there is no way to override it. So we add this
     * at the end (last place looked).
     */
    ConfigurationStore.addResources((CombinedConfiguration) conf,
            "/ambra/configuration/global-defaults-test.xml");
}

From source file:com.baeldung.file.FileOperationsTest.java

@Test
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
    String expectedData = "Hello World from fileTest.txt!!!";

    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("fileTest.txt").getFile());
    InputStream inputStream = new FileInputStream(file);
    String data = readFromInputStream(inputStream);

    Assert.assertEquals(expectedData, data.trim());
}