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:com.gtp.tradeapp.rest.UserControllerITest.java

@Test
public void usersCreateEndpointShouldCreateSuccessfully() throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    String expectedContent = IOUtils
            .toString(classLoader.getResourceAsStream("controller/user/sampleUser.json"));

    mockMvc.perform(post("/user/create").contentType("application/json;charset=UTF-8").content(expectedContent))
            .andExpect(status().isOk())/*from   w w w. j a v a 2s .c  om*/
            .andExpect(content().json("{\"code\":1,\"message\":\"User added Successfully!\"}"));
}

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

public void testCustomLog4jFromConfigDir() throws Exception {
    File log4jFile = new File(getTestCaseConfDir(), "test-log4j.properties");
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-oozie-log4j.properties");
    IOUtils.copyStream(is, new FileOutputStream(log4jFile));
    setSystemProperty(XLogService.LOG4J_FILE, "test-log4j.properties");
    XLogService ls = new XLogService();
    ls.init(null);//w  ww  . j a va  2 s .  c o m
    Assert.assertFalse(ls.getFromClasspath());
    Assert.assertEquals("test-log4j.properties", ls.getLog4jProperties());
    ls.destroy();
}

From source file:org.openmrs.module.kenyaemr.lab.LabManager.java

/**
 * Reloads all lab data from configurations
 *///w ww .  j a va 2  s  .com
public synchronized void refresh() {
    tests.clear();

    for (LabConfiguration configuration : Context.getRegisteredComponents(LabConfiguration.class)) {
        try {
            ClassLoader loader = configuration.getClassLoader();
            InputStream stream = loader.getResourceAsStream(configuration.getPath());
            loadTestsFromXML(stream);
        } catch (Exception ex) {
            throw new RuntimeException("Cannot find " + configuration.getModuleId() + ":"
                    + configuration.getPath() + ". Make sure it's in api/src/main/resources");
        }
    }
}

From source file:org.apache.synapse.commons.util.MiscellaneousUtil.java

/**
 * Load a xml configuration file//  www .  java  2  s  . c o m
 *
 * @param filePath file path
 * @return OMElement of build from the config file
 */
public static OMElement loadXMLConfig(String filePath) {

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

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

    InputStream in = null;
    if (System.getProperty(CONF_LOCATION) != null) {
        try {
            in = new FileInputStream(System.getProperty(CONF_LOCATION) + File.separator + filePath);
        } catch (FileNotFoundException e) {
            String msg = "Error loading properties from a file at from the System defined location: "
                    + System.getProperty(CONF_LOCATION) + File.separator + filePath;
            log.warn(msg);
        }
    }

    if (in == null) {
        //if can not find with system path definition looking to the class path for the given config file
        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 {
            OMElement document = new StAXOMBuilder(in).getDocumentElement();
            document.build();
            return document;
        } catch (Exception e) {
            handleException("Error while parsing the content of the file: " + filePath, e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.warn("Error while closing the input stream from the file: " + filePath, e);
            }
        }
    }
    return null;
}

From source file:de.micromata.genome.gwiki.plugin.CombinedClassLoader.java

@Override
public InputStream getResourceAsStream(String name) {
    for (ClassLoader cl : parents) {
        InputStream resource = cl.getResourceAsStream(name);
        if (resource != null)
            return resource;
    }/*from w  w  w .j a  v  a2 s .  co  m*/
    return null;
}

From source file:biz.netcentric.cq.tools.actool.validators.BeanValidatorsTest.java

private String getTestConfigAsString(final String resourceName) throws IOException {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream(resourceName);

    StringWriter stringWriter = new StringWriter();
    IOUtils.copy(is, stringWriter, "UTF-8");
    return stringWriter.toString();
}

From source file:org.softdays.mandy.service.support.BankHolidayServiceImpl.java

/**
 * Initializes the bean.//from   w  w w . j a  v a2 s.  com
 * 
 * @throws IOException
 *             thrown when unable to read from the specified reader
 * @throws ParserException
 *             thrown if an error occurs during parsing
 */
private void init() throws IOException, ParserException {
    final long start = System.currentTimeMillis();
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    final InputStream ics = classLoader.getResourceAsStream("holidays/basic.ics");
    final CalendarBuilder builder = new CalendarBuilder();
    final Calendar calendar = builder.build(ics);

    final ComponentList components = calendar.getComponents();
    @SuppressWarnings("rawtypes")
    final Iterator iterator = components.iterator();
    while (iterator.hasNext()) {
        final Component component = (Component) iterator.next();
        final Property dstart = component.getProperty("DTSTART");
        final Property summary = component.getProperty("SUMMARY");
        final DateTime date = FORMATTER.parseDateTime(dstart.getValue());
        this.bankHolidays.put(date, summary.getValue());
    }
    if (LOGGER.isTraceEnabled()) {
        final long duration = System.currentTimeMillis() - start;
        LOGGER.trace(String.format("init duration: %s ms", duration));
    }
}

From source file:com.palantir.stash.disapprove.servlet.StaticContentServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    final String user = authenticateUser(req, res);
    if (user == null) {
        // not logged in, redirect
        res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString());
        return;/* w w  w  .  j a v a 2 s  . c  o m*/
    }

    final String pathInfo = req.getPathInfo();
    OutputStream os = null;
    try {
        // The class loader that found this class will also find the static resources
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream is = cl.getResourceAsStream(PREFIX + pathInfo);
        if (is == null) {
            res.sendError(404, "File " + pathInfo + " could not be found");
            return;
        }
        os = res.getOutputStream();
        //res.setContentType("text/html;charset=UTF-8");
        String contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            contentType = URLConnection.guessContentTypeFromName(pathInfo);
        }
        if (contentType == null) {
            contentType = "application/binary";
        }
        log.debug("Serving file " + pathInfo + " with content type " + contentType);
        res.setContentType(contentType);
        IOUtils.copy(is, os);
        /*
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = bis.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
        }
        */
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:org.openmrs.module.kenyaemr.metadata.MetadataManager.java

/**
 * Refreshes all metadata//from   w  ww .j  a  v a  2  s. c  o  m
 */
public synchronized void refresh() {
    for (MetadataConfiguration configuration : Context.getRegisteredComponents(MetadataConfiguration.class)) {
        log.warn("Loading metadata package set from " + configuration.getModuleId() + ":"
                + configuration.getPath());

        try {
            ClassLoader loader = configuration.getClassLoader();
            InputStream stream = loader.getResourceAsStream(configuration.getPath());
            loadPackagesFromXML(stream, loader);
        } catch (Exception ex) {
            throw new RuntimeException("Cannot find " + configuration.getModuleId() + ":"
                    + configuration.getPath() + ". Make sure it's in api/src/main/resources");
        }
    }
}

From source file:com.sonicle.webtop.core.app.ReportManager.java

private InputStream loadReport(AbstractReport report) throws WTException {
    String rptName = report.getName() + ".jasper";
    String path = report.getPath() + rptName;
    ClassLoader cl = LangUtils.findClassLoader(report.getClass());
    InputStream is = cl.getResourceAsStream(path);
    if (is == null)
        throw new WTException("Unable to load resource [{0}]", path);
    return is;//from  www. ja  v  a  2  s. c  om
}