List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:com.alibaba.jstorm.daemon.supervisor.SyncSupervisorEvent.java
private void downloadLocalStormCode(Map conf, String topologyId, String masterCodeDir) throws IOException, TException { // STORM-LOCAL-DIR/supervisor/stormdist/storm-id String stormroot = StormConfig.supervisor_stormdist_root(conf, topologyId); FileUtils.copyDirectory(new File(masterCodeDir), new File(stormroot)); ClassLoader classloader = Thread.currentThread().getContextClassLoader(); String resourcesJar = resourcesJar(); URL url = classloader.getResource(StormConfig.RESOURCES_SUBDIR); String targetDir = stormroot + '/' + StormConfig.RESOURCES_SUBDIR; if (resourcesJar != null) { LOG.info("Extracting resources from jar at " + resourcesJar + " to " + targetDir); JStormUtils.extract_dir_from_jar(resourcesJar, StormConfig.RESOURCES_SUBDIR, stormroot);// extract dir // from jar;; // util.clj } else if (url != null) { LOG.info("Copying resources at " + url.toString() + " to " + targetDir); FileUtils.copyDirectory(new File(url.getFile()), (new File(targetDir))); }//from w w w . j av a 2s. com }
From source file:com.liferay.portal.configuration.ConfigurationImpl.java
protected void updateBasePath(ClassLoader classLoader, String name) { InputStream inputStream = null; try {/* w w w .j ava 2s . c om*/ URL url = classLoader.getResource(name + Conventions.PROPERTIES_EXTENSION); if (url == null) { return; } String protocol = url.getProtocol(); if (!protocol.equals("file")) { return; } Properties properties = new Properties(); inputStream = url.openStream(); properties.load(inputStream); if (properties.containsKey("base.path")) { return; } String fileName = StringUtil.replace(url.getFile(), "%20", StringPool.SPACE); File file = new File(fileName); if (!file.exists() || !file.canWrite()) { if (_log.isWarnEnabled()) { _log.warn("Unable to write " + file); } return; } Writer writer = new FileWriter(file, true); StringBundler sb = new StringBundler(4); sb.append(StringPool.OS_EOL); sb.append(StringPool.OS_EOL); sb.append("base.path="); String basePath = url.getPath(); int pos = basePath.lastIndexOf(StringPool.SLASH + name + Conventions.PROPERTIES_EXTENSION); if (pos != -1) { basePath = basePath.substring(0, pos); } sb.append(basePath); writer.write(sb.toString()); writer.close(); } catch (Exception e) { _log.error(e, e); } finally { StreamUtil.cleanUp(inputStream); } }
From source file:com.lonepulse.zombielink.processor.RequestParamEndpointTest.java
/** * <p>Test for a {@link Request} with a {@link File} entity.</p> * //ww w . j ava 2s .co m * @since 1.3.0 */ @Test public final void testFileEntity() throws ParseException, IOException, URISyntaxException { String subpath = "/fileentity"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); File file = new File(classLoader.getResource("LICENSE.txt").toURI()); FileEntity fe = new FileEntity(file); stubFor(put(urlEqualTo(subpath)).willReturn(aResponse().withStatus(200))); requestEndpoint.fileEntity(file); verify(putRequestedFor(urlEqualTo(subpath)).withRequestBody(equalTo(EntityUtils.toString(fe)))); }
From source file:net.collegeman.phpinjava.PHP.java
/** * Initialize a <code>PHP</code> wrapper with a specific <code>ClassLoader</code> instance. Refer * to the doc for {@link #PHP(String)} for a description of the <code>url</code> parameter. *///from w w w .j a v a2 s . co m public PHP(String url, ClassLoader classLoader) { if (url == null || url.length() < 1) throw new IllegalArgumentException("[url] parameter must be defined"); if (classLoader == null) throw new IllegalArgumentException("[classLoader] parameter must be defined"); // classpath reference if (url.indexOf("classpath:/") == 0) { URL resource = classLoader.getResource(url.substring(11)); File ref = new File(resource.getPath()); initByFile(ref); } // remote script else if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) { try { URLConnection conn = new URL(url).openConnection(); initByInputStream(conn.getInputStream()); } catch (Exception e) { throw new RuntimeException(e); } } // file reference else { initByFile(new File(url)); } }
From source file:org.apache.axis2.wsdl.util.WSDLWrapperReloadImpl.java
private static URL getAbsoluteURL(final ClassLoader classLoader, final String filePath, URL wURL) throws WSDLException { URL url = (URL) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return classLoader.getResource(filePath); }// w w w .ja va 2 s .c o m }); if (url == null) { if (log.isDebugEnabled()) { log.debug("Could not get URL from classloader. Looking in a jar."); } if (classLoader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) classLoader; url = getURLFromJAR(urlLoader, wURL); } } return url; }
From source file:com.ai.alm.launcher.Launcher.java
public Launcher() { Properties properties = new Properties(); try {/*w w w .ja va2 s . com*/ ClassLoader loader = Launcher.class.getClassLoader(); URL url = loader.getResource(CONF_FILE); properties.load(url.openStream()); // from file String propFile = System.getProperty(CONF_PARAM); if (null != propFile) { properties.load(new FileInputStream(propFile)); } // Load system properties.putAll(System.getProperties()); } catch (Exception ignored) { // ignored.printStackTrace(); } // Defaults host = properties.getProperty("jetty.host", host_default); port = Integer.parseInt(properties.getProperty("jetty.port", port_default)); secret = properties.getProperty("jetty.secret", secret_default); contextPath = properties.getProperty("jetty.contextPath", contextPath_default); workDirPath = properties.getProperty("jetty.workDir", workDirPath_default); // Detailed Logs logsEnabled = Boolean.parseBoolean(properties.getProperty("jetty.logs", logsEnabled_default)); out.println("Jetty Configuration Properties ===>> " + "\n\thost=" + host + "\n\tport=" + port + "\n\tcontext=" + contextPath + "\n\tsecret=" + secret + "\n\twork-dir=" + workDirPath + "\n\tlogs=" + logsEnabled); }
From source file:com.ning.http.client.async.MultipartUploadTest.java
private File getClasspathFile(String file) throws FileNotFoundException { ClassLoader cl = null; try {// ww w .ja va 2 s . com cl = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { } if (cl == null) { cl = MultipartUploadTest.class.getClassLoader(); } URL resourceUrl = cl.getResource(file); try { return new File(new URI(resourceUrl.toString()).getSchemeSpecificPart()); } catch (URISyntaxException e) { throw new FileNotFoundException(file); } }
From source file:nz.govt.natlib.ndha.manualdeposit.dialogs.About.java
@SuppressWarnings("unchecked") private void startup() { try {//from w w w. j a v a2 s . co m try { theFormControl = new FormControl(this, theSettingsPath); } catch (Exception ex) { LOG.error("Error loading form parameters", ex); } ClassLoader cLoader = Thread.currentThread().getContextClassLoader(); Toolkit kit = Toolkit.getDefaultToolkit(); Package p = this.getClass().getPackage(); lblVersion.setText(p.getImplementationVersion()); if (new File(theLogoFileName).exists()) { theLogo = kit.getImage(theLogoFileName); } else { java.net.URL imageURL = cLoader.getResource(theLogoFileName); if (imageURL != null) { theLogo = kit.getImage(imageURL); } } if (theLogo != null) { lblBuildNo.setForeground(Color.white); lblBuildNoLabel.setForeground(Color.white); //lblHeader.setForeground(Color.white); lblVersion.setForeground(Color.white); lblVersionLabel.setForeground(Color.white); paintImage(); } //String manifestFileName = "/META-INF/MANIFEST.MF"; Class cls = this.getClass(); String className = cls.getSimpleName(); String classFileName = className + ".class"; String pathToThisClass = cls.getResource(classFileName).toString(); int mark = pathToThisClass.indexOf("!"); String pathToManifest = pathToThisClass.substring(0, mark + 1); if (!pathToManifest.equals("")) { pathToManifest += "/META-INF/MANIFEST.MF"; LOG.debug("Path to manifest: " + pathToManifest); Manifest mf = new Manifest(new URL(pathToManifest).openStream()); if (mf != null) { Attributes attr = mf.getMainAttributes(); String attrVersion = "Implementation-Version"; String attrBuild = "Implementation-Build"; String version = attr.getValue(attrVersion); String build = attr.getValue(attrBuild); this.lblVersion.setText(version); this.lblBuildNo.setText(build); } } Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); LOG.debug("free memory: " + freeMemory / 1024); LOG.debug("allocated memory: " + allocatedMemory / 1024); LOG.debug("max memory: " + maxMemory / 1024); LOG.debug("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024); } catch (IOException ex) { ex.printStackTrace(); LOG.error(ex.getMessage(), ex); } }
From source file:com.bitplan.rest.RestServerImpl.java
/** * get the given Store//from w w w . j av a 2 s.c om * * @param type * @param name * @return the store file * @throws IOException */ public File getStoreFile(String type, String name) throws IOException { final ClassLoader cl = RestServerImpl.class.getClassLoader(); URL surl = cl.getResource(name); File result = null; if (surl != null) { LOGGER.log(Level.WARNING, "getting " + type + " from " + surl.toString()); result = File.createTempFile(name, ".tmp"); FileUtils.copyURLToFile(surl, result); } else { LOGGER.log(Level.WARNING, "could not get " + type + " from resource " + name); } return result; }
From source file:name.livitski.tools.persista.StorageBootstrap.java
/** * Returns the list of entity classes configured for this * object's {@link #getPersistenceUnit() persistence unit} * or an empty list if no classes have been configured. * Persistence unit's XML descriptor is expected to list * all its persistent classes explicitly. * @throws StorageConfigurationException if there is a problem * reading persistence unit configuration * @throws IllegalStateException if a persistent class cannot * be loaded/* ww w . j a v a 2 s . c o m*/ */ public List<Class<?>> getEntityClasses() throws StorageConfigurationException { if (null == entities) { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final URL resource = loader.getResource(PERSISTENCE_RESOURCE); if (null == resource) throw new IllegalStateException("Persistence metadata is not deployed in " + PERSISTENCE_RESOURCE); try { final String persistenceUnit = getPersistenceUnit(); final List<PersistenceMetadata> descriptor = PersistenceXmlLoader.deploy(resource, Collections.emptyMap(), new EntityResolverStub(log()), PersistenceUnitTransactionType.RESOURCE_LOCAL); PersistenceMetadata source = null; for (PersistenceMetadata candidate : descriptor) if (candidate.getName().equals(persistenceUnit)) { source = candidate; break; } if (null == source) throw new ConfigurationException( "Persistence unit '" + persistenceUnit + "' is not defined in " + resource + ". "); entities = new ArrayList<Class<?>>(); for (String qName : source.getClasses()) entities.add(Class.forName(qName, false, loader)); } catch (ClassNotFoundException noclass) { throw new IllegalStateException("Could not load persistent class. " + noclass.getMessage(), noclass); } catch (ConfigurationException e) { throw new StorageConfigurationException(this, e); } catch (Exception e) { throw new StorageConfigurationException(this, "Error parsing persistence metadata at " + resource + ". " + e.getMessage(), e); } } return Collections.unmodifiableList(entities); }