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:bboss.org.apache.velocity.texen.ant.TexenTask.java

/**
 * Set the context properties that will be
 * fed into the initial context be the// ww  w  .j  a  v  a2 s. c o  m
 * generating process starts.
 * @param file
 */
public void setContextProperties(String file) {
    String[] sources = StringUtils.split(file, ",");
    contextProperties = new ExtendedProperties();

    // Always try to get the context properties resource
    // from a file first. Templates may be taken from a JAR
    // file but the context properties resource may be a
    // resource in the filesystem. If this fails than attempt
    // to get the context properties resource from the
    // classpath.
    for (int i = 0; i < sources.length; i++) {
        ExtendedProperties source = new ExtendedProperties();

        try {
            // resolve relative path from basedir and leave
            // absolute path untouched.
            File fullPath = project.resolveFile(sources[i]);
            log("Using contextProperties file: " + fullPath);
            source.load(new FileInputStream(fullPath));
        } catch (IOException e) {
            ClassLoader classLoader = this.getClass().getClassLoader();

            try {
                InputStream inputStream = classLoader.getResourceAsStream(sources[i]);

                if (inputStream == null) {
                    throw new BuildException("Context properties file " + sources[i]
                            + " could not be found in the file system or on the classpath!");
                } else {
                    source.load(inputStream);
                }
            } catch (IOException ioe) {
                source = null;
            }
        }

        if (source != null) {
            for (Iterator j = source.getKeys(); j.hasNext();) {
                String name = (String) j.next();
                String value = StringUtils.nullTrim(source.getString(name));
                contextProperties.setProperty(name, value);
            }
        }
    }
}

From source file:org.apache.oozie.service.TestZKXLogStreamingService.java

public void testTuncateLog() throws Exception {
    XLogFilter.reset();//from w ww .j a  v  a2s.c o  m
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);
    // prevent conflicts with other tests by changing the log file location
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());
    assertFalse(doStreamDisabledCheck());
    File logFile = new File(Services.get().get(XLogService.class).getOozieLogPath(),
            Services.get().get(XLogService.class).getOozieLogName());
    logFile.getParentFile().mkdirs();

    ConfigurationService.set(XLogFilter.MAX_SCAN_DURATION, "1");
    Date startDate = new Date();
    Date endDate = new Date(startDate.getTime() + 60 * 60 * 1000 * 15);

    String log = doStreamLog(new XLogFilter(), startDate, endDate);
    assertTrue(log.contains("Truncated logs to max log scan duration"));
    String logError = doStreamErrorLog(new XLogFilter(), startDate, endDate);
    assertFalse(logError.contains("Truncated logs to max log scan duration"));
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides sending report request to server.
   @param filename name of a file containing report request
   @param path request target path/*  ww w  .  j a  v  a 2s .c  o  m*/
   @param depth report depth
   @return server response
 */
private String report(String filename, String path, int depth)
        throws ClientProtocolException, IOException, URISyntaxException {
    ReportRequest req = new ReportRequest(initUri(path), depth);

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream(filename);

    StringEntity se = new StringEntity(convertStreamToString(is), "UTF-8");

    se.setContentType(TYPE_XML);
    req.setEntity(se);

    HttpResponse resp = client.execute(req);

    String response = "";
    response += EntityUtils.toString(resp.getEntity(), "UTF-8");

    EntityUtils.consume(resp.getEntity());

    return response;
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides sending propfind request to server.
   @param fileName name of a file containing propfinde request
   @param uriName propfind uri/*from w w  w  .j av a  2  s  . co m*/
   @return server response
 */
private String propfind(String fileName, String uriName)
        throws URISyntaxException, ClientProtocolException, IOException {

    PropfindRequest req = new PropfindRequest(initUri(uriName));
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream is = classLoader.getResourceAsStream(fileName);

    StringEntity se = new StringEntity(convertStreamToString(is), "UTF-8");

    se.setContentType(TYPE_XML);
    req.setEntity(se);

    HttpResponse resp = client.execute(req);

    String response = "";
    response += EntityUtils.toString(resp.getEntity(), "UTF-8");

    EntityUtils.consume(resp.getEntity());

    return response;

}

From source file:com.lonepulse.zombielink.processor.RequestParamEndpointTest.java

/**
 * <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
 * /*from  w  ww. j a v  a2 s  . co  m*/
 * @since 1.3.0
 */
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {

    String subpath = "/bufferedhttpentity";

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
    InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
    BasicHttpEntity bhe = new BasicHttpEntity();
    bhe.setContent(parallelInputStream);

    stubFor(put(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200)));

    requestEndpoint.bufferedHttpEntity(inputStream);

    verify(putRequestedFor(urlEqualTo(subpath))
            .withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}

From source file:gov.va.vinci.leo.ae.LeoBaseAnnotator.java

/**
 * Gets a resource as an input stream./*from w w  w . jav  a2  s . c o  m*/
 * <p/>
 * Note: Resource paths are specified via file: and classpath: to determine
 * if the resource should be looked up in the file system or in the
 * classpath. If file: or classpath: is not specified, file path is assumed.
 *
 * @param resourcePath the path to the resource to get the inputstream for.
 * @return the input stream for the resource.
 * @throws java.io.IOException if the input stream for the resource throws an exception.
 */
public InputStream getResourceAsInputStream(String resourcePath) throws IOException {
    InputStream stream = null;

    if (resourcePath == null) {
        throw new IllegalArgumentException("Resource path cannot be null.");
    }

    if (resourcePath.startsWith("classpath:")) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        stream = cl.getResourceAsStream(resourcePath.substring(10));
        if (stream == null) {
            throw new IllegalArgumentException("Resource: " + resourcePath + " not found in classpath.");
        }
        return stream;
    } else {
        String file;
        if (resourcePath.startsWith("file:")) {
            file = resourcePath.substring(5);
        } else {
            file = resourcePath;
        }

        File f = new File(file);

        if (!f.exists()) {
            throw new IllegalArgumentException(
                    "Resource: " + resourcePath + " not found using file path resolution. Current directory is "
                            + new File(".").getCanonicalPath());
        }

        return new FileInputStream(f);
    }

}

From source file:org.apache.oozie.service.TestZKXLogStreamingService.java

public void testNoDashInConversionPattern() throws Exception {
    XLogFilter.reset();//from  ww  w  .j a v  a2  s . c  o m
    XLogFilter.defineParameter("USER");
    XLogFilter.defineParameter("GROUP");
    XLogFilter.defineParameter("TOKEN");
    XLogFilter.defineParameter("APP");
    XLogFilter.defineParameter("JOB");
    XLogFilter.defineParameter("ACTION");
    XLogFilter xf = new XLogFilter();
    xf.setParameter("USER", "oozie");
    xf.setLogLevel("DEBUG|INFO");
    // Previously, a dash ("-") was always required somewhere in a line in order for that line to pass the filter; this test
    // checks that this condition is no longer required for log streaming to work
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-no-dash-log4j.properties");
    Properties log4jProps = new Properties();
    log4jProps.load(is);
    // prevent conflicts with other tests by changing the log file location
    log4jProps.setProperty("log4j.appender.oozie.File", getTestCaseDir() + "/oozie.log");
    log4jProps.store(new FileOutputStream(log4jFile), "");
    setSystemProperty(XLogService.LOG4J_FILE, log4jFile.getName());
    assertFalse(doStreamDisabledCheck());
    LogFactory.getLog("a").info(
            "2009-06-24 02:43:14,505 INFO _L1_:317 - SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] APP[-] "
                    + "JOB[-] ACTION[-] Released Lock");
    LogFactory.getLog("a")
            .info("2009-06-24 02:43:14,505 INFO _L2_:317 - SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-] APP[-] "
                    + "JOB[-] ACTION[-] Released Lock");
    LogFactory.getLog("a")
            .info("2009-06-24 02:43:14,505 INFO _L3_:317 SERVER[foo] USER[oozie] GROUP[oozie] TOKEN[-] APP[-] "
                    + "JOB[-] ACTION[-] Released Lock");
    LogFactory.getLog("a")
            .info("2009-06-24 02:43:14,505 INFO _L4_:317 SERVER[foo] USER[blah] GROUP[oozie] TOKEN[-] APP[-] "
                    + "JOB[-] ACTION[-] Released Lock");
    String out = doStreamLog(xf);
    String outArr[] = out.split("\n");
    // Lines 2 and 4 are filtered out because they have the wrong user
    assertEquals(2, outArr.length);
    assertTrue(outArr[0].contains("_L1_"));
    assertFalse(out.contains("_L2_"));
    assertTrue(outArr[1].contains("_L3_"));
    assertFalse(out.contains("_L4_"));
}

From source file:com.moss.schematrax.SchemaData.java

public SchemaData(ClassLoader loader, String resourcesPrefix) throws Exception {
    this.resourcesPrefix = resourcesPrefix;
    this.loader = loader;

    Document document;// ww  w. java 2  s.  c  o m
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    String indexResourceLocation = resourcesPrefix + "index.xml";
    InputStream indexStream = loader.getResourceAsStream(indexResourceLocation);
    if (indexStream == null)
        throw new Exception("Could not find " + indexResourceLocation + " on the classpath.");
    document = builder.parse(indexStream);

    readConfiguration(document);
    initUpdates(document);

    initVersions(document);

}

From source file:com.berico.clavin.resolver.impl.lucene.IndexBuilder.java

/**
 * Print a nice CLAVIN Banner, hurray!/* w w  w .j a  v  a  2s  . c o m*/
 */
public void printBanner() {

    // Get the current classloader.
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    // Retrieve the banner text from the text file in the src/main/resources
    // directory.
    InputStream is = cl.getResourceAsStream("banner.txt");

    try {

        // Pull the banner from the input stream
        String banner = IOUtils.toString(is);

        // Print the banner.
        p(banner);

    } catch (IOException e) {

        // Oops, didn't work!
        e.printStackTrace();
    }
}

From source file:SearchlistClassLoader.java

/**
 *  load the byte data for a class definition.
 *
 *  @param name the fully-qualified class name
 *  @return a byte[] containing the class bytecode or <i>null</i>
 *//*w ww . j a v a  2  s  .c  o  m*/
protected byte[] loadClassData(ClassLoader cl, String name) {
    ByteArrayOutputStream barray;
    byte buff[];
    int len;

    InputStream in = cl.getResourceAsStream(translate(name, ".", "/") + ".class");

    if (in == null)
        return null;

    try {

        barray = new ByteArrayOutputStream(1024 * 16);
        buff = new byte[1024];

        do {
            len = in.read(buff, 0, buff.length);
            if (len > 0)
                barray.write(buff, 0, len);
        } while (len >= 0);

        return (barray.size() > 0 ? barray.toByteArray() : null);

    } catch (Exception e) {
        return null;
    }
}