List of usage examples for java.lang ClassLoader getResourceAsStream
public InputStream getResourceAsStream(String name)
From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java
/** * Loads properties from resource with given name. * * @param name/*from w w w . ja va 2s. co m*/ * the resource name * @return properties loaded from resource * @throws java.io.IOException * if an error occurred when reading properties file * * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.util.Properties#load(java.io.InputStream) */ public static Properties loadPropertiesResource(String name) throws IOException { Properties rProps = new Properties(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream ins = loader.getResourceAsStream(name); try { rProps.load(ins); } finally { close(ins); } return rProps; }
From source file:ee.sk.digidoc.SignedDoc.java
/** * Reads the cert from a file, URL or from another * location somewhere in the CLASSPATH such as * in the librarys jar file./*from www. j ava 2s. co m*/ * @param certLocation certificates file name, * or URL. You can use url in form jar://<location> to read * a certificate from the car file or some other location in the * CLASSPATH * @return certificate object */ public static X509Certificate readCertificate(String certLocation) throws DigiDocException { X509Certificate cert = null; InputStream isCert = null; try { URL url = null; if (certLocation.startsWith("http")) { url = new URL(certLocation); isCert = url.openStream(); } else if (certLocation.startsWith("jar://")) { ClassLoader cl = ConfigManager.instance().getClass().getClassLoader(); isCert = cl.getResourceAsStream(certLocation.substring(6)); } else { isCert = new FileInputStream(certLocation); } CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); cert = (X509Certificate) certificateFactory.generateCertificate(isCert); isCert.close(); isCert = null; } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_READ_FILE); } finally { if (isCert != null) { try { isCert.close(); } catch (Exception ex2) { m_logger.error("Error closing streams: " + ex2); } } } return cert; }
From source file:org.apache.ignite.internal.util.spring.IgniteSpringHelperImpl.java
/** {@inheritDoc} */ @Override//from w w w. ja v a 2 s .co m public String userVersion(ClassLoader ldr, IgniteLogger log) { assert ldr != null; assert log != null; // For system class loader return cached version. if (ldr == U.gridClassLoader() && SYS_LDR_VER.get() != null) return SYS_LDR_VER.get(); String usrVer = U.DFLT_USER_VERSION; InputStream in = ldr.getResourceAsStream(IGNITE_XML_PATH); if (in != null) { // Note: use ByteArrayResource instead of InputStreamResource because // InputStreamResource doesn't work. ByteArrayOutputStream out = new ByteArrayOutputStream(); try { U.copy(in, out); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(new ByteArrayResource(out.toByteArray())); usrVer = (String) factory.getBean("userVersion"); usrVer = usrVer == null ? U.DFLT_USER_VERSION : usrVer.trim(); } catch (NoSuchBeanDefinitionException ignored) { if (log.isInfoEnabled()) log.info("User version is not explicitly defined (will use default version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']'); usrVer = U.DFLT_USER_VERSION; } catch (BeansException e) { U.error(log, "Failed to parse Spring XML file (will use default user version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']', e); usrVer = U.DFLT_USER_VERSION; } catch (IOException e) { U.error(log, "Failed to read Spring XML file (will use default user version) [file=" + IGNITE_XML_PATH + ", clsLdr=" + ldr + ']', e); usrVer = U.DFLT_USER_VERSION; } finally { U.close(out, log); } } // For system class loader return cached version. if (ldr == U.gridClassLoader()) SYS_LDR_VER.compareAndSet(null, usrVer); return usrVer; }
From source file:org.acmsl.commons.regexpplugin.RegexpManager.java
/** * Retrieves the stream associated to the resource * whose name is given, using a concrete class loader. * @param loader the class loader./*ww w . j av a 2 s. c om*/ * @param name the resource name. * @return the stream. */ @Nullable protected InputStream getResourceAsStream(@Nullable final ClassLoader loader, @NotNull final String name) { return AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run() { final InputStream result; if (loader != null) { result = loader.getResourceAsStream(name); } else { result = ClassLoader.getSystemResourceAsStream(name); } return result; } }); }
From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java
private InputStream getStream(String name, ClassLoader loader) { if (loader == null) { return Thread.currentThread().getContextClassLoader().getResourceAsStream(name); }/*from w ww .j a va 2s .com*/ return loader.getResourceAsStream(name); }
From source file:geva.Main.AbstractRun.java
/** * Read the default properties. Replace or add properties from the command line. * If the file is not found on the file system class loading from the jar is tried * @param args arguments//from w ww . j a va 2 s. co m */ @SuppressWarnings({ "IOResourceOpenedButNotSafelyClosed" }) protected void readProperties(String[] args) { ClassLoader loader; InputStream in; try { this.properties = new Properties(); File f = new File(this.propertiesFilePath); if (!f.exists()) { // try classloading loader = ClassLoader.getSystemClassLoader(); in = loader.getResourceAsStream(this.propertiesFilePath); this.properties.load(in); logger.info("Loading properties from ClassLoader and: " + this.propertiesFilePath); } else { FileInputStream is = new FileInputStream(f); this.properties.load(is); logger.info("Loading properties from file system: " + this.propertiesFilePath); } if (args != null) { for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-") && args.length > (i + 1) && !args[i].equals(Constants.VERSION_FLAG)) { this.properties.setProperty(args[i].substring(1), args[i + 1]); i++; } } } for (Enumeration e = properties.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); logger.info(key + "=" + properties.getProperty(key, "Not defined")); } } catch (IOException e) { loader = ClassLoader.getSystemClassLoader(); in = loader.getResourceAsStream(this.propertiesFilePath); try { this.properties.load(in); } catch (Exception ex) { System.err.println("Properties reading output caught:" + ex); } System.err.println(MessageFormat.format("Using default: {0} Bad:{1} Could not load:{2}", this.propertiesFilePath, this.propertiesFilePath, e)); } catch (Exception e) { System.err .println("Could not commandline argument:" + e + " properties path:" + this.propertiesFilePath); } }
From source file:geva.Mapper.ContextFreeGrammar.java
/**Read a BNF file to a string and call readBNFString to parse the grammar * string. Find file from the class loader * @param file_name name of file//from w ww .j a v a2s . co m * @return parse success */ @SuppressWarnings({ "UnusedReturnValue", "IOResourceOpenedButNotSafelyClosed" }) public boolean readBNFFile(String file_name) throws MalformedGrammarException { StringBuffer contents = new StringBuffer(); try { int bufferSize = 1024; String line; ClassLoader loader = ClassLoader.getSystemClassLoader(); InputStream is = loader.getResourceAsStream(file_name); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr, bufferSize); assert (br != null) : "Cannot load resource from classloader: " + file_name; while ((line = br.readLine()) != null) { contents.append(line); //readLine removes the lineseparator from http://www.javapractices.com/Topic42.cjp contents.append(System.getProperty("line.separator")); } br.close(); } catch (FileNotFoundException e) { System.err.println("Grammar File not found: " + file_name); return false; } catch (NullPointerException e) { System.err.println("Grammar File not found in classloader: " + file_name); return false; } catch (IOException e) { System.err.println("IOException when looking for grammar file: " + file_name); return false; } contents.append("\n"); return readBNFString(contents.toString()); }
From source file:com.github.nlloyd.hornofmongo.MongoScope.java
protected Reader loadFromClasspath(String filePath) { Reader reader = null;/*from w ww .ja v a 2 s . c o m*/ ClassLoader loader = this.getClass().getClassLoader(); reader = new BufferedReader(new InputStreamReader(loader.getResourceAsStream(filePath))); return reader; }
From source file:org.globus.security.provider.TestPEMFileBasedKeyStore.java
@BeforeClass public void setUp() throws Exception { ClassLoader loader = TestPEMFileBasedKeyStore.class.getClassLoader(); String[] trustedCertFilenames = new String[] { "testTrustStore/1c3f2ca8.0", "testTrustStore/b38b4d8c.0" }; this.trustedDirectory = new DirSetupUtil(trustedCertFilenames); this.trustedDirectory.createTempDirectory(); this.trustedDirectory.copy(); for (String trustedCertFilename : trustedCertFilenames) { InputStream in = null;// w w w. j av a 2s . c o m try { in = loader.getResourceAsStream(trustedCertFilename); if (in == null) { throw new Exception("Unable to load: " + trustedCertFilename); } this.trustedCertificates.put(this.trustedDirectory.getFileSetupUtil(trustedCertFilename), CertificateLoadUtil.loadCertificate(in)); } finally { if (in != null) { in.close(); } } } String[] defaultTrustedCert = new String[] { "testTrustStore/d1b603c3.0" }; this.defaultTrustedDirectory = new DirSetupUtil(defaultTrustedCert); this.defaultTrustedDirectory.createTempDirectory(); this.defaultTrustedDirectory.copy(); for (String aDefaultTrustedCert : defaultTrustedCert) { InputStream in = null; try { in = loader.getResourceAsStream(aDefaultTrustedCert); if (in == null) { throw new Exception("Unable to load: " + aDefaultTrustedCert); } this.trustedCertificates.put(this.defaultTrustedDirectory.getFileSetupUtil(aDefaultTrustedCert), CertificateLoadUtil.loadCertificate(in)); } finally { if (in != null) { in.close(); } } } // String proxyFilename1 = "validatorTest/gsi2fullproxy.pem"; String proxyFilename1 = "validatorTest/gsi3independentFromLimitedProxy.pem"; this.proxyFile1 = new FileSetupUtil(proxyFilename1); this.proxyFile1.copyFileToTemp(); this.proxyCertificates.put(this.proxyFile1, new X509Credential(loader.getResourceAsStream(proxyFilename1), loader.getResourceAsStream(proxyFilename1))); String proxyFilename2 = "validatorTest/gsi3FromPathOneProxy.pem"; this.proxyFile2 = new FileSetupUtil(proxyFilename2); this.proxyFile2.copyFileToTemp(); this.proxyCertificates.put(this.proxyFile2, new X509Credential(loader.getResourceAsStream(proxyFilename2), loader.getResourceAsStream(proxyFilename2))); String certFilename = "validatorTest/testeec2.pem"; this.certFile = new FileSetupUtil(certFilename); this.certFile.copyFileToTemp(); String keyFilename = "validatorTest/testeec2-private.pem"; this.keyFile = new FileSetupUtil(keyFilename); this.keyFile.copyFileToTemp(); String keyEncFilename = "validatorTest/testeec2-private-enc.pem"; this.keyEncFile = new FileSetupUtil(keyEncFilename); this.keyEncFile.copyFileToTemp(); Security.addProvider(new GlobusProvider()); }
From source file:com.elecnor.ecosystem.serviceimpl.LicenseDirectoryServiceImpl.java
public Integer readFromHeader(ArrayList<String> excelHeader, String valToCheck) { int result = 0; try {/*w w w. j av a 2 s. co m*/ ClassLoader cl = PropertyFileReader.class.getClassLoader(); InputStream in = cl.getResourceAsStream("header.properties"); Properties prop = new Properties(); prop.load(in); if (valToCheck == null) { String excelUploadedHeader = excelHeader.toString().substring(1, excelHeader.toString().indexOf("]")); if (excelUploadedHeader .equalsIgnoreCase(prop.getProperty(ConstantUtil.STATE_LICENSE_EXCEL_FORMAT))) { result = 1; } else { result = 0; } } else { return Integer.valueOf(prop.getProperty(valToCheck)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; }