List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:dk.statsbiblioteket.util.XPropertiesTest.java
/** * Helper method for deleating a file in the CLASSPATH * * @param resourceName the name of the resource to delete * @return true if the resource was deleted *//*from w w w . ja va 2 s . com*/ protected boolean deleteResource(String resourceName) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL resourceURL = loader.getResource(resourceName); if (resourceURL == null) { File f = new File(resourceName); if (f.exists()) { return f.delete(); } log.error("Could not delete '" + f.getAbsoluteFile() + "'"); return false; } return new File(resourceURL.getFile()).delete(); }
From source file:org.apache.hadoop.crypto.key.JavaKeyStoreProvider.java
private JavaKeyStoreProvider(URI uri, Configuration conf) throws IOException { super(conf);// w ww .ja v a 2 s .c o m this.uri = uri; path = ProviderUtils.unnestUri(uri); fs = path.getFileSystem(conf); // Get the password file from the conf, if not present from the user's // environment var if (System.getenv().containsKey(KEYSTORE_PASSWORD_ENV_VAR)) { password = System.getenv(KEYSTORE_PASSWORD_ENV_VAR).toCharArray(); } if (password == null) { String pwFile = conf.get(KEYSTORE_PASSWORD_FILE_KEY); if (pwFile != null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL pwdFile = cl.getResource(pwFile); if (pwdFile == null) { // Provided Password file does not exist throw new IOException("Password file does not exists"); } try (InputStream is = pwdFile.openStream()) { password = IOUtils.toString(is).trim().toCharArray(); } } } if (password == null) { password = KEYSTORE_PASSWORD_DEFAULT; } try { Path oldPath = constructOldPath(path); Path newPath = constructNewPath(path); keyStore = KeyStore.getInstance(SCHEME_NAME); FsPermission perm = null; if (fs.exists(path)) { // flush did not proceed to completion // _NEW should not exist if (fs.exists(newPath)) { throw new IOException(String.format("Keystore not loaded due to some inconsistency " + "('%s' and '%s' should not exist together)!!", path, newPath)); } perm = tryLoadFromPath(path, oldPath); } else { perm = tryLoadIncompleteFlush(oldPath, newPath); } // Need to save off permissions in case we need to // rewrite the keystore in flush() permissions = perm; } catch (KeyStoreException e) { throw new IOException("Can't create keystore", e); } catch (NoSuchAlgorithmException e) { throw new IOException("Can't load keystore " + path, e); } catch (CertificateException e) { throw new IOException("Can't load keystore " + path, e); } ReadWriteLock lock = new ReentrantReadWriteLock(true); readLock = lock.readLock(); writeLock = lock.writeLock(); }
From source file:interactivespaces.launcher.bootstrap.InteractiveSpacesFrameworkBootstrap.java
/** * Simple method to parse META-INF/services file for framework factory. Currently, it assumes the first non-commented * line is the class nodeName of the framework factory implementation. * * @return the created <tt>FrameworkFactory</tt> instance * * @throws Exception/* w w w.j av a 2 s . co m*/ * if any errors occur. **/ private FrameworkFactory getFrameworkFactory() throws Exception { // using the ServiceLoader to get a factory. ClassLoader classLoader = InteractiveSpacesFrameworkBootstrap.class.getClassLoader(); URL url = classLoader.getResource(OSGI_FRAMEWORK_LAUNCH_FRAMEWORK_FACTORY); if (url != null) { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); try { for (String s = br.readLine(); s != null; s = br.readLine()) { // Try to load first non-empty, non-commented line. s = s.trim(); if (!s.isEmpty() && s.charAt(0) != '#') { return (FrameworkFactory) classLoader.loadClass(s).newInstance(); } } } finally { if (br != null) { br.close(); } } } throw new Exception("Could not find framework factory."); }
From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java
private void createHttpFSServer(boolean addDelegationTokenAuthHandler) throws Exception { File homeDir = TestDirHelper.getTestDir(); Assert.assertTrue(new File(homeDir, "conf").mkdir()); Assert.assertTrue(new File(homeDir, "log").mkdir()); Assert.assertTrue(new File(homeDir, "temp").mkdir()); HttpFSServerWebApp.setHomeDirForCurrentThread(homeDir.getAbsolutePath()); File secretFile = new File(new File(homeDir, "conf"), "secret"); Writer w = new FileWriter(secretFile); w.write("secret"); w.close();/*from w w w .ja v a 2 s . c o m*/ //HDFS configuration File hadoopConfDir = new File(new File(homeDir, "conf"), "hadoop-conf"); hadoopConfDir.mkdirs(); String fsDefaultName = TestHdfsHelper.getHdfsConf().get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY); Configuration conf = new Configuration(false); conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsDefaultName); conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true); conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_XATTRS_ENABLED_KEY, true); File hdfsSite = new File(hadoopConfDir, "hdfs-site.xml"); OutputStream os = new FileOutputStream(hdfsSite); conf.writeXml(os); os.close(); //HTTPFS configuration conf = new Configuration(false); if (addDelegationTokenAuthHandler) { conf.set("httpfs.authentication.type", HttpFSKerberosAuthenticationHandlerForTesting.class.getName()); } conf.set("httpfs.services.ext", MockGroups.class.getName()); conf.set("httpfs.admin.group", HadoopUsersConfTestHelper.getHadoopUserGroups(HadoopUsersConfTestHelper.getHadoopUsers()[0])[0]); conf.set("httpfs.proxyuser." + HadoopUsersConfTestHelper.getHadoopProxyUser() + ".groups", HadoopUsersConfTestHelper.getHadoopProxyUserGroups()); conf.set("httpfs.proxyuser." + HadoopUsersConfTestHelper.getHadoopProxyUser() + ".hosts", HadoopUsersConfTestHelper.getHadoopProxyUserHosts()); conf.set("httpfs.authentication.signature.secret.file", secretFile.getAbsolutePath()); conf.set("httpfs.hadoop.config.dir", hadoopConfDir.toString()); File httpfsSite = new File(new File(homeDir, "conf"), "httpfs-site.xml"); os = new FileOutputStream(httpfsSite); conf.writeXml(os); os.close(); ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("webapp"); WebAppContext context = new WebAppContext(url.getPath(), "/webhdfs"); Server server = TestJettyHelper.getJettyServer(); server.addHandler(context); server.start(); if (addDelegationTokenAuthHandler) { HttpFSServerWebApp.get().setAuthority(TestJettyHelper.getAuthority()); } }
From source file:io.siddhi.extension.io.file.FileSinkTestCase.java
@BeforeClass public void init() { ClassLoader classLoader = FileSourceLineModeTestCase.class.getClassLoader(); String rootPath = classLoader.getResource("files").getFile(); sourceRoot = new File(rootPath + "/repo/sink_repo"); dirUri = rootPath + "/new"; sinkUri = rootPath + "/sink"; fileToAppend = new File(dirUri); sinkRoot = new File(sinkUri); }
From source file:com.jeeframework.util.xml.XMLProperties.java
/** * Creates a new XMLPropertiesTest object. * * @param fileName the full path the file that properties should be read from * and written to./*from w w w .java 2s .c om*/ * @throws IOException if an error occurs loading the properties. */ public XMLProperties(String fileName) throws IOException { Assert.notNull(fileName, "fileName must not be null"); ClassLoader clToUse = ClassUtils.getDefaultClassLoader(); URL url = clToUse.getResource(fileName); if (url == null) { throw new FileNotFoundException(fileName + " not found "); } InputStream is = null; try { URLConnection con = url.openConnection(); con.setUseCaches(false); is = con.getInputStream(); Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); buildDoc(reader); } finally { if (is != null) { is.close(); } } }
From source file:org.suren.autotest.web.framework.selenium.SeleniumEngine.java
/** * engine/*from w w w.j a v a2s . c o m*/ * @param enginePro * @throws MalformedURLException */ private void loadDefaultEnginePath(ClassLoader classLoader, Properties enginePro) throws MalformedURLException { Enumeration<URL> resurceUrls = null; URL defaultResourceUrl = null; try { resurceUrls = classLoader.getResources(ENGINE_CONFIG_FILE_NAME); defaultResourceUrl = classLoader.getResource(ENGINE_CONFIG_FILE_NAME); } catch (IOException e) { logger.error("Engine properties loading error.", e); } if (resurceUrls == null) { return; } //?jar while (resurceUrls.hasMoreElements()) { URL url = resurceUrls.nextElement(); try { loadFromURL(enginePro, url); } catch (IOException e) { logger.error("loading engine error.", e); } } try { //? loadFromURL(enginePro, defaultResourceUrl); } catch (IOException e) { logger.error("loading engine error.", e); } loadDriverFromMapping(classLoader, enginePro); }
From source file:dk.statsbiblioteket.util.XProperties.java
/** * Store the properties as the resource named by resourceName. * The ressource is first searched for in the same order as for load(). If * found and in writable directory, it is replaced. * If it does not exist, a new file is created at the default directory, * with the name resourceName.//from ww w .j a v a2s . c o m * Note: Trying to replace a resource placed anywhere else than a * write-enabled directory, will give an IOException. * * @param resourceName the name of the resource to store the properties to * @throws IOException if the resource could not be stored */ public synchronized void store(String resourceName) throws IOException { log.trace(String.format("Storing properties to resource %s", resourceName)); log.trace("Locating resource"); ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL resourceURL = loader.getResource(resourceName); File f; if (new File(defaultPath, resourceName).isFile()) { f = new File(defaultPath, resourceName); } else if (new File(resourceName).isFile()) { f = new File(resourceName); } else if (resourceURL != null && new File(resourceURL.getPath()).exists()) { f = new File(resourceURL.getPath()); } else { // TODO: Does not handle "C:\whatever if (resourceName.startsWith(File.separator)) { f = new File(resourceName); } else { f = new File(defaultPath, resourceName); } } FileOutputStream filestream = new FileOutputStream(f); store(filestream, null); }
From source file:dk.statsbiblioteket.util.XProperties.java
/** * Fetch stored properties from the given resource. This uses * ContextClassLoader, so as long as the * resource is in the CLASSPATH, it should be accessible. * * The resource is searched for in the following order: * - If the resource can be found in defaultPath, use this * - Else if the resource can be found in current directory use this * - Else if the resource can be found in classpath, use this * * @param resourceName the name of the resource containing the properties * @param ignoreNonExisting don't throw an exception if the resource can not * be found/*from w w w. j av a2s . c om*/ * @param ignoreMalformed don't throw an exception if the resource is * malformed * @throws InvalidPropertiesException if the ignores aren't true and the * resource contains unknown classes * @throws IOException thrown if there are IO errors during read OR if * resource is not found and ignoreNonExisting is false. */ public synchronized void load(String resourceName, boolean ignoreNonExisting, boolean ignoreMalformed) throws InvalidPropertiesException, IOException { log.trace(String.format("Loading resource %s with" + " ignoreNonExisting %s and" + " ignoreMalformed %s", resourceName, ignoreNonExisting, ignoreMalformed)); this.resourceName = resourceName; clear(); InputStream instream; log.trace("Locating resource '" + resourceName + "'"); ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL resourceURL = loader.getResource(resourceName); if (new File(defaultPath, resourceName).isFile()) { instream = new FileInputStream(new File(defaultPath, resourceName)); } else if (new File(resourceName).isFile()) { instream = new FileInputStream(new File(resourceName)); } else if (resourceURL != null) { instream = resourceURL.openStream(); } else { String msg = String.format("Could not locate resource %s", resourceName); if (ignoreNonExisting) { log.debug(msg + ", ignoring"); return; } log.warn(msg); throw new FileNotFoundException(msg); } log.trace("Loading resource"); if (ignoreMalformed) { try { load(instream); } catch (InvalidPropertiesException e) { //Ignore } } else { load(instream); } log.debug(String.format("Properties resource \"%s\" loaded", resourceName)); }
From source file:io.siddhi.extension.io.file.FileSourceBinaryModeTestCase.java
@BeforeClass public void init() { ClassLoader classLoader = FileSourceBinaryModeTestCase.class.getClassLoader(); String rootPath = classLoader.getResource("files").getFile(); sourceRoot = new File(rootPath + "/repo"); dirUri = rootPath + "/new"; newRoot = new File(dirUri); moveAfterProcessDir = rootPath + "/moved_files"; }