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:org.apache.pig.test.TestGrunt.java

public void testRegisterWithoutQuotes() throws Throwable {
    PigServer server = new PigServer(ExecType.MAPREDUCE, cluster.getProperties());
    PigContext context = server.getPigContext();

    String strCmd = "register pig-withouthadoop.jar\n";

    ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
    InputStreamReader reader = new InputStreamReader(cmd);

    Grunt grunt = new Grunt(new BufferedReader(reader), context);

    grunt.exec();/* w ww .  j  a  v a 2s.  c  o  m*/
    assertTrue(context.extraJars.contains(ClassLoader.getSystemResource("pig-withouthadoop.jar")));
}

From source file:org.apache.pig.test.TestPigRunner.java

@Test
public void testRegisterExternalJar() throws Exception {
    String jarName = Util.findPigJarName();

    String[] args = { "-Dpig.additional.jars=" + jarName, "-Dmapred.job.queue.name=default", "-x", execType,
            "-e", "A = load '" + INPUT_FILE + "';store A into '" + OUTPUT_FILE + "';\n" };
    PigStats stats = PigRunner.run(args, new TestNotificationListener(execType));

    Util.deleteFile(cluster, OUTPUT_FILE);
    PigContext ctx = stats.getPigContext();

    assertNotNull(ctx);/*from   www  .  j  a v a 2s.  c  o m*/

    assertTrue(ctx.extraJars.contains(ClassLoader.getSystemResource(jarName)));
    assertTrue("default",
            ctx.getProperties().getProperty(MRConfiguration.JOB_QUEUE_NAME) != null
                    && ctx.getProperties().getProperty(MRConfiguration.JOB_QUEUE_NAME).equals("default")
                    || ctx.getProperties().getProperty("mapreduce.job.queuename") != null
                            && ctx.getProperties().getProperty("mapreduce.job.queuename").equals("default"));

}

From source file:org.glowroot.agent.weaving.ClassAnalyzer.java

private static List<AnalyzedMethodKey> getNonAbstractMethods(String className, @Nullable ClassLoader loader)
        throws ClassNotFoundException, IOException {
    String path = ClassNames.toInternalName(className) + ".class";
    URL url;/*from www .  j  a va 2s.  com*/
    if (loader == null) {
        // null loader means the bootstrap class loader
        url = ClassLoader.getSystemResource(path);
    } else {
        url = loader.getResource(path);
    }
    if (url == null) {
        // what follows is just a best attempt in the sort-of-rare case when a custom class
        // loader does not expose .class file contents via getResource(), e.g.
        // org.codehaus.groovy.runtime.callsite.CallSiteClassLoader
        return getNonAbstractMethodsPlanB(className, loader);
    }
    byte[] bytes = Resources.toByteArray(url);
    NonAbstractMethodClassVisitor accv = new NonAbstractMethodClassVisitor();
    new ClassReader(bytes).accept(accv, ClassReader.SKIP_FRAMES + ClassReader.SKIP_CODE);
    return accv.analyzedMethodKeys;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*from w w  w . java2  s  .  co m*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:org.commoncrawl.io.internal.NIODNSCache.java

@Test
public void validateTrieCode() throws Exception {

    //    addNode("www.google.com",System.currentTimeMillis() + 60000).setMetadata("www.google.com");
    //    addNode("pictures.google.com",System.currentTimeMillis() + 60000).setMetadata("pictures.google.com");
    //    addNode("pictures2.google.com",System.currentTimeMillis() + 60000).setMetadata("pictures2.google.com");
    //    addNode("gmail.google.com",System.currentTimeMillis() + 60000).setMetadata("gmail.google.com");
    //    addNode("foobar.google.com",System.currentTimeMillis() + 60000).setMetadata("foobar.google.com");
    //    Node googleSuperNode = addNode("google.com",System.currentTimeMillis() + 60000);
    //    googleSuperNode.markAsSuperHost();
    //    googleSuperNode.setMetadata("google.com");

    //   Node wwwGoogleCom = findNode("www.google.com");
    //   Node productsGoogleCom = findNode("products.google.com");

    //   org.junit.Assert.assertTrue(wwwGoogleCom.getMetadata().equals("www.google.com"));
    //   org.junit.Assert.assertTrue(productsGoogleCom.getMetadata().equals("google.com"));

    URL resourceURL = ClassLoader.getSystemResource("urls.txt");

    if (resourceURL == null) {
        throw new FileNotFoundException();
    }//from  w  w w.jav  a  2s  .  c  o m

    Set<String> hostSet = new HashSet<String>();

    for (int pass = 0; pass < 1; ++pass) {

        System.out.println("running pass:" + pass);

        InputStream stream = resourceURL.openStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

        String line;
        int lineCount = 0;

        while ((line = reader.readLine()) != null) {
            try {
                URL url = new URL(line);
                if (url.getHost() != null && url.getHost().length() != 0) {
                    if (pass == 0) {
                        //hostSet.add(url.getHost().toLowerCase());
                        cacheIPAddressForHost(url.getHost(), url.getHost().hashCode(),
                                System.currentTimeMillis() + 5000 + (int) (Math.random() * 30000.00),
                                Integer.toString(url.getHost().hashCode()));
                    } else {

                        Node node = findNode(url.getHost());
                        if (node != null) {

                            if (node.getIPAddress() != url.getHost().hashCode()) {
                                throw new RuntimeException(
                                        "Metadata Mismatch for host:" + url.getHost() + ".Excpected:"
                                                + url.getHost().hashCode() + " Got: " + node.getIPAddress());
                            }
                        } else {
                            throw new RuntimeException("Node Null! Excpected:" + url.getHost());
                        }
                    }
                }
                if (++lineCount % 10000 == 0) {
                    System.out.println("pruning mid-stream");
                    pruneCache();
                    System.out.println("sleeping a little while ..");
                    Thread.sleep(100);
                    System.out.println("wokeup");
                    //System.out.print(".");
                }
            } catch (MalformedURLException e) {

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("done reading entries");
    }
    System.out.println("Host Count:" + hostSet.size());
    System.out.println("Number of Nodes:" + numberOfNodes);
    System.out.println("Number of Nodes EQ_1:" + numberOfNodesChildEQ1);
    System.out.println("Number of Nodes LTEQ_4:" + numberOfNodesChildLTEQ4);
    System.out.println("Number of Nodes LTEQ_8:" + numberOfNodesChildLTEQ8);
    System.out.println("Number of Nodes GT_8:" + numberOfNodesChildGT8);

    while (true) {
        System.out.println("sleeping...");
        Thread.sleep(100);
        System.out.println("pruning.. ");
        pruneCache();
    }

}

From source file:org.commoncrawl.io.NIODNSCache.java

@Test
public void validateTrieCode() throws Exception {

    // addNode("www.google.com",System.currentTimeMillis() +
    // 60000).setMetadata("www.google.com");
    // addNode("pictures.google.com",System.currentTimeMillis() +
    // 60000).setMetadata("pictures.google.com");
    // addNode("pictures2.google.com",System.currentTimeMillis() +
    // 60000).setMetadata("pictures2.google.com");
    // addNode("gmail.google.com",System.currentTimeMillis() +
    // 60000).setMetadata("gmail.google.com");
    // addNode("foobar.google.com",System.currentTimeMillis() +
    // 60000).setMetadata("foobar.google.com");
    // Node googleSuperNode = addNode("google.com",System.currentTimeMillis() +
    // 60000);/*from  ww  w.j  a  v  a  2 s . c om*/
    // googleSuperNode.markAsSuperHost();
    // googleSuperNode.setMetadata("google.com");

    // Node wwwGoogleCom = findNode("www.google.com");
    // Node productsGoogleCom = findNode("products.google.com");

    // org.junit.Assert.assertTrue(wwwGoogleCom.getMetadata().equals("www.google.com"));
    // org.junit.Assert.assertTrue(productsGoogleCom.getMetadata().equals("google.com"));

    URL resourceURL = ClassLoader.getSystemResource("urls.txt");

    if (resourceURL == null) {
        throw new FileNotFoundException();
    }

    Set<String> hostSet = new HashSet<String>();

    for (int pass = 0; pass < 1; ++pass) {

        System.out.println("running pass:" + pass);

        InputStream stream = resourceURL.openStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

        String line;
        int lineCount = 0;

        while ((line = reader.readLine()) != null) {
            try {
                URL url = new URL(line);
                if (url.getHost() != null && url.getHost().length() != 0) {
                    if (pass == 0) {
                        // hostSet.add(url.getHost().toLowerCase());
                        cacheIPAddressForHost(url.getHost(), url.getHost().hashCode(),
                                System.currentTimeMillis() + 5000 + (int) (Math.random() * 30000.00),
                                Integer.toString(url.getHost().hashCode()));
                    } else {

                        Node node = findNode(url.getHost());
                        if (node != null) {

                            if (node.getIPAddress() != url.getHost().hashCode()) {
                                throw new RuntimeException(
                                        "Metadata Mismatch for host:" + url.getHost() + ".Excpected:"
                                                + url.getHost().hashCode() + " Got: " + node.getIPAddress());
                            }
                        } else {
                            throw new RuntimeException("Node Null! Excpected:" + url.getHost());
                        }
                    }
                }
                if (++lineCount % 10000 == 0) {
                    System.out.println("pruning mid-stream");
                    pruneCache();
                    System.out.println("sleeping a little while ..");
                    Thread.sleep(100);
                    System.out.println("wokeup");
                    // System.out.print(".");
                }
            } catch (MalformedURLException e) {

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("done reading entries");
    }
    System.out.println("Host Count:" + hostSet.size());
    System.out.println("Number of Nodes:" + numberOfNodes);
    System.out.println("Number of Nodes EQ_1:" + numberOfNodesChildEQ1);
    System.out.println("Number of Nodes LTEQ_4:" + numberOfNodesChildLTEQ4);
    System.out.println("Number of Nodes LTEQ_8:" + numberOfNodesChildLTEQ8);
    System.out.println("Number of Nodes GT_8:" + numberOfNodesChildGT8);

    while (true) {
        System.out.println("sleeping...");
        Thread.sleep(100);
        System.out.println("pruning.. ");
        pruneCache();
    }

}

From source file:com.safi.asterisk.handler.SafletEngine.java

public void updateServiceClasspath() {
    try {/*from  w ww .  j ava 2  s . co  m*/
        URL url = ClassLoader.getSystemResource("wrapper.conf");
        Properties props = new Properties();
        props.load(new FileInputStream(new File(url.toURI())));
        String patt = "^wrapper\\.java\\.classpath\\.[0-9]{1,3}\\s*=%ROOT_DIR%/lib/([a-zA-Z0-9\\.\\-_])*(\\*)?.jar$";
        Pattern pattern = Pattern.compile(patt);
        List<Map.Entry<Object, Object>> cpEntries = new LinkedList<Map.Entry<Object, Object>>();
        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            String key = (String) entry.getKey();
            Matcher matcher = pattern.matcher(key);
            if (matcher.matches()) {
                matcher.group(1);
            }
            if (key.matches(patt)) {
                cpEntries.add(entry);
            }
        }

    } catch (Exception exe) {
        log.error("Couldn't udpate service classpath", exe);
    }
}

From source file:org.nebulaframework.ui.swing.cluster.ClusterMainUI.java

/**
 * Displays Splash Screen//ww  w.j  a va2  s  . c o m
 * 
 * @return Splash Screen Reference
 */
public static JWindow showSplash() {

    JWindow splash = new JWindow();
    splash.setSize(400, 250);
    splash.setLayout(null);

    JLabel status = new JLabel("Developed by Yohan Liyanage, 2008");
    JLabelAppender.setLabel(status);
    status.setFont(new Font("sansserif", Font.PLAIN, 10));
    status.setSize(350, 30);
    status.setLocation(10, 220);
    splash.add(status);

    JLabel lbl = new JLabel(
            new ImageIcon(ClassLoader.getSystemResource("META-INF/resources/nebula-startup.png")));
    lbl.setSize(400, 250);
    lbl.setLocation(0, 0);
    splash.add(lbl);

    splash.setVisible(true);
    splash.setLocationRelativeTo(null);

    return splash;
}

From source file:org.evosuite.utils.ReportGenerator.java

/**
 * <p>//ww  w  .j a va2s .  com
 * copyFile
 * </p>
 * 
 * @param name
 *            a {@link java.lang.String} object.
 */
public static void copyFile(String name) {
    URL systemResource = ClassLoader.getSystemResource("report/" + name);
    logger.debug("Copying from resource: " + systemResource);
    copyFile(systemResource, new File(getReportDir(), "files/" + name));
    copyFile(systemResource, new File(getReportDir().getAbsolutePath() + "/html/files/" + name));
}

From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java

public void setDbResetScript(String dbResetScript) {
    if (dbResetScript != null) {
        String[] scripts = dbResetScript.split(",");
        List<File> scriptList = new ArrayList<File>(scripts.length);
        for (String script : scripts) {
            if (!StringUtils.isBlank(script)) {
                script = "/" + script.trim();
                URL url = ClassLoader.getSystemResource(script);
                if (url == null) {
                    url = this.getClass().getResource(script);
                }/*from www  .  j a v  a  2  s  . c  om*/
                if (url == null) {
                    LOG.warn("unable to find sql script " + script + " in classpath");
                } else {
                    LOG.debug("found dbReset sql script at " + url);
                    scriptList.add(new File(url.getFile()));
                }
            }
        }
        this.dbResetScripts = scriptList;
    }
}