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.taobao.diamond.common.Constants.java

/** ?-D > env > diamond.properties  */
public static void init() {
    File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress");
    if (!diamondFile.exists()) {
        diamondFile.getParentFile().mkdirs();
        try (OutputStream out = new FileOutputStream(diamondFile)) {
            out.write("localhost".getBytes());
        } catch (IOException e) {
            throw new IllegalStateException(diamondFile.toString(), e);
        }//from w  w w  .  j  a v  a  2  s.  c  o  m
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
            fields.add(field);
        }
    }

    Properties props = new Properties();
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = Constants.class.getClassLoader();
        try (InputStream in = cl.getResourceAsStream("diamond.properties")) {
            if (in != null)
                props.load(in);
        } catch (IOException e) {
            log.warn("load diamond.properties", e);
        }
    }
    props.putAll(System.getenv());
    props.putAll(System.getProperties());

    Map<String, Object> old = new HashMap<>();
    try {
        for (Field field : fields) {
            if (!props.containsKey(field.getName()))
                continue;
            old.put(field.getName(), field.get(Constants.class));

            String value = props.getProperty(field.getName());
            Class<?> clazz = field.getType();
            if (String.class.equals(clazz)) {
                field.set(Constraints.class, value);
            } else if (int.class.equals(clazz)) {
                if (value != null) {
                    field.set(Constraints.class, Integer.parseInt(value));
                }
            } else {
                throw new IllegalArgumentException(field + "  " + value + " ?");
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE");
    setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE");
    setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME");
}

From source file:com.taobao.tddl.common.config.impl.DefaultConfigDataHandlerFactory.java

private static void findSpecifiedConfigHandlerClass() {
    ClassLoader currentCL = getBaseClassLoader();
    InputStream resource;/*from   w ww .ja v  a2  s. co m*/
    for (;;) {
        if (currentCL != null) {
            resource = currentCL.getResourceAsStream(propertyFile);
        } else {
            resource = ClassLoader.getSystemResourceAsStream(propertyFile);
            break;
        }

        if (null != resource) {
            break;
        } else {
            currentCL = currentCL.getParent();
        }
    }

    if (null != resource) {
        prop = new Properties();
        try {
            prop.load(resource);
            handlerClassName = prop.getProperty(HANDLER_CLASS);
            if (null == handlerClassName || "".equals(handlerClassName)) {
                handlerClassName = DEFAULT_HANDLER_CLASS;
            }
        } catch (IOException e) {
            log.error("properties can not load " + propertyFile);
        }
    } else {
        handlerClassName = DEFAULT_HANDLER_CLASS;
    }
}

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

/**
 * Loads the properties from a given property file path
 *
 * @param filePath Path of the property file
 * @return Properties loaded from given file
 *//*from w  w w .  j a  v  a 2  s  .  c o  m*/
public static Properties loadProperties(String filePath) {

    Properties properties = new Properties();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

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

    InputStream 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 {
            properties.load(in);
        } catch (IOException e) {
            String msg = "Error loading properties from a file at :" + filePath;
            log.error(msg, e);
            throw new SecureVaultException(msg, e);
        }
    }
    return properties;
}

From source file:be.fedict.trust.BelgianTrustValidatorFactory.java

private static X509Certificate loadCertificate(String resourceName) {
    LOG.debug("loading certificate: " + resourceName);
    Thread currentThread = Thread.currentThread();
    ClassLoader classLoader = currentThread.getContextClassLoader();
    InputStream certificateInputStream = classLoader.getResourceAsStream(resourceName);
    if (null == certificateInputStream) {
        throw new IllegalArgumentException("resource not found: " + resourceName);
    }/*  w  w  w  . ja  v a2  s.  c  o m*/
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(certificateInputStream);
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:org.apache.asterix.runtime.evaluators.staticcodegen.CodeGenUtil.java

/**
 * Gets the input stream from a class file.
 *
 * @param className,/*from  www  .  j  ava  2s . c om*/
 *            the name of a class.
 * @param classLoader,
 *            the corresponding class loader.
 * @return the input stream.
 */
private static InputStream getResourceStream(String className, ClassLoader classLoader) {
    return classLoader.getResourceAsStream(className.replace('.', '/') + ".class");
}

From source file:org.apache.openaz.xacml.util.FactoryFinder.java

/**
 * Attempts to load a class using the Jar Service Provider Mechanism
 *
 * @param factoryId the <code>String</code> factory id of the object to load
 * @param classExtends the <code>Class</code> the object must extend
 * @return an instance of the <code>Class</code> referenced by the factory ID
 * @throws FactoryException/*ww  w .jav  a 2 s  .  c  o m*/
 */
private static <T> T findJarServiceProvider(String factoryId, Class<T> classExtends, Properties xacmlProperties)
        throws FactoryException {
    String serviceId = "META-INF/services/" + factoryId;
    InputStream is = null;

    /*
     * First try using the Context ClassLoader
     */
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl != null) {
        is = cl.getResourceAsStream(serviceId);
        if (is == null) {
            /*
             * Fall back to the current ClassLoader
             */
            cl = FactoryFinder.class.getClassLoader();
            is = cl.getResourceAsStream(serviceId);
        }
    } else {
        /*
         * No Context ClassLoader, try the current ClassLoader
         */
        cl = FactoryFinder.class.getClassLoader();
        is = cl.getResourceAsStream(serviceId);
    }

    if (is == null) {
        /*
         * No resource provider found
         */
        return null;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Found jar resource=" + serviceId + " using ClassLoader: " + cl);
    }

    /*
     * Read from the stream
     */
    BufferedReader rd;
    try {
        rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    } catch (UnsupportedEncodingException ex) {
        rd = new BufferedReader(new InputStreamReader(is));
    }

    String factoryClassName = null;
    try {
        factoryClassName = rd.readLine();
    } catch (IOException ex) {
        logger.error("IOException reading resource stream: " + ex.getMessage(), ex);
        return null;
    } finally {
        try {
            if (rd != null) {
                rd.close();
            }
        } catch (IOException e) {
            // nothing we can do with this
            logger.error("Unable to close stream: " + e, e);
        }
    }

    if (factoryClassName != null && !"".equals(factoryClassName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Found in resource, value=" + factoryClassName);
        }
        return newInstance(factoryClassName, classExtends, cl, false, xacmlProperties);
    }

    return null;
}

From source file:net.ymate.platform.core.support.ConfigBuilder.java

public static ConfigBuilder system() {
    final Properties __props = new Properties();
    InputStream _in = null;/*from   ww  w  . j  a  v  a2  s  . c  om*/
    try {
        ClassLoader _classLoader = ConfigBuilder.class.getClassLoader();
        if (RuntimeUtils.isWindows()) {
            _in = _classLoader.getResourceAsStream("ymp-conf_WIN.properties");
        } else if (RuntimeUtils.isUnixOrLinux()) {
            _in = _classLoader.getResourceAsStream("ymp-conf_UNIX.properties");
        }
        //
        if (_in == null) {
            _in = _classLoader.getResourceAsStream("ymp-conf.properties");
        }
        if (_in != null) {
            __props.load(_in);
        }
        return create(__props);
    } catch (Exception e) {
        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
    } finally {
        try {
            if (_in != null)
                _in.close();
        } catch (Exception ignored) {
        }
    }
}

From source file:SecuritySupport.java

static InputStream getResourceAsStream(final ClassLoader cl, final String name) {
    return (InputStream) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            InputStream ris;//  www . jav  a2 s  .  c o m
            if (cl == null) {
                ris = ClassLoader.getSystemResourceAsStream(name);
            } else {
                ris = cl.getResourceAsStream(name);
            }
            return ris;
        }
    });
}

From source file:Resources.java

/**
 * Returns a resource on the classpath as a Stream object
 *
 * @param loader   The classloader used to load the resource
 * @param resource The resource to find/*from   w  w w. j a  v  a 2  s .  c  o  m*/
 * @return The resource
 * @throws IOException If the resource cannot be found or read
 */
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
    InputStream in = null;
    if (loader != null)
        in = loader.getResourceAsStream(resource);
    if (in == null)
        in = ClassLoader.getSystemResourceAsStream(resource);
    if (in == null)
        throw new IOException("Could not find resource " + resource);
    return in;
}

From source file:org.fusesource.meshkeeper.distribution.PluginClassLoader.java

private static Properties loadProperties(ClassLoader cl, String uri) throws IOException {
    InputStream in = cl.getResourceAsStream(uri);
    if (in == null) {
        return null;
    }//  w w w  .  j  av a 2 s .c  o m

    // lets load the file
    BufferedInputStream reader = new BufferedInputStream(in);
    try {
        Properties properties = new Properties();
        properties.load(reader);
        return properties;
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
        }
    }
}