Example usage for java.lang Class getResourceAsStream

List of usage examples for java.lang Class getResourceAsStream

Introduction

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

Prototype

@CallerSensitive
public InputStream getResourceAsStream(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:org.gvnix.support.MessageBundleUtils.java

/**
 * Copy properties associated with the given class to the message bundle of
 * given language./*from w  ww  .  j av  a 2  s.  c o  m*/
 * <p/>
 * Note that properties to add are taken from messages[_xx].properties files
 * and added to messages[_xx].properties in the destination project.
 * <p/>
 * <strong>This method doesn't check if messages[_xx].properties file exist
 * in the add-on invoking it</strong>
 * 
 * @param language Language locale as string (en, es, ca, ...)
 * @param invokingClass Class of the Add-on invoking this method. It's
 *        needed in order to load local resources
 * @param propFileOperations
 * @param projectOperations
 * @param fileManager
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void addPropertiesToMessageBundle(String language, Class invokingClass,
        PropFileOperations propFileOperations, ProjectOperations projectOperations, FileManager fileManager) {
    Properties properties = new Properties();
    LogicalPath webappPath = WebProjectUtils.getWebappPath(projectOperations);

    String sourcePropertyFile = "/".concat(invokingClass.getPackage().getName()).replace('.', '/');

    // Take "en" as default language
    String targetFilePath = "/WEB-INF/i18n/messages.properties";
    String targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

    try {
        if (language.equals("en")) {
            sourcePropertyFile = sourcePropertyFile.concat("/messages.properties");
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        } else {
            targetFilePath = "/WEB-INF/i18n/messages_".concat(language).concat(".properties");
            targetFile = projectOperations.getPathResolver().getIdentifier(webappPath, targetFilePath);

            sourcePropertyFile = sourcePropertyFile.concat("/messages_".concat(language).concat(".properties"));
            properties.load(invokingClass.getResourceAsStream(sourcePropertyFile));
        }

        if (fileManager.exists(targetFile)) {
            propFileOperations.addProperties(webappPath, targetFilePath,
                    new HashMap<String, String>((Map) properties), true, true);
        } else {
            logger.warning(targetFile.concat(" file doesn't exist in project."));
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE,
                "Message properties for language \"".concat(language).concat("\" can't be loaded"));
    }
}

From source file:org.apache.axis2.jaxws.util.WSToolingUtils.java

/**
 * Retrieves the major version number of the WsGen class that we're using
 * // w w w.j a  v a 2  s.  c om
 * @return String
 * 
 */
public static String getWsGenVersion() throws ClassNotFoundException, IOException {

    Class clazz = null;
    try {

        clazz = forName("com.sun.tools.ws.WsGen", false, getContextClassLoader(null));

    } catch (ClassNotFoundException e1) {

        try {

            clazz = forName("com.sun.tools.internal.ws.WsGen", false, getContextClassLoader(null));

        } catch (ClassNotFoundException e2) {
            if (log.isDebugEnabled()) {
                log.debug("Exception thrown from getWsGenVersion: " + e2.getMessage(), e2);
            }
            throw (ClassNotFoundException) e2;
        }
    }

    Properties p = new Properties();

    try {

        p.load(clazz.getResourceAsStream("version.properties"));

    } catch (IOException ioex) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from getWsGenVersion: " + ioex.getMessage(), ioex);

        }
        throw (IOException) ioex.getCause();
    }

    return (p.getProperty("major-version"));
}

From source file:com.amalto.webapp.core.util.Util.java

public static String getXML(Class<?> c, String filename) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(c.getResourceAsStream(filename)));
    String xml = ""; //$NON-NLS-1$
    String line;//  ww  w .  j  a  va  2 s.  c o m
    while ((line = in.readLine()) != null) {
        xml += line + "\n"; //$NON-NLS-1$
    }
    return xml;
}

From source file:WarUtil.java

/**
 * ?????????????????/* w  ww .  j  a  v a  2s  .co m*/
 * 
 * @param path
 * @param caller
 * @return
 */
public static InputStream getResourceAsStream(String path, Class<?> caller) {

    String resource = path;
    if (resource.startsWith(SLASH)) {
        resource = resource.substring(1);
    }

    InputStream is = null;
    File file = new File(path);
    if (file.exists() && file.isFile()) {
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
        }
    }
    if (is == null) {
        ClassLoader tcl = Thread.currentThread().getContextClassLoader();
        if (tcl != null) {
            is = tcl.getResourceAsStream(resource);
        }
    }
    if (is == null) {
        is = caller.getResourceAsStream(path);
    }
    if (is == null) {
        is = ClassLoader.class.getResourceAsStream(path);
    }
    if (is == null) {
        is = ClassLoader.getSystemResourceAsStream(resource);
    }

    return is;
}

From source file:com.kaching.platform.converters.ConstructorAnalysis.java

/**
 * Produces an assignment or field names to values or fails.
 * @throws IllegalConstructorException/*from   w  w w.ja v a2  s . c  o  m*/
 */
static AnalysisResult analyse(Class<?> klass, Constructor<?> constructor) throws IOException {
    Class<?>[] parameterTypes = constructor.getParameterTypes();
    InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
    if (in == null) {
        throw new IllegalArgumentException(format("can not find bytecode for %s", klass));
    }
    return analyse(in, klass.getName().replace('.', '/'), klass.getSuperclass().getName().replace('.', '/'),
            parameterTypes);
}

From source file:com.jwebmp.core.FileTemplates.java

/**
 * Returns the template as a string//w  ww .  ja v  a  2  s.c  om
 *
 * @param referenceClass
 *       The class to reference to locate the file
 * @param templateName
 *       The file without .min.js or .js attached to it
 * @param fileName
 *
 * @return The string for the file
 */
public static StringBuilder getFileTemplate(Class referenceClass, String templateName, String fileName,
        boolean alwaysRefresh) {
    StringBuilder template = TemplateScripts.get(templateName);
    if (template == null || alwaysRefresh) {
        try {
            String templateFileName = fileName;
            if (!(fileName.contains(".html") || fileName.contains(".htm") || fileName.contains(".js")
                    || fileName.contains(".css") || fileName.contains(".min") || fileName.contains(".txt"))) {
                templateFileName += ".js";
            }
            if (templateFileName.endsWith(".min")) {
                templateFileName = templateFileName + ".js";
            }
            String contents = IOUtils.toString(referenceClass.getResourceAsStream(templateFileName),
                    StaticStrings.UTF8_CHARSET);
            setTemplateScript(templateName, new StringBuilder(contents));
        } catch (FileNotFoundException ex) {
            LOG.log(Level.SEVERE,
                    "[Error]-[unable to find template file];[TemplateFile]-[" + templateName
                            + "];[TemplatePath]-[" + referenceClass.getResource(templateName).getPath() + "]",
                    ex);
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, "Unable to read file contents jwangular template File", ex);
        } catch (NullPointerException npe) {
            LOG.log(Level.SEVERE, "template file [" + fileName + "(.js)] not found.", npe);
        } catch (Exception npe) {
            LOG.log(Level.SEVERE, "Exception Rendering Template", npe);
        }
    }
    return TemplateScripts.get(templateName);
}

From source file:org.opencms.ui.CmsVaadinUtils.java

/**
 * Reads the declarative design for a component and localizes it using a messages object.<p>
 *
 * The design will need to be located in the same directory as the component's class and have '.html' as a file extension.
 *
 * @param component the component for which to read the design
 * @param messages the message bundle to use for localization
 * @param macros the macros to use on the HTML template
 *//*from w ww. j  a  va2s .  co  m*/
@SuppressWarnings("resource")
public static void readAndLocalizeDesign(Component component, CmsMessages messages,
        Map<String, String> macros) {

    Class<?> componentClass = component.getClass();
    List<Class<?>> classes = Lists.newArrayList();
    classes.add(componentClass);
    classes.addAll(ClassUtils.getAllSuperclasses(componentClass));
    InputStream designStream = null;
    for (Class<?> cls : classes) {
        if (cls.getName().startsWith("com.vaadin")) {
            break;
        }
        String filename = cls.getSimpleName() + ".html";
        designStream = cls.getResourceAsStream(filename);
        if (designStream != null) {
            break;
        }

    }
    if (designStream == null) {
        throw new IllegalArgumentException("Design not found for : " + component.getClass());
    }
    readAndLocalizeDesign(component, designStream, messages, macros);
}

From source file:org.djer.sensiolab.insight.api.service.DataHelper.java

private InputStream getFile(final String fileName) {
    final Class<?> resourceLoader = this.getClass();
    final InputStream file = resourceLoader.getResourceAsStream(fileName);
    return file;/*from www.j  a  va2 s  .  co m*/
}

From source file:org.arrow.service.WorkflowDeployment.java

public void deploy(String path, Class<?> testClass) {
    BpmnParser driver = new XStreamBpmnParser();
    InputStream stream = testClass.getResourceAsStream(path);
    Definitions definitions = driver.parse(stream);

    repositoryService.deploy(definitions);
}

From source file:net.zcarioca.zcommons.config.source.spi.DefaultConfigSourceServiceProvider.java

private InputStream getResourceAsStream(Class<?> referenceClass, String resourceName) {
    InputStream in = referenceClass.getResourceAsStream(resourceName);
    if (in == null) {
        in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName);
    }/*  ww  w  . ja v  a  2 s  .c o  m*/
    return in;
}