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.alfresco.util.test.junitrules.TemporaryModels.java

public QName loadModel(String modelPath, ClassLoader classLoader) {
    InputStream modelStream = classLoader.getResourceAsStream(modelPath);
    if (modelStream == null) {
        throw new DictionaryException("Could not find bootstrap model " + modelPath);
    }/* w ww. j  a  va  2 s  .c o m*/
    try {
        return loadModel(modelStream);
    } finally {
        try {
            modelStream.close();
        } catch (IOException ioe) {
            logger.warn("Failed to close model input stream for '" + modelPath + "': " + ioe);
        }
    }
}

From source file:org.apache.flex.forks.velocity.runtime.resource.loader.ClasspathResourceLoader.java

/**
 * Get an InputStream so that the Runtime can build a
 * template with it.//from w  ww.  j a va  2s . c o  m
 *
 * @param name name of template to get
 * @return InputStream containing the template
 * @throws ResourceNotFoundException if template not found
 *         in  classpath.
 */
public synchronized InputStream getResourceStream(String name) throws ResourceNotFoundException {
    InputStream result = null;

    if (name == null || name.length() == 0) {
        throw new ResourceNotFoundException("No template name provided");
    }

    try {
        ClassLoader classLoader = this.getClass().getClassLoader();
        result = classLoader.getResourceAsStream(name);
    } catch (Exception fnfe) {
        /*
         *  log and convert to a general Velocity ResourceNotFoundException
         */

        throw new ResourceNotFoundException(fnfe.getMessage());
    }

    return result;
}

From source file:br.msf.commons.util.IOUtils.java

public static InputStream getClasspathInputStream(final String resourcePath, final ClassLoader classLoader) {
    if (CharSequenceUtils.isBlankOrNull(resourcePath)) {
        return null;
    }/* w  ww  . ja v  a  2s. c  om*/
    final String pathToUse = resourcePath.replaceAll("^[/]+", "");
    final ClassLoader cl = (classLoader != null ? classLoader : ReflectionUtils.getDefaultClassLoader());
    return cl.getResourceAsStream(pathToUse);
}

From source file:com.sonicle.webtop.contacts.rpt.RptAddressbook.java

@Override
protected void fillBuiltInParams() {
    super.fillBuiltInParams();

    String pkgName = LangUtils.getClassPackageName(this.getClass());
    String basepath = LangUtils.packageToPath(pkgName);
    ClassLoader cl = LangUtils.findClassLoader(this.getClass());

    InputStream is = null;/*from   w w  w.  j a  va2 s  . c o m*/
    try {
        is = cl.getResourceAsStream(basepath + "/img-contact.png");
        params.put("CONTACT_IMAGE", ImageIO.read(is));
    } catch (IOException ex) {
        throw new WTRuntimeException("Unable to read image", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
    try {
        is = cl.getResourceAsStream(basepath + "/img-contacts-list.png");
        params.put("CONTACTS_LIST_IMAGE", ImageIO.read(is));
    } catch (IOException ex) {
        throw new WTRuntimeException("Unable to read image", ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.webbfontaine.valuewebb.action.tt.TtPrinting.java

public SingleTTReport prepareFCVRReport(TtGen ttGen, boolean isDraft) {
    SingleTTReport str = new SingleTTReport();

    str.getTtId().setValue(new BigDecimal(ttGen.getId().toString()));

    ClassLoader classLoader = getClass().getClassLoader();

    if (isDraft) {
        str.getDraft().setValue(classLoader.getResourceAsStream(PrintUtils.getDraftImagePath()));
    } else {//  w w w  .j a v  a 2 s. c o  m
        String signImage = PrintUtils.getSignatureImagePath();
        if (!StringUtils.isEmpty(signImage)) {
            str.getSignature().setValue(classLoader.getResourceAsStream(signImage));
        }

        if (ttGen.getFcvrNum() == null) {
            str.getDraft().setValue(classLoader.getResourceAsStream(PrintUtils.getDraftImagePath()));
        }
    }

    str.getTitle().setValue(classLoader.getResourceAsStream(PrintUtils.getTitleImagePath()));
    return str;
}

From source file:it.jnrpe.plugins.TestCommandLineParsing.java

@Test
public void testNoArgumentsOption() throws Exception {
    ClassLoader cl = TestCommandLineParsing.class.getClassLoader();
    PluginDefinition pluginDef = PluginRepositoryUtil.parseXmlPluginDefinition(cl,
            cl.getResourceAsStream("check_mysql_plugin.xml"));

    GroupBuilder gBuilder = new GroupBuilder();

    for (PluginOption po : pluginDef.getOptions()) {
        gBuilder = gBuilder.withOption(po.toOption());
    }/*www. j  a v a2 s .co m*/

    Group group = gBuilder.create();
    Parser p = new Parser();
    p.setGroup(group);
    CommandLine cli = p.parse(new String[] { "--hostname", "$ARG1$", "--port", "$ARG2$", "--database", "$ARG3$",
            "--user", "$ARG4$", "--password", "$ARG5$", "--check-slave" });

    Assert.assertTrue(cli.hasOption("--check-slave"));
}

From source file:com.create.controller.ValidationResultRestTestExecutor.java

private String getJsonContent(String fileName) throws IOException {
    final ClassLoader classLoader = getClass().getClassLoader();
    try (final InputStream inputStream = classLoader.getResourceAsStream(fileName)) {
        return IOUtils.toString(inputStream);
    }//from   ww w.  j  av  a2  s . co  m
}

From source file:org.apache.bval.jsr.ConstraintDefaults.java

@SuppressWarnings("unchecked")
private Map<String, Class<? extends ConstraintValidator<?, ?>>[]> loadDefaultConstraints(String resource) {
    final Properties constraintProperties = new Properties();
    final ClassLoader classloader = getClassLoader();
    final InputStream stream = classloader.getResourceAsStream(resource);
    if (stream == null) {
        log.log(Level.WARNING, String.format("Cannot find %s", resource));
    } else {//from  ww  w .  j  a  v a  2  s .c  om
        try {
            constraintProperties.load(stream);
        } catch (IOException e) {
            log.log(Level.SEVERE, String.format("Cannot load %s", resource), e);
        } finally {
            try {
                stream.close();
            } catch (final IOException e) {
                // no-op
            }
        }
    }

    final Map<String, Class<? extends ConstraintValidator<?, ?>>[]> loadedConstraints = new HashMap<String, Class<? extends ConstraintValidator<?, ?>>[]>();

    for (final Map.Entry<Object, Object> entry : constraintProperties.entrySet()) {
        final List<Class<?>> classes = new LinkedList<Class<?>>();
        for (String className : StringUtils.split((String) entry.getValue(), ',')) {
            try {
                classes.add(Reflection.getClass(classloader, className.trim()));
            } catch (Exception e) {
                log.log(Level.SEVERE, String.format("Cannot find class %s", className), e);
            }
        }
        loadedConstraints.put((String) entry.getKey(), classes.toArray(new Class[classes.size()]));
    }
    return loadedConstraints;
}

From source file:$output.java

 private InputStream loadResourceAsStream(ClassLoader loader, boolean reload, String resourceName) throws IOException {
   if (!reload) {
      return loader.getResourceAsStream(resourceName);
   } else {// w w  w .j a v  a 2 s. c o  m
      URL url = loader.getResource(resourceName);
      if (url == null) {
         return null;
      }
      URLConnection connection = url.openConnection();
      if (connection == null) {
         throw new IllegalArgumentException(resourceName + " could not be opened");
      }
      connection.setUseCaches(false);
      return connection.getInputStream();
   }
}

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

public void testDefaultLog4jFromConfigDir() throws Exception {
    File log4jFile = new File(getTestCaseConfDir(), XLogService.DEFAULT_LOG4J_PROPERTIES);
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    InputStream is = cl.getResourceAsStream("test-oozie-log4j.properties");
    IOUtils.copyStream(is, new FileOutputStream(log4jFile));
    XLogService ls = new XLogService();
    ls.init(null);/*ww  w. j a  v  a2  s  .c  om*/
    Assert.assertFalse(ls.getFromClasspath());
    Assert.assertEquals(XLogService.DEFAULT_LOG4J_PROPERTIES, ls.getLog4jProperties());
    ls.destroy();
}