List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:gdt.data.grain.Support.java
/** * Get class resource as input stream. // w ww . ja v a2 s . c o m * @param handler the class * @param resource$ the resource name. * @return input stream. */ public static InputStream getClassResource(Class<?> handler, String resource$) { try { InputStream is = handler.getResourceAsStream(resource$); if (is != null) { //System.out.println("Support:getClassResource:resource stream="+is.toString()); return is; } else { // System.out.println("Support:getClassResource:cannot get embedded resource stream for handler="+handler.getName()); ClassLoader classLoader = handler.getClassLoader(); //if(classLoader!=null) // System.out.println("Support:getClassResource:class loader="+classLoader.toString()); is = classLoader.getResourceAsStream(resource$); //if(is!=null) // System.out.println("Support:getClassResource:resourse stream="+is.toString()); //else // System.out.println("Support:getClassResource:cannot get resource stream"); String handler$ = handler.getName(); //System.out.println("Support:getClassResource:class="+handler$); String handlerName$ = handler.getSimpleName(); //System.out.println("Support:getClassResource:class name="+handlerName$); String handlerPath$ = handler$.replace(".", "/"); //System.out.println("Support:getClassResource:class path="+handlerPath$); String resourcePath$ = "src/" + handlerPath$.replace(handlerName$, resource$); //System.out.println("Support:getClassResource:resource path="+resourcePath$); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); URL resourceUrl = classloader.getResource(resourcePath$); if (resourceUrl != null) { //System.out.println("Support:getClassResource:resource URL="+resourceUrl.toString()); return resourceUrl.openStream(); } else { //System.out.println("Support:getClassResource:cannot get resource URL"); } } } catch (Exception e) { Logger.getLogger(gdt.data.grain.Support.class.getName()).severe(e.toString()); } return null; }
From source file:org.apache.axis2.util.Loader.java
/** * Searches for <code>resource</code> in different * places. The search order is as follows: * <ol>/* w w w . j a va 2 s . c o m*/ * <p><li>Search for <code>resource</code> using the thread context * class loader under Java2. If that fails, search for * <code>resource</code> using the class loader that loaded this * class (<code>Loader</code>). * <p><li>Try one last time with * <code>ClassLoader.getSystemResourceAsStream(resource)</code>, that is is * using the system class loader in JDK 1.2 and virtual machine's * built-in class loader in JDK 1.1. * </ol> * <p/> * * @param resource * @return Returns URL */ static public InputStream getResourceAsStream(String resource) { ClassLoader classLoader = null; try { // Let's try the Thread Context Class Loader classLoader = getTCL(); if (classLoader != null) { log.debug("Trying to find [" + resource + "] using " + classLoader + " class loader."); InputStream is = classLoader.getResourceAsStream(resource); if (is != null) { return is; } } } catch (Throwable t) { log.warn("Caught Exception while in Loader.getResourceAsStream. This may be innocuous.", t); } try { // We could not find resource. Ler us now try with the // classloader that loaded this class. classLoader = Loader.class.getClassLoader(); if (classLoader != null) { log.debug("Trying to find [" + resource + "] using " + classLoader + " class loader."); InputStream is = classLoader.getResourceAsStream(resource); if (is != null) { return is; } } } catch (Throwable t) { log.warn("Caught Exception while in Loader.getResourceAsStream. This may be innocuous.", t); } // Last ditch attempt: get the resource from the class path. It // may be the case that clazz was loaded by the Extentsion class // loader which the parent of the system class loader. Hence the // code below. log.debug("Trying to find [" + resource + "] using ClassLoader.getSystemResourceAsStream()."); return ClassLoader.getSystemResourceAsStream(resource); }
From source file:com.amazonaws.client.regions.RegionUtils.java
/** * Loads a set of region metadata from an XML file stored as a resource * of the given classloader./*from w ww.ja v a 2s .c om*/ * * @param classLoader the class loader to load the resource from * @param name the path to the resource * @return the parsed region metadata * @throws IOException if the resource is not found or cannot be parsed */ public static RegionMetadata loadMetadataFromResource(final ClassLoader classLoader, final String name) throws IOException { InputStream stream = classLoader.getResourceAsStream(name); if (stream == null) { throw new FileNotFoundException("No resource '" + name + "' found."); } try { return loadMetadataFromInputStream(stream); } finally { stream.close(); } }
From source file:org.wso2.carbon.springservices.GenericApplicationContextUtil.java
/** * Method to get the spring application context for a spring service * * @param axisService - spring service/*from w w w . j a v a2s . c o m*/ * @param contextLocation - location of the application context file * @return - GenericApplicationContext for the given spring service * @throws AxisFault */ public static GenericApplicationContext getSpringApplicationContext(AxisService axisService, String contextLocation) throws AxisFault { Parameter appContextParameter = axisService.getParameter(SPRING_APPLICATION_CONTEXT); if (appContextParameter != null) { return (GenericApplicationContext) appContextParameter.getValue(); } else { GenericApplicationContext appContext = new GenericApplicationContext(); ClassLoader classLoader = axisService.getClassLoader(); appContext.setClassLoader(classLoader); ClassLoader prevCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classLoader); XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext); xbdr.setValidating(false); InputStream in = classLoader.getResourceAsStream(contextLocation); if (in == null) { throw new AxisFault("Spring context cannot be located for AxisService"); } xbdr.loadBeanDefinitions(new InputStreamResource(in)); appContext.refresh(); axisService.addParameter(new Parameter(SPRING_APPLICATION_CONTEXT, appContext)); } catch (Exception e) { throw AxisFault.makeFault(e); } finally { // Restore Thread.currentThread().setContextClassLoader(prevCl); } return appContext; } }
From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java
/** * Deregister any JDBC drivers registered by the webapp that the webapp forgot. This is made * unnecessary complex because a) DriverManager checks the class loader of the calling class (it * would be much easier if it checked the context class loader) b) using reflection would create * a dependency on the DriverManager implementation which can, and has, changed. * * We can't just create an instance of JdbcLeakPrevention as it will be loaded by the common * class loader (since it's .class file is in the $CATALINA_HOME/lib directory). This would fail * DriverManager's check on the class loader of the calling class. So, we load the bytes via our * parent class loader but define the class with this class loader so the JdbcLeakPrevention * looks like a webapp class to the DriverManager. * * If only apps cleaned up after themselves... */// ww w .j a v a 2s.com private final static void clearReferencesJdbc(ClassLoader classLoader) { InputStream is = classLoader.getResourceAsStream("com/gigaspaces/internal/utils/JdbcLeakPrevention.class"); // We know roughly how big the class will be (~ 1K) so allow 2k as a // starting point byte[] classBytes = new byte[2048]; int offset = 0; try { int read = is.read(classBytes, offset, classBytes.length - offset); while (read > -1) { offset += read; if (offset == classBytes.length) { // Buffer full - double size byte[] tmp = new byte[classBytes.length * 2]; System.arraycopy(classBytes, 0, tmp, 0, classBytes.length); classBytes = tmp; } read = is.read(classBytes, offset, classBytes.length - offset); } Method defineClassMethod = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class); defineClassMethod.setAccessible(true); Class<?> lpClass = (Class<?>) defineClassMethod.invoke(classLoader, "com.gigaspaces.internal.utils.JdbcLeakPrevention", classBytes, 0, offset); Object obj = lpClass.newInstance(); @SuppressWarnings("unchecked") List<String> driverNames = (List<String>) obj.getClass().getMethod("clearJdbcDriverRegistrations") .invoke(obj); for (String name : driverNames) { if (logger.isLoggable(Level.FINE)) logger.fine("A class loader registered the JDBC driver [" + name + "] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered."); } } catch (Exception e) { //So many things to go wrong above... if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "JDBC driver de-registration failed", e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // ignore } } } }
From source file:org.jfan.an.utils.VersionInfo.java
/** * Loads version information for a package. * * @param pckg the package for which to load version information, * for example "org.apache.http". * The package name should NOT end with a dot. * @param clsldr the classloader to load from, or * <code>null</code> for the thread context classloader * * @return the version information for the argument package, or * <code>null</code> if not available *//*from w w w . j ava 2 s . c om*/ public static VersionInfo loadVersionInfo(final String pckg, final ClassLoader clsldr) { Args.notNull(pckg, "Package identifier"); final ClassLoader cl = clsldr != null ? clsldr : Thread.currentThread().getContextClassLoader(); Properties vip = null; // version info properties, if available try { // org.apache.http becomes // org/apache/http/version.properties final InputStream is = cl.getResourceAsStream(pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE); if (is != null) { try { final Properties props = new Properties(); props.load(is); vip = props; } finally { is.close(); } } } catch (final IOException ex) { // shamelessly munch this exception } VersionInfo result = null; if (vip != null) { result = fromMap(pckg, vip, cl); } return result; }
From source file:com.healthcit.cacure.utils.ResourceBundleMessageSource.java
/** * This method is responsible for loading the property file represented by propertiesFileName * into properties passed in./*from w ww.j ava 2s . co m*/ * * @param propertiesFileName - property file to load * @param properties - ResourceBundleMessageSource object to load props into * @return the ResourceBundleMessageSource instance loaded with properties */ protected static ResourceBundleMessageSource load(String propertiesFileName, ResourceBundleMessageSource properties) { InputStream in; ClassLoader cl = ResourceBundleMessageSource.class.getClassLoader(); if (cl == null) { FileInputStream fis; try { fis = new FileInputStream(new File(propertiesFileName)); } catch (Exception ex) { throw new RuntimeException( "ClassLoader returned null and could not find file=" + propertiesFileName); } in = fis; } else { in = cl.getResourceAsStream(propertiesFileName); } if (in == null) { Logger.getLogger(ResourceBundleMessageSource.class) .warn("Could not read properties file: " + propertiesFileName); } try { properties.load(in); if (null != in) { in.close(); } } catch (Exception e) { Logger.getLogger(ResourceBundleMessageSource.class) .warn("Could not read properties file: " + propertiesFileName); } return properties; }
From source file:it.cnr.icar.eric.common.AbstractProperties.java
/** * Loads properties from resourceName (from classpath) to 'properties'. * * @param classLoader the ClassLoader to use when getting resource * @param properties existing properties (might get overwritten) * @param resourceName the resource name, to be loaded from classpath * @return True if load ok. False otherwise. *//*w w w . ja va 2 s. co m*/ protected static boolean loadResourceProperties(ClassLoader classLoader, Properties properties, String resourceName) { log.trace(CommonResourceBundle.getInstance().getString("message.LoadPropsFromClasspath", new Object[] { resourceName })); try { InputStream is = classLoader.getResourceAsStream(resourceName); if (is == null) { throw new JAXRException(CommonResourceBundle.getInstance().getString("message.resourceNotFound", new String[] { resourceName })); } properties.load(is); is.close(); return true; } catch (Exception e) { log.debug(CommonResourceBundle.getInstance().getString("message.IgnoringDueToException", new Object[] { resourceName, e.toString() })); return false; } }
From source file:org.wso2.carbon.springservices.GenericApplicationContextUtil.java
public static GenericApplicationContext getSpringApplicationContextClassPath(ClassLoader classLoader, String relPath) throws AxisFault { GenericApplicationContext appContext = new GenericApplicationContext(); appContext.setClassLoader(classLoader); ClassLoader prevCl = Thread.currentThread().getContextClassLoader(); try {/*from www .j a v a 2 s. co m*/ Thread.currentThread().setContextClassLoader(classLoader); XmlBeanDefinitionReader xbdr = new XmlBeanDefinitionReader(appContext); xbdr.setValidating(false); InputStream in = classLoader.getResourceAsStream(relPath); if (in == null) { throw new AxisFault("Spring context cannot be located for AxisService"); } xbdr.loadBeanDefinitions(new InputStreamResource(in)); appContext.refresh(); } catch (Exception e) { throw AxisFault.makeFault(e); } finally { // Restore Thread.currentThread().setContextClassLoader(prevCl); } return appContext; }
From source file:com.aurel.track.lucene.util.StringUtil.java
public static String read(ClassLoader classLoader, String name) throws IOException { return read(classLoader.getResourceAsStream(name)); }