Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

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

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:org.apache.axis2.transport.base.BaseUtils.java

/**
 * Loads the properties from a given property file path
 *
 * @param filePath Path of the property file
 * @return Properties loaded from given file
 *//*from  ww w.jav a2 s .  c  o m*/
public static Properties loadProperties(String filePath) {

    Properties properties = new Properties();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    if (log.isDebugEnabled()) {
        log.debug("Loading a file '" + filePath + "' from classpath");
    }

    InputStream in = cl.getResourceAsStream(filePath);
    if (in == null) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to load file  '" + filePath + "'");
        }

        filePath = "conf" + File.separatorChar + filePath;
        if (log.isDebugEnabled()) {
            log.debug("Loading a file '" + filePath + "' from classpath");
        }

        in = cl.getResourceAsStream(filePath);
        if (in == null) {
            if (log.isDebugEnabled()) {
                log.debug("Unable to load file  ' " + filePath + " '");
            }
        }
    }
    if (in != null) {
        try {
            properties.load(in);
        } catch (IOException e) {
            String msg = "Error loading properties from a file at :" + filePath;
            log.error(msg, e);
            throw new BaseTransportException(msg, e);
        }
    }
    return properties;
}

From source file:de.mpg.escidoc.util.Util.java

public static void loadProperties() {
    ClassLoader loader = null;
    InputStream in = null;// w w  w . j  ava2 s. c  o  m
    try {
        if (loader == null) {
            loader = Util.class.getClassLoader();
        }
        InputStream is = loader.getResourceAsStream(PROPERTIES_FILE);
        if (is != null) {
            properties = new Properties();
            properties.load(is);
        }
    } catch (Exception e) {
        properties = null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Throwable ignore) {
                ignore.printStackTrace();
            }
        }
    }
}

From source file:org.apache.axis2.util.Loader.java

/**
 * Gets the resource with the specified class loader.
 *
 * @param loader// w  w w  .j  a  va 2s  .  c  om
 * @param resource
 * @return Returns URL.
 * @throws ClassNotFoundException
 */
static public InputStream getResourceAsStream(ClassLoader loader, String resource)
        throws ClassNotFoundException {
    try {
        if (loader != null) {
            log.debug("Trying to find [" + resource + "] using " + loader + " class loader.");
            InputStream is = loader.getResourceAsStream(resource);
            if (is != null) {
                return is;
            }
        }
    } catch (Throwable t) {
        log.warn("Caught Exception while in Loader.getResource. This may be innocuous.", t);
    }
    return getResourceAsStream(resource);
}

From source file:com.runwaysdk.browser.JavascriptTestRunner.java

public static Test suite() throws Exception {
    // Read project.version
    Properties prop1 = new Properties();
    ClassLoader loader1 = Thread.currentThread().getContextClassLoader();
    InputStream stream1 = loader1.getResourceAsStream("avail-maven.properties");
    prop1.load(stream1);//ww  w  .  ja v  a  2s. c  o  m
    String projVer = prop1.getProperty("mvn.project.version");

    TestSuite suite = new TestSuite();

    int browserLoopIterationNumber = 0;

    System.out.println("Preparing to run cross-browser javascript unit tests.");
    long totalTime = System.currentTimeMillis();

    for (String browser : supportedBrowsers) {
        try {
            String browserDisplayName = String.valueOf(browser.charAt(1)).toUpperCase() + browser.substring(2);
            System.out.println("Opening " + browserDisplayName);

            TestSuite browserSuite = new TestSuite(browserDisplayName);

            selenium = new DefaultSelenium("localhost", 4444, browser,
                    "http://localhost:8080/runwaysdk-browser-test-" + projVer + "/");
            selenium.start();
            isSeleniumStarted = true;
            selenium.open("MasterTestLauncher.jsp");

            //          selenium.waitForCondition("selenium.browserbot.getCurrentWindow().document.getElementById('all');", "6000");

            selenium.setTimeout("1000");

            System.out.println("Running tests...");
            long time = System.currentTimeMillis();

            selenium.click("all");
            selenium.waitForCondition(
                    "!selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.isRunning()",
                    Integer.toString(MAXIMUM_TOTAL_TEST_DURATION * 1000));

            time = System.currentTimeMillis() - time; // elapsed time in milis
            if (time < 1000) {
                System.out.println("Tests completed in " + time + " miliseconds.");
            } else if (time < 60000) {
                time = time / 1000;
                System.out.println("Tests completed in " + time + " seconds.");
            } else if (time < 3600000) {
                time = time / (1000 * 60);
                System.out.println("Tests completed in " + time + " minutes.");
            } else {
                time = time / (1000 * 60 * 60);
                System.out.println("Tests completed in " + time + " hours.");
            }

            //System.out.println(selenium.getEval("\n\n" + "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.XML);") + "\n\n");

            // tests are done running, get the results and display them through junit

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            String resultsJunitXML = selenium.getEval(
                    "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.JUnitXML);");
            String resultsYUITestXML = selenium.getEval(
                    "selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Runner.getResults(selenium.browserbot.getCurrentWindow().com.runwaysdk.test.TestFramework.getY().Test.Format.XML);");

            // Write the test output to xml
            Properties prop = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream stream = loader.getResourceAsStream("default/common/terraframe.properties");
            prop.load(stream);
            String basedir = prop.getProperty("local.root");

            System.out.println("Writing javascript test results to '" + basedir
                    + "/target/surefire-reports/TEST-com.runwaysdk.browser.JavascriptTestRunner-"
                    + browserDisplayName + ".xml.");
            File dir = new File(basedir + "/target/surefire-reports");
            dir.mkdirs();
            final OutputStream os = new FileOutputStream(dir.getAbsolutePath()
                    + "/TEST-com.runwaysdk.browser.JavascriptTestRunner-" + browserDisplayName + ".xml", false);
            final PrintStream printStream = new PrintStream(os);
            printStream.print(resultsJunitXML);
            printStream.close();

            InputSource in = new InputSource();
            in.setCharacterStream(new StringReader(resultsYUITestXML));
            Element doc = db.parse(in).getDocumentElement();

            NodeList suiteList = doc.getElementsByTagName("testsuite");

            if (suiteList == null || suiteList.getLength() == 0) {
                //suiteList = (NodeList)doc;
                throw new Exception("Unable to find any suites!");
            }

            String uniqueWhitespace = "";
            for (int j = 0; j < browserLoopIterationNumber; j++) {
                uniqueWhitespace = uniqueWhitespace + " ";
            }

            for (int i = 0; i < suiteList.getLength(); i++) //looping through test suites
            {
                Node n = suiteList.item(i);
                TestSuite s = new TestSuite();
                NamedNodeMap nAttrMap = n.getAttributes();

                s.setName(nAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace);

                NodeList testCaseList = ((Element) n).getElementsByTagName("testcase");
                for (int j = 0; j < testCaseList.getLength(); j++) // looping through test cases
                {
                    Node x = testCaseList.item(j);
                    NamedNodeMap xAttrMap = x.getAttributes();

                    TestSuite testCaseSuite = new TestSuite();
                    testCaseSuite.setName(xAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace);

                    NodeList testList = ((Element) x).getElementsByTagName("test");
                    for (int k = 0; k < testList.getLength(); k++) // looping through tests
                    {
                        Node testNode = testList.item(k);
                        NamedNodeMap testAttrMap = testNode.getAttributes();

                        Test t = new GeneratedTest(
                                testAttrMap.getNamedItem("name").getNodeValue() + uniqueWhitespace);

                        if (testAttrMap.getNamedItem("result").getNodeValue().equals("fail")) {
                            ((GeneratedTest) t).testFailMessage = testAttrMap.getNamedItem("message")
                                    .getNodeValue();
                        }

                        testCaseSuite.addTest(t);
                    }

                    s.addTest(testCaseSuite);
                }

                browserSuite.addTest(s);
            }

            //suite.addTest(browserSuite);
            browserLoopIterationNumber++;
        } // end try
        catch (Exception e) {
            throw (e);
        } finally {
            if (isSeleniumStarted) {
                selenium.stop();
                isSeleniumStarted = false;
            }
        }
    } // end for loop on browsers

    totalTime = System.currentTimeMillis() - totalTime; // elapsed time in milis
    if (totalTime < 1000) {
        System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " miliseconds.");
    } else if (totalTime < 60000) {
        totalTime = totalTime / 1000;
        System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " seconds.");
    } else if (totalTime < 3600000) {
        totalTime = totalTime / (1000 * 60);
        System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " minutes.");
    } else {
        totalTime = totalTime / (1000 * 60 * 60);
        System.out.println("Cross-browser javascript unit tests completed in " + totalTime + " hours.");
    }

    return suite;
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.PdfaConvert.java

private static void loadVersionFile() {

    // get version properties file
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {/* w w w.  j a v  a2 s .c  om*/
        InputStream resourceStream = loader.getResourceAsStream(ApplicationConstants.VERSION_PROPS);
        Properties versionProps = new Properties();
        versionProps.load(resourceStream);
        String version = versionProps.getProperty(ApplicationConstants.VERSION_KEY);
        if (StringUtils.isEmpty(version)) {
            version = "<not available>";
        }
        applicationVersion = version;
        logger.debug("{} version: {}", PdfaConvert.class.getSimpleName(), applicationVersion);
    } catch (IOException e) {
        logger.error("Could not load properties file: {}", ApplicationConstants.PROJECT_PROPS, e);
    }
}

From source file:com.amazonaws.eclipse.core.regions.RegionUtils.java

/**
 * Load regions from local file./*from   ww  w.ja  v  a  2s  .co  m*/
 */
public static List<Region> loadRegionsFromLocalFile() {
    ClassLoader classLoader = RegionUtils.class.getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(LOCAL_REGION_FILE);
    return parseRegionMetadata(inputStream);
}

From source file:com.amazonaws.eclipse.core.regions.RegionUtils.java

/**
 * Failsafe method to initialize the regions list from the list bundled with
 * the plugin, in case it cannot be fetched from the remote source.
 *//* w  w  w. j a  v a  2 s.co  m*/
private static void initBundledRegions() {
    ClassLoader classLoader = RegionUtils.class.getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(LOCAL_REGION_FILE);
    regions = parseRegionMetadata(inputStream);
    for (Region r : regions) {
        if (r == LocalRegion.INSTANCE) {
            // No flag to load for the local region.
            continue;
        }

        AwsToolkitCore.getDefault().getImageRegistry().put(AwsToolkitCore.IMAGE_FLAG_PREFIX + r.getId(),
                ImageDescriptor.createFromFile(RegionUtils.class, "/icons/" + r.getFlagIconPath()));
    }
}

From source file:org.apache.hama.zookeeper.QuorumPeer.java

/**
 * Make a Properties object holding ZooKeeper config equivalent to zoo.cfg. If
 * there is a zoo.cfg in the classpath, simply read it in. Otherwise parse the
 * corresponding config options from the Hama XML configs and generate the
 * appropriate ZooKeeper properties.//from  www  . j  a v  a2 s.  c  o  m
 * 
 * @param conf Configuration to read from.
 * @return Properties holding mappings representing ZooKeeper zoo.cfg file.
 */
public static Properties makeZKProps(Configuration conf) {
    // First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
    // it and grab its configuration properties.
    ClassLoader cl = QuorumPeer.class.getClassLoader();
    InputStream inputStream = cl.getResourceAsStream(ZOOKEEPER_CONFIG_NAME);
    if (inputStream != null) {
        try {
            return parseZooCfg(conf, inputStream);
        } catch (IOException e) {
            LOG.warn("Cannot read " + ZOOKEEPER_CONFIG_NAME + ", loading from XML files", e);
        }
    }

    // Otherwise, use the configuration options from Hama's XML files.
    Properties zkProperties = new Properties();

    // Set the max session timeout from the provided client-side timeout
    zkProperties.setProperty("maxSessionTimeout", conf.get(Constants.ZOOKEEPER_SESSION_TIMEOUT, "1200000"));

    // Directly map all of the hama.zookeeper.property.KEY properties.
    for (Entry<String, String> entry : conf) {
        String key = entry.getKey();
        if (key.startsWith(ZK_CFG_PROPERTY)) {
            String zkKey = key.substring(ZK_CFG_PROPERTY_SIZE);
            String value = entry.getValue();
            // If the value has variables substitutions, need to do a get.
            if (value.contains(VARIABLE_START)) {
                value = conf.get(key);
            }
            zkProperties.put(zkKey, value);
        }
    }

    // If clientPort is not set, assign the default
    if (zkProperties.getProperty(ZOOKEEPER_CLIENT_PORT) == null) {
        zkProperties.put(ZOOKEEPER_CLIENT_PORT, DEFAULT_ZOOKEEPER_CLIENT_PORT);
    }

    // Create the server.X properties.
    int peerPort = conf.getInt("hama.zookeeper.peerport", 2888);
    int leaderPort = conf.getInt("hama.zookeeper.leaderport", 3888);

    String[] serverHosts = conf.getStrings(ZOOKEEPER_QUORUM, "localhost");
    for (int i = 0; i < serverHosts.length; ++i) {
        String serverHost = serverHosts[i];
        String address = serverHost + ":" + peerPort + ":" + leaderPort;
        String key = "server." + i;
        zkProperties.put(key, address);
    }

    return zkProperties;
}

From source file:com.thejustdo.util.Utils.java

/**
 * Reads the content of a file and returns it in a big string object.
 *
 * @param filename Name and location to the plain file.
 * @return All the lines inside the file.
 *//*from   w w w  .j  av a 2s .c o m*/
public static String getPlainTextFileFromContext(String filename) {
    log.log(Level.INFO, "Loading contents of file: {0}.", filename);
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        InputStream is = cl.getResourceAsStream(filename);
        StringBuilder answer = new StringBuilder();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(isr);

        // while there are more lines.
        String line;
        while (reader.ready()) {
            line = reader.readLine();
            answer.append(line).append("\n");
        }

        // closing resources.
        reader.close();

        return answer.toString();
    } catch (IOException ex) {
        log.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.espertech.esper.core.deploy.EPLModuleUtil.java

public static Module readResource(String resource) throws IOException, ParseException {
    String stripped = resource.startsWith("/") ? resource.substring(1) : resource;

    InputStream stream = null;/*from ww w .j ava2  s  .  co  m*/
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        stream = classLoader.getResourceAsStream(stripped);
    }
    if (stream == null) {
        stream = EPDeploymentAdminImpl.class.getResourceAsStream(resource);
    }
    if (stream == null) {
        stream = EPDeploymentAdminImpl.class.getClassLoader().getResourceAsStream(stripped);
    }
    if (stream == null) {
        throw new IOException("Failed to find resource '" + resource + "' in classpath");
    }

    try {
        return EPLModuleUtil.readInternal(stream, resource);
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
            log.debug("Error closing input stream", e);
        }
    }
}