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.pig.tools.DownloadResolver.java

private DownloadResolver() {
    if (System.getProperty("grape.config") != null) {
        LOG.info("Using ivysettings file from " + System.getProperty("grape.config"));
    } else {//from www .  jav a 2  s  .c om
        // Retrieve the ivysettings configuration file
        Map<String, String> envMap = System.getenv();
        File confFile = null;
        // Check for configuration file in PIG_CONF_DIR
        if (envMap.containsKey("PIG_CONF_DIR")) {
            confFile = new File(new File(envMap.get("PIG_CONF_DIR")).getPath(), IVY_FILE_NAME);
        }

        // Check for configuration file in PIG_HOME if not found in PIG_CONF_DIR
        if (confFile == null || !confFile.exists()) {
            confFile = new File(new File(envMap.get("PIG_HOME"), "conf").getPath(), IVY_FILE_NAME);
        }

        // Check for configuration file in Classloader if not found in PIG_CONF_DIR and PIG_HOME
        if (confFile == null || !confFile.exists()) {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader.getResource(IVY_FILE_NAME) != null) {
                LOG.info("Found ivysettings file in classpath");
                confFile = new File(classLoader.getResource(IVY_FILE_NAME).getFile());

                if (!confFile.exists()) {
                    // ivysettings file resides inside a jar
                    try {
                        List<String> ivyLines = IOUtils
                                .readLines(classLoader.getResourceAsStream(IVY_FILE_NAME));
                        confFile = File.createTempFile("ivysettings", ".xml");
                        confFile.deleteOnExit();
                        for (String str : ivyLines) {
                            FileUtils.writeStringToFile(confFile, str, true);
                        }
                    } catch (Exception e) {
                        LOG.warn("Could not create an ivysettings file from resource");
                    }
                }
            }
        }

        // Set the Configuration file
        if (confFile != null && confFile.exists()) {
            LOG.info("Using ivysettings file from " + confFile.toString());
            System.setProperty("grape.config", confFile.toString());
        } else {
            LOG.warn("Could not find custom ivysettings file in PIG_CONF_DIR or PIG_HOME or classpath.");
        }
    }
}

From source file:ResourceBundleSupport.java

/**
 * Returns the resource specified by the <strong>relative</strong> name.
 *
 * @param name the name of the resource relative to the given class
 * @param c    the source class//from   w w w .j av a2 s.c  o m
 * @return the url of the resource or null, if not found.
 */
public static URL getResourceRelative(final String name, final Class c) {
    final ClassLoader cl = getClassLoader(c);
    final String cname = convertName(name, c);
    if (cl == null) {
        return null;
    }
    return cl.getResource(cname);
}

From source file:jp.aegif.nemaki.util.impl.PropertyManagerImpl.java

/**
 * Override is not supported for update/*www  .  j a  v  a 2  s.com*/
 */
@Override
public void modifyValue(String key, String value) {
    config.setProperty(key, value);

    SolrResourceLoader loader = new SolrResourceLoader(null);
    ClassLoader classLoader = loader.getClassLoader();
    URL url = classLoader.getResource(propertiesFile);

    try {
        if (url == null) {
            config.store(new FileOutputStream(new File(loader.locateSolrHome() + "/conf/" + propertiesFile)),
                    null);
        } else {
            config.store(new FileOutputStream(new File(url.toURI())), null);
        }

    } catch (FileNotFoundException e) {
        // TODO ??? catch 
        e.printStackTrace();
    } catch (IOException e) {
        // TODO ??? catch 
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO ??? catch 
        e.printStackTrace();
    }

}

From source file:MenuItemChooser.java

private void loadMenuItem() {
    itemName.setText(items[currMenuItem].name);
    itemType.setText(items[currMenuItem].type);
    price.setText(new Integer(items[currMenuItem].price).toString());
    qty.setText(new Integer(items[currMenuItem].qtyOrdered).toString());
    ClassLoader cl = this.getClass().getClassLoader();
    Icon menuItemIcon = new ImageIcon(cl.getResource(items[currMenuItem].imagePath));
    image.setIcon(menuItemIcon);//from ww w  .j a  va2  s .c  o  m
    desc.setText(items[currMenuItem].desc);
}

From source file:com.sastix.cms.server.services.cache.CacheServiceTest.java

@Before
public void setUp() throws IOException {
    ClassLoader classLoader = getClass().getClassLoader();
    Path path = Paths.get(classLoader.getResource("logo.png").getFile());
    bytesToBeCached = Files.readAllBytes(path);
}

From source file:com.flexive.testRunner.FxTestRunnerThread.java

/**
 * {@inheritDoc}//  w w w  . j a v a2  s. c o m
 */
@Override
public void run() {
    synchronized (lock) {
        if (testInProgress)
            return;
        testInProgress = true;
    }
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL jar = cl.getResource("lib/flexive-tests.jar");

        //build a list of all test classes
        List<Class> testClasses = new ArrayList<Class>(100);
        try {
            JarInputStream jin = new JarInputStream(jar.openStream());
            while (jin.available() != 0) {
                JarEntry je = jin.getNextJarEntry();
                if (je == null)
                    continue;

                final String name = je.getName();
                //only classes, no inner classes, abstract or mock classes
                if (name.endsWith(".class") && !(name.indexOf('$') > 0) && !(name.indexOf("Abstract") > 0)
                        && !(name.indexOf("Mock") > 0)) {
                    boolean ignore = false;
                    //check ignore package
                    for (String pkg : FxTestRunner.ignorePackages)
                        if (name.indexOf(pkg) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String className = name.substring(name.lastIndexOf('/') + 1);
                    //check ignore classes
                    for (String cls : FxTestRunner.ignoreTests)
                        if (className.indexOf(cls) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String fqn = name.replaceAll("\\/", ".").substring(0, name.lastIndexOf('.'));
                    try {
                        testClasses.add(Class.forName(fqn));
                    } catch (ClassNotFoundException e) {
                        LOG.error("Could not find test class: " + fqn);
                    }
                }
            }
        } catch (IOException e) {
            LOG.error(e);
        }
        TestNG testng = new TestNG();
        testng.setTestClasses(testClasses.toArray(new Class[testClasses.size()]));
        // skip.ear groups have to be excluded, else tests that include these will be skipped as well (like ContainerBootstrap which is needed)
        testng.setExcludedGroups("skip.ear");
        System.setProperty("flexive.tests.ear", "1");
        TestListenerAdapter tla = new TestListenerAdapter();
        testng.addListener(tla);

        if (callback != null) {
            FxTestRunnerListener trl = new FxTestRunnerListener(callback);
            testng.addListener(trl);
        }

        testng.setThreadCount(4);
        testng.setVerbose(0);
        testng.setDefaultSuiteName("EARTestSuite");
        testng.setOutputDirectory(outputPath);
        if (callback != null)
            callback.resetTestInfo();
        try {
            testng.run();
        } catch (Exception e) {
            LOG.error(e);
            new FxFacesMsgErr("TestRunner.err.testNG", e.getMessage()).addToContext();
        }
        if (callback != null) {
            callback.setRunning(false);
            callback.setResultsAvailable(true);
        }
    } finally {
        synchronized (lock) {
            testInProgress = false;
        }
    }
}

From source file:com.puppycrawl.tools.checkstyle.api.LocalizedMessageTest.java

@Test
public void testBundleReloadUrlNotNullStreamNull() throws IOException {

    ClassLoader classloader = mock(ClassLoader.class);
    String resource = "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties";

    URL url = getMockUrl(null);/*  w  w w  .  j  a v  a 2 s.  c o  m*/
    when(classloader.getResource(resource)).thenReturn(url);

    LocalizedMessage.UTF8Control control = new LocalizedMessage.UTF8Control();
    control.newBundle("com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH, "java.class",
            classloader, true);
}

From source file:org.apache.hadoop.realtime.client.DragonClient.java

private static String getTestRuntimeClasspath() {

    InputStream classpathFileStream = null;
    BufferedReader reader = null;
    String envClassPath = "";

    LOG.info("Trying to generate classpath for app master from current thread's classpath");
    try {/* w  w w .jav  a2s.com*/

        // Create classpath from generated classpath
        // Check maven ppom.xml for generated classpath info
        // Works if compile time env is same as runtime. Mainly tests.
        ClassLoader thisClassLoader = Thread.currentThread().getContextClassLoader();
        String generatedClasspathFile = "yarn-apps-ds-generated-classpath";
        classpathFileStream = thisClassLoader.getResourceAsStream(generatedClasspathFile);
        if (classpathFileStream == null) {
            LOG.info("Could not classpath resource from class loader");
            return envClassPath;
        }
        LOG.info("Readable bytes from stream=" + classpathFileStream.available());
        reader = new BufferedReader(new InputStreamReader(classpathFileStream));
        String cp = reader.readLine();
        if (cp != null) {
            envClassPath += cp.trim() + ":";
        }
        // Put the file itself on classpath for tasks.
        envClassPath += thisClassLoader.getResource(generatedClasspathFile).getFile();
    } catch (IOException e) {
        LOG.info("Could not find the necessary resource to generate class path for tests. Error="
                + e.getMessage());
    }

    try {
        if (classpathFileStream != null) {
            classpathFileStream.close();
        }
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        LOG.info("Failed to close class path file stream or reader. Error=" + e.getMessage());
    }
    return envClassPath;
}

From source file:io.vertx.lang.js.JSVerticleFactory.java

private boolean isNodeJS(ClassLoader loader) {
    URL url = loader.getResource("package.json");
    if (url == null)
        return false;
    else if (hasNodeModules(url) || hasEngines(loader)) {
        try {/*from   w  w  w.java 2 s.c  om*/
            ClasspathFileResolver.unzip(url);
        } catch (IOException ex) {
            return false;
        }
        return true;
    } else
        return false;
}

From source file:jp.aegif.nemaki.util.impl.PropertyManagerImpl.java

/**
 * Override is not supported for update/*  w  ww . ja  v a 2 s.com*/
 */
@Override
public void addValue(String key, String value) {
    String currentVal = config.getProperty(key);
    String[] currentVals = (StringUtils.isEmpty(currentVal)) ? new String[0] : currentVal.split(",");
    List<String> valList = new ArrayList<String>();
    Collections.addAll(valList, currentVals);

    valList.add(0, value);
    String newVal = StringUtils.join(valList.toArray(), ",");
    config.setProperty(key, newVal);

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URL url = classLoader.getResource(propertiesFile);
    try {
        config.store(new FileOutputStream(new File(url.toURI())), null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}