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.napkindrawing.dbversion.task.DbVersionCommand.java

protected String loadResourceFile(String path) {
    log("Attempting to load resource file: " + path);
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    log("Loader: " + loader);
    InputStream createInputStream = loader.getResourceAsStream(path);

    if (createInputStream == null) {
        throw new RuntimeException("Couldnt' load resource file: " + path);
    }//from  w  w  w  . j  a  va2  s .  c  om

    String contents;

    try {
        contents = IOUtils.toString(createInputStream);
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }

    return contents;
}

From source file:org.openlmis.fulfillment.web.OrderController.java

/**
 * Returns csv or pdf of defined object in response.
 *
 * @param orderId UUID of order to print
 * @param format  String describing return format (pdf or csv)
 *///from  ww  w  . ja v a2  s  .c  o m
@RequestMapping(value = "/orders/{id}/print", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ModelAndView printOrder(HttpServletRequest request, @PathVariable("id") UUID orderId,
        @RequestParam("format") String format) throws IOException {

    Order order = orderRepository.findOne(orderId);
    if (order == null) {
        throw new OrderNotFoundException(orderId);
    }
    permissionService.canViewOrder(order);

    String filePath = "jasperTemplates/ordersJasperTemplate.jrxml";
    ClassLoader classLoader = getClass().getClassLoader();

    Template template = new Template();
    template.setName("ordersJasperTemplate");

    try (InputStream fis = classLoader.getResourceAsStream(filePath)) {
        templateService.createTemplateParameters(template, fis);
    }
    JasperReportsMultiFormatView jasperView = jasperReportsViewService.getJasperReportsView(template, request);

    Map<String, Object> params = new HashMap<>();
    params.put("format", format);

    return jasperReportsViewService.getOrderJasperReportView(jasperView, params, order);
}

From source file:com.atlassian.jira.plugin.aboutpagepanel.AboutPagePanelModuleDescriptorImpl.java

private Set<Material> loadMaterials(final Plugin plugin) {
    final Set<Material> materials = Sets.newTreeSet();
    if (!isEmpty(this.getLicensesLocation())) {
        ClassLoader classLoader = plugin.getClassLoader();

        InputStream resourceAsStream = classLoader.getResourceAsStream(this.getLicensesLocation());
        if (resourceAsStream != null) {
            try {
                String bomContents = IOUtils.toString(resourceAsStream, encodingConfiguration.getEncoding());
                Iterables.addAll(materials, bomParser.extractLgplMaterials(bomContents));
            } catch (IOException e) {
                log.debug("Could not load detailed license information for " + plugin.getName() + " "
                        + plugin.getKey() + " : " + this.getName() + " at " + this.getLicensesLocation(), e);
            } finally {
                IOUtils.closeQuietly(resourceAsStream);
            }//  ww w.  j a v  a 2 s  . co  m
        } else {
            log.debug("Could not locate detailed license information for " + plugin.getName() + " "
                    + plugin.getKey() + " : " + this.getName() + " at " + this.getLicensesLocation());
        }
    }
    return materials;
}

From source file:net.sf.nmedit.nomad.core.NomadLoader.java

public Nomad createNomad(final NomadPlugin plugin) {
    NomadLoader.plugin = plugin;//w w  w  .  j a va  2 s .  com

    // first get the boot progress callbeck
    final SplashHandler progress = Boot.getSplashHandler();
    // initializing ...
    progress.setText("Initializing Nomad...");
    progress.setProgress(0.1f);
    // now we read all property files
    // 1. nomad.properties
    final Properties nProperties = new Properties();
    getProperties(nProperties, Nomad.getCorePropertiesFile());

    RootSystemProperties sproperties = new RootSystemProperties(nProperties);
    SystemPropertyFactory.sharedInstance().setFactory(new NomadPropertyFactory(sproperties));

    // 1.2 init locale
    initLocale();
    // 1.4 menu layout configuration
    InputStream mlIn = null;
    try {
        ClassLoader loader = getClass().getClassLoader();
        mlIn = loader.getResourceAsStream("./MenuLayout.xml");

        menuLayout = MenuLayout.getLayout(new BufferedInputStream(mlIn));
    } catch (Exception e) {
        Log log = LogFactory.getLog(getClass());
        if (log.isFatalEnabled()) {
            log.fatal("could not read MenuLayout", e);
        }
        throw new RuntimeException(e);
    } finally {
        try {
            if (mlIn != null)
                mlIn.close();
        } catch (IOException e) {
            Log log = LogFactory.getLog(NomadLoader.class);
            if (log.isWarnEnabled()) {
                log.warn("closing menu layout", e);
            }
        }
    }
    // increase progress
    progress.setProgress(0.2f);
    // 1.5 initialize look and feel (important: before creating any swing components)

    String lafClassName = plugin.getDescriptor().getAttribute("javax.swing.LookAndFeel").getValue();
    String themeClassName = plugin.getDescriptor().getAttribute("javax.swing.plaf.metal.MetalTheme").getValue();
    String defaultLafOnPlatform = plugin.getDescriptor().getAttribute("nomad.plaf.usePlatformDefault")
            .getValue();

    initLookAndFeel(lafClassName, themeClassName, defaultLafOnPlatform);
    // 1.6 initialize main window's menu
    progress.setProgress(0.3f);

    /*     NomadActionControl nomadActions = new NomadActionControl( Nomad.sharedInstance() );
          nomadActions.installActions(menuBuilder);
      */
    progress.setProgress(0.5f);
    progress.setText("Initializing main window...");

    activatePlugins();

    progress.setText("Initializing services...");

    JPFServiceInstallerTool.activateAllServices(plugin);
    progress.setText("Starting Nomad...");

    // SwingUtilities.invokeLater(run);

    Nomad nomad = new Nomad(plugin, menuLayout);
    return nomad;
}

From source file:com.autentia.tnt.manager.report.ReportManager.java

private void parseDocument(Boolean typeFile, String reportName) {

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

    final InputStream jasperreportDtd = loader
            .getResourceAsStream("net/sf/jasperreports/engine/dtds/jasperreport.dtd");
    InputStream xmlSource = null;

    parsingStart = System.currentTimeMillis();
    log.debug("parseDocument - [start] " + reportName);
    try {//from  w w w  . ja  v a  2 s  . c  om
        SAXParser sp = new SAXParser();
        log.debug("parseDocument -   newSAXParser=" + (System.currentTimeMillis() - parsingStart) + " ms.");

        File f = null;
        try {
            if (typeFile == true)
                f = new File(loader.getResource(reportName).toURI());
            else
                f = new File(reportName);
        } catch (URISyntaxException e) {
            log.error("Error en ParseDocument", e);
        }
        log.debug("parseDocument -   getResource=" + (System.currentTimeMillis() - parsingStart) + " ms.");

        xmlSource = new FileInputStream(f);

        sp.setContentHandler(this);
        sp.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals("//JasperReports//DTD Report Design//EN")
                        || systemId.equals("http://jasperreports.sourceforge.net/dtds/jasperreport.dtd")) {
                    return new InputSource(jasperreportDtd);
                } else {
                    String msg = "DTD (" + publicId + " " + systemId + ") cannot be resolved by ReportManager: "
                            + "please change TNTConcept to add the new DTD or change your JasperReport's JRXML file "
                            + "to use the standard DTD";
                    log.error("parseDocument - " + msg);
                    throw new IllegalArgumentException(msg);
                }
            }
        });

        sp.parse(new InputSource(xmlSource));
    } catch (FinalizeParsingException fpe) {
        // ignore this exception as it is thrown as an optimization
    } catch (SAXException se) {
        log.error("parseDocument - exception", se);
    } catch (IOException ie) {
        log.error("parseDocument - exception", ie);
    }

    finally {
        if (xmlSource != null) {
            try {
                xmlSource.close();
            } catch (IOException e) {
                // ignored
            }
        }
        try {
            jasperreportDtd.close();
        } catch (IOException e) {
            // ignored
        }
        log.info(
                "parseDocument - " + reportName + " (" + (System.currentTimeMillis() - parsingStart) + " ms.)");
    }
}

From source file:com.espertech.esper.client.ConfigurationParser.java

/**
 * Returns an input stream from an application resource in the classpath.
 * @param resource to get input stream for
 * @return input stream for resource/*from  w  w w.j av a  2s.c o  m*/
 */
protected static InputStream getResourceAsStream(String resource) {
    String stripped = resource.startsWith("/") ? resource.substring(1) : resource;

    InputStream stream = null;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        stream = classLoader.getResourceAsStream(stripped);
    }
    if (stream == null) {
        stream = ConfigurationParser.class.getResourceAsStream(resource);
    }
    if (stream == null) {
        stream = ConfigurationParser.class.getClassLoader().getResourceAsStream(stripped);
    }
    if (stream == null) {
        throw new EPException(resource + " not found");
    }
    return stream;
}

From source file:com.h3xstream.findbugs.test.service.FindBugsLauncher.java

private void addFilesToStream(final ClassLoader cl, final JarOutputStream jar, final File dir,
        final String path) throws IOException {
    for (final File nextFile : dir.listFiles()) {
        if (nextFile.isFile()) {
            final String resource = path + nextFile.getName();
            jar.putNextEntry(new ZipEntry(resource));
            jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource)));
        } else {//from  w w w.ja v a  2s.  com
            addFilesToStream(cl, jar, nextFile, path + nextFile.getName() + "/");
        }
    }
}

From source file:com.joyent.manta.client.MantaClientPutIT.java

@Test
public final void testPutWithMarkSupportedStream() throws IOException, URISyntaxException {
    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Assert.assertNotNull(classLoader.getResource(TEST_FILENAME));

    try (InputStream testDataInputStream = classLoader.getResourceAsStream(TEST_FILENAME);
            CountingInputStream countingInputStream = new CountingInputStream(testDataInputStream)) {
        Assert.assertTrue(countingInputStream.markSupported());
        mantaClient.put(path, countingInputStream);
        Assert.assertTrue(mantaClient.existsAndIsAccessible(path));

        File localFile = Paths.get(classLoader.getResource(TEST_FILENAME).toURI()).toFile();
        byte[] expectedBytes = FileUtils.readFileToByteArray(localFile);

        try (MantaObjectInputStream in = mantaClient.getAsInputStream(path)) {
            byte[] actualBytes = IOUtils.readFully(in, (int) localFile.length());
            AssertJUnit.assertArrayEquals(expectedBytes, actualBytes);
        }/*w w  w . j av  a  2  s  .co m*/
    }
}

From source file:com.urbancode.terraform.tasks.vmware.RouterConfigPostCreateTask.java

private void copyTempFile(String fileName) throws IOException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String cpDir = "org/urbancode/terraform/conf" + File.separator;
    InputStream inputStream = loader.getResourceAsStream(cpDir + fileName);
    try {/*from  w ww  .  ja va 2  s . co m*/
        writeInputStreamToFile(inputStream, this.tempConfDir + fileName);
    } catch (IOException e) {
        inputStream.close();
    }
}

From source file:org.suren.autotest.web.framework.code.DefaultXmlDataSourceGenerator.java

@Override
public void generate(String srcCoding, String outputDir) {
    this.outputDir = outputDir;
    ClassLoader classLoader = this.getClass().getClassLoader();

    //??/*from  www .j a v a 2s . c  o m*/
    try (InputStream confInput = classLoader.getResourceAsStream(srcCoding)) {
        generate(confInput, outputDir, null);
    } catch (DocumentException | IOException e) {
        logger.error(String.format("Main config [%s] parse process error.", srcCoding), e);
    } catch (SAXException e) {
        e.printStackTrace();
    } finally {
        for (String resPath : docMap.keySet()) {
            Document doc = docMap.get(resPath);
            write(doc, resPath);
        }
    }
}