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:be.fedict.eid.tsl.BelgianTrustServiceListFactory.java

private static X509Certificate loadCertificateFromResource(String resourceName) {
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("could not load certificate resource: " + resourceName);
    }/*from w w w.j a v a 2 s . c om*/
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(certificateInputStream);
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("certificate factory error: " + e.getMessage(), e);
    }
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the Inputstream from the resource. Wrapes the Class.getResourceAsStream(String)-method.
 *
 * @param name// www  . java2  s  .  c  om
 *            The name from the resource.
 * @param obj
 *            The Object.
 * @return The resource or null if the resource does not exists.
 */
public static InputStream getResourceAsStream(final String name, final Object obj) {
    InputStream inputStream = obj.getClass().getResourceAsStream(name);
    if (null == inputStream) {
        final ClassLoader loader = ClassExtensions.getClassLoader(obj);
        inputStream = loader.getResourceAsStream(name);
    }
    return inputStream;
}

From source file:de.alpharogroup.lang.ClassExtensions.java

/**
 * Gives the Inputstream from the resource. Wrapes the Class.getResourceAsStream(String)-method.
 *
 * @param name/*from  w  w w .  jav  a2 s  .  com*/
 *            The name from the resource.
 * @return The resource or null if the resource does not exists.
 */
public static InputStream getResourceAsStream(final String name) {
    final ClassLoader loader = ClassExtensions.getClassLoader();
    final InputStream inputStream = loader.getResourceAsStream(name);
    return inputStream;
}

From source file:org.apache.axiom.om.util.StAXUtils.java

/**
 * Load factory properties from a resource. The context class loader is used to locate
 * the resource. The method converts boolean and integer values to the right Java types.
 * All other values are returned as strings.
 * /* w  w w  . j  av a  2  s  . co m*/
 * @param name
 * @return
 */
// This has package access since it is used from within anonymous inner classes
static Map loadFactoryProperties(String name) {
    ClassLoader cl = getContextClassLoader();
    InputStream in = cl.getResourceAsStream(name);
    if (in == null) {
        return null;
    } else {
        try {
            Properties rawProps = new Properties();
            Map props = new HashMap();
            rawProps.load(in);
            for (Iterator it = rawProps.entrySet().iterator(); it.hasNext();) {
                Map.Entry entry = (Map.Entry) it.next();
                String strValue = (String) entry.getValue();
                Object value;
                if (strValue.equals("true")) {
                    value = Boolean.TRUE;
                } else if (strValue.equals("false")) {
                    value = Boolean.FALSE;
                } else {
                    try {
                        value = Integer.valueOf(strValue);
                    } catch (NumberFormatException ex) {
                        value = strValue;
                    }
                }
                props.put(entry.getKey(), value);
            }
            if (log.isDebugEnabled()) {
                log.debug("Loaded factory properties from " + name + ": " + props);
            }
            return props;
        } catch (IOException ex) {
            log.error("Failed to read " + name, ex);
            return null;
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
}

From source file:fr.landel.utils.io.FileUtils.java

/**
 * Get the content of a file from class loader (from classpath root).
 * /*from  w ww  .  ja v a2s.  c om*/
 * @param path
 *            The path
 * @param charset
 *            The file charset
 * @param classLoader
 *            The class loader (advice: use a Class in the same JAR of the
 *            file to load), if null use the class loader of the current
 *            thread
 * @return The buffered content
 * @throws IOException
 *             Exception thrown if problems occurs during reading
 */
public static StringBuilder getFileContent(final String path, final Charset charset,
        final ClassLoader classLoader) throws IOException {
    Assertor.that(path).isNotBlank().orElseThrow("The 'path' parameter cannot be null or blank");
    Assertor.that(charset).isNotNull().orElseThrow("The 'charset' parameter cannot be null");

    ClassLoader loader = classLoader;

    final StringBuilder content = new StringBuilder();

    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }

    try (InputStream inputStream = loader.getResourceAsStream(path)) {
        loadContent(content, inputStream, charset);
    }

    return content;
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 * Tries to open an input stream for a resource.
 *  /*from   w w w .j av  a  2 s . co m*/
 * @param resource the resource name
 * @return an input stream for the resource or <code>null</code> if the resource was not found
 */
public static InputStream getResourceInputStream(String resource) {
    InputStream is = null;

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader != null) {
        is = classLoader.getResourceAsStream(resource);
    }

    if (is == null) {
        classLoader = JRLoader.class.getClassLoader();
        if (classLoader != null) {
            is = classLoader.getResourceAsStream(resource);
        }

        if (is == null) {
            is = JRPropertiesUtil.class.getResourceAsStream("/" + resource);
        }
    }

    return is;
}

From source file:ml.dmlc.xgboost4j.java.NativeLibrary.java

private static File extract(String libPath, ClassLoader classLoader)
        throws IOException, IllegalArgumentException {

    // Split filename to prefix and suffix (extension)
    String filename = libPath.substring(libPath.lastIndexOf('/') + 1);
    int lastDotIdx = filename.lastIndexOf('.');
    String prefix = "";
    String suffix = null;/* w w w .  j a v  a 2 s .  c o  m*/
    if (lastDotIdx >= 0 && lastDotIdx < filename.length() - 1) {
        prefix = filename.substring(0, lastDotIdx);
        suffix = filename.substring(lastDotIdx);
    }

    // Prepare temporary file
    File temp = File.createTempFile(prefix, suffix);
    temp.deleteOnExit();

    // Open and check input stream
    InputStream is = classLoader.getResourceAsStream(libPath);
    if (is == null) {
        throw new FileNotFoundException("File " + libPath + " was not found inside JAR.");
    }

    // Open output stream and copy data between source file in JAR and the temporary file
    try {
        Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } finally {
        is.close();
    }

    return temp;
}

From source file:org.apache.axis2.jaxws.description.impl.DescriptionUtils.java

/**
 * Get the InputStream from the relative path and classloader
 * @param path/*from  ww w. j  a v  a2 s .c  o  m*/
 * @param classLoader
 * @return
 */
private static InputStream getInputStream(String path, ClassLoader classLoader) {
    if (log.isDebugEnabled()) {
        log.debug("Start getInputStream with (" + path + ") and classloader (" + classLoader + ")");
    }
    InputStream configStream = classLoader.getResourceAsStream(path);
    if (configStream == null) {
        // try another classloader
        ClassLoader cl = System.class.getClassLoader();
        if (log.isDebugEnabled()) {
            log.debug("Attempting with System classloader (" + cl + ")");
        }
        if (cl != null) {
            configStream = cl.getResourceAsStream(path);
        }
    }
    if (configStream == null) {
        // and another classloader
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (log.isDebugEnabled()) {
            log.debug("Attempting with current thread " + "classloader (" + cl + ")");
        }
        if (cl != null) {
            configStream = cl.getResourceAsStream(path);
        }
    }
    return configStream;
}

From source file:net.sf.eclipsecs.core.config.meta.MetadataFactory.java

/**
 * Initializes the meta data from the xml file.
 *
 * @throws CheckstylePluginException/*from   w w w .ja va 2 s .c o m*/
 *             error loading the meta data file
 */
private static void doInitialization() throws CheckstylePluginException {

    ClassLoader classLoader = CheckstylePlugin.getDefault().getAddonExtensionClassLoader();
    Collection<String> potentialMetadataFiles = getAllPotentialMetadataFiles(classLoader);
    for (String metadataFile : potentialMetadataFiles) {

        InputStream metadataStream = null;

        try {
            metadataStream = classLoader.getResourceAsStream(metadataFile);
            if (metadataStream != null) {

                ResourceBundle metadataBundle = getMetadataI18NBundle(metadataFile, classLoader);
                parseMetadata(metadataStream, metadataBundle);
            }
        } catch (DocumentException e) {
            CheckstyleLog.log(e, "Could not read metadata " + metadataFile); //$NON-NLS-1$
        } finally {
            IOUtils.closeQuietly(metadataStream);
        }
    }
}

From source file:com.att.aro.core.util.Util.java

/**
 * Pull the given file name from Jar and write into the AroLibrary
 *
 * @param filename/*from ww  w. j a v a 2  s . co  m*/
 */
public static String makeLibFilesFromJar(String filename) {
    String homePath = System.getProperty("user.home");
    String targetLibFolder = homePath + File.separator + "VideoOptimizerLibrary";
    ClassLoader aroClassloader = Util.class.getClassLoader();
    try {
        InputStream is = aroClassloader.getResourceAsStream(filename);
        if (is != null) {
            File libfolder = new File(targetLibFolder);
            //            if (!libfolder.exists() || !libfolder.isDirectory() || new File(libfolder+File.separator+filename).exists()) {
            targetLibFolder = makeLibFolder(filename, libfolder);
            if (targetLibFolder != null)
                makeLibFile(filename, targetLibFolder, is);
            else
                return null;
            // }
        }
        return targetLibFolder;
    } catch (Exception e) {
        return null;
    }
}