List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:com.tuplejump.stargate.cassandra.CassandraUtils.java
static URL getStorageConfigURL() throws ConfigurationException { String configUrl = System.getProperty("cassandra.config"); if (configUrl == null) configUrl = DEFAULT_CONFIGURATION; URL url;//from ww w . j a v a2s.co m try { url = new URL(configUrl); url.openStream().close(); // catches well-formed but bogus URLs } catch (Exception e) { ClassLoader loader = DatabaseDescriptor.class.getClassLoader(); url = loader.getResource(configUrl); if (url == null) throw new ConfigurationException("Cannot locate " + configUrl); } return url; }
From source file:fll.xml.XMLUtils.java
/** * Get all challenge descriptors build into the software. *///from www . j ava 2 s . com public static Collection<URL> getAllKnownChallengeDescriptorURLs() { final String baseDir = "fll/resources/challenge-descriptors/"; final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); final URL directory = classLoader.getResource(baseDir); if (null == directory) { LOGGER.warn("base dir for challenge descriptors not found"); return Collections.emptyList(); } final Collection<URL> urls = new LinkedList<URL>(); if ("file".equals(directory.getProtocol())) { try { final URI uri = directory.toURI(); final File fileDir = new File(uri); final File[] files = fileDir.listFiles(); if (null != files) { for (final File file : files) { if (file.getName().endsWith(".xml")) { try { final URL fileUrl = file.toURI().toURL(); urls.add(fileUrl); } catch (final MalformedURLException e) { LOGGER.error("Unable to convert file to URL: " + file.getAbsolutePath(), e); } } } } } catch (final URISyntaxException e) { LOGGER.error("Unable to convert URL to URI: " + e.getMessage(), e); } } else if (directory.getProtocol().equals("jar")) { final CodeSource src = XMLUtils.class.getProtectionDomain().getCodeSource(); if (null != src) { final URL jar = src.getLocation(); JarInputStream zip = null; try { zip = new JarInputStream(jar.openStream()); JarEntry ze = null; while ((ze = zip.getNextJarEntry()) != null) { final String entryName = ze.getName(); if (entryName.startsWith(baseDir) && entryName.endsWith(".xml")) { // add 1 to baseDir to skip past the path separator final String challengeName = entryName.substring(baseDir.length()); // check that the file really exists and turn it into a URL final URL challengeUrl = classLoader.getResource(baseDir + challengeName); if (null != challengeUrl) { urls.add(challengeUrl); } else { // TODO could write the resource out to a temporary file if // needed // then mark the file as delete on exit LOGGER.warn("URL doesn't exist for " + baseDir + challengeName + " entry: " + entryName); } } } zip.close(); } catch (final IOException e) { LOGGER.error("Error reading jar file at: " + jar.toString(), e); } finally { IOUtils.closeQuietly(zip); } } else { LOGGER.warn("Null code source in protection domain, cannot get challenge descriptors"); } } else { throw new UnsupportedOperationException("Cannot list files for URL " + directory); } return urls; }
From source file:com.netflix.nicobar.core.utils.ClassPathUtils.java
/** * Find the root path for the given resource. If the resource is found in a Jar file, then the * result will be an absolute path to the jar file. If the resource is found in a directory, * then the result will be the parent path of the given resource. * * For example, if the resourceName is given as "scripts/myscript.groovy", and the path to the file is * "/root/sub1/script/myscript.groovy", then this method will return "/root/sub1" * * @param resourceName relative path of the resource to search for. E.G. "scripts/myscript.groovy" * @param classLoader the {@link ClassLoader} to search * @return absolute path of the root of the resource. *//*w w w .j a va2s.co m*/ @Nullable public static Path findRootPathForResource(String resourceName, ClassLoader classLoader) { Objects.requireNonNull(resourceName, "resourceName"); Objects.requireNonNull(classLoader, "classLoader"); URL resource = classLoader.getResource(resourceName); if (resource != null) { String protocol = resource.getProtocol(); if (protocol.equals("jar")) { return getJarPathFromUrl(resource); } else if (protocol.equals("file")) { return getRootPathFromDirectory(resourceName, resource); } else { throw new IllegalStateException("Unsupported URL protocol: " + protocol); } } return null; }
From source file:net.ontopia.topicmaps.entry.XMLConfigSource.java
/** * INTERNAL://from www .j a va 2s.c om */ public static TopicMapRepositoryIF getRepositoryFromClassPath(String resourceName, Map<String, String> environ) { // look up configuration via classpath ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource(resourceName); if (url == null) throw new OntopiaRuntimeException("Could not find resource '" + resourceName + "' on CLASSPATH."); // build configuration environment if (environ == null) environ = new HashMap<String, String>(1); if ("file".equals(url.getProtocol())) { String file = url.getFile(); environ.put(CWD, file.substring(0, file.lastIndexOf('/'))); } else environ.put(CWD, "."); // read configuration and create the repository instance try { return createRepository(readSources(new InputSource(url.openStream()), environ)); } catch (IOException e) { throw new OntopiaRuntimeException(e); } }
From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java
public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception { JanusGraphManagement mgmt = graph.openManagement(); if (mgmt.getGraphIndex(CHARACTER) == null) { final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make(); mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex(); }/*from ww w . j a v a2 s . co m*/ if (mgmt.getGraphIndex(COMIC_BOOK) == null) { final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make(); mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex(); mgmt.makePropertyKey(WEAPON).dataType(String.class).make(); mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make(); } mgmt.commit(); ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader(); URL resource = classLoader.getResource("META-INF/marvel.csv"); int line = 0; Map<String, Set<String>> comicToCharacter = new HashMap<>(); Map<String, Set<String>> characterToComic = new HashMap<>(); Set<String> characters = new HashSet<>(); BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>(); try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) { String[] nextLine; while ((nextLine = reader.readNext()) != null && line < rowsToLoad) { line++; String comicBook = nextLine[1]; String[] characterNames = nextLine[0].split("/"); if (!comicToCharacter.containsKey(comicBook)) { comicToCharacter.put(comicBook, new HashSet<String>()); } List<String> comicCharacters = Arrays.asList(characterNames); comicToCharacter.get(comicBook).addAll(comicCharacters); characters.addAll(comicCharacters); } } for (String character : characters) { creationQueue.add(new CharacterCreationCommand(character, graph)); } BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>(); for (String comicBook : comicToCharacter.keySet()) { creationQueue.add(new ComicBookCreationCommand(comicBook, graph)); Set<String> comicCharacters = comicToCharacter.get(comicBook); for (String character : comicCharacters) { AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook)); appearedQueue.add(lineCommand); if (!characterToComic.containsKey(character)) { characterToComic.put(character, new HashSet<String>()); } characterToComic.get(character).add(comicBook); } REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size()); } int maxAppearances = 0; String maxCharacter = ""; for (String character : characterToComic.keySet()) { Set<String> comicBookSet = characterToComic.get(character); int numberOfAppearances = comicBookSet.size(); REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances); if (numberOfAppearances > maxAppearances) { maxCharacter = character; maxAppearances = numberOfAppearances; } } LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances); ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); for (int i = 0; i < POOL_SIZE; i++) { executor.execute(new BatchCommand(graph, creationQueue)); } executor.shutdown(); while (!executor.awaitTermination(60, TimeUnit.SECONDS)) { LOG.info("Awaiting:" + creationQueue.size()); if (report) { REPORTER.report(); } } executor = Executors.newSingleThreadExecutor(); executor.execute(new BatchCommand(graph, appearedQueue)); executor.shutdown(); while (!executor.awaitTermination(60, TimeUnit.SECONDS)) { LOG.info("Awaiting:" + appearedQueue.size()); if (report) { REPORTER.report(); } } LOG.info("MarvelGraphFactory.load complete"); }
From source file:com.sunchenbin.store.feilong.core.lang.ClassLoaderUtil.java
/** * Load a given resource./*from ww w.j ava 2 s . co m*/ * <p> * This method will try to load the resource using the following methods (in order): * </p> * <ul> * <li>From {@link Thread#getContextClassLoader() Thread.currentThread().getContextClassLoader()} * <li>From {@link Class#getClassLoader() ClassLoaderUtil.class.getClassLoader()} * <li>From the {@link Class#getClassLoader() callingClass.getClassLoader() } * </ul> * * @param resourceName * The name of the resource to load * @param callingClass * The Class object of the calling object * @return the resource */ public static URL getResource(String resourceName, Class<?> callingClass) { ClassLoader classLoader = getClassLoaderByCurrentThread(); URL url = classLoader.getResource(resourceName); if (url == null) { LOGGER.warn("In ClassLoader:[{}],not found the resourceName:[{}]", JsonUtil.format(getClassLoaderInfoMapForLog(classLoader)), resourceName); classLoader = getClassLoaderByClass(ClassLoaderUtil.class); url = getResource(classLoader, resourceName); if (url == null) { LOGGER.warn("In ClassLoader:[{}],not found the resourceName:[{}]", JsonUtil.format(getClassLoaderInfoMapForLog(classLoader)), resourceName); classLoader = getClassLoaderByClass(callingClass); url = getResource(classLoader, resourceName); } } if (url == null) { LOGGER.warn("resourceName:[{}] in all ClassLoader not found", resourceName); } else { LOGGER.debug("found the resourceName:[{}],In ClassLoader :[{}] ", resourceName, JsonUtil.format(getClassLoaderInfoMapForLog(classLoader))); } return url; }
From source file:com.netflix.config.ConfigurationManager.java
/** * Load properties from resource file into the system wide configuration * @param path path of the resource/*from ww w .j a v a 2s . c o m*/ * @throws IOException */ public static void loadPropertiesFromResources(String path) throws IOException { if (instance == null) { instance = getConfigInstance(); } ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(path); if (url == null) { throw new IOException("Cannot locate " + path + " as a classpath resource."); } Properties props = new Properties(); InputStream fin = url.openStream(); props.load(fin); fin.close(); if (instance instanceof AggregatedConfiguration) { String name = getConfigName(url); ConcurrentMapConfiguration config = new ConcurrentMapConfiguration(); config.loadProperties(props); ((AggregatedConfiguration) instance).addConfiguration(config, name); } else { ConfigurationUtils.loadProperties(props, instance); } }
From source file:org.apache.cayenne.util.ResourceLocator.java
/** * Looks up the URL for the named resource using the specified ClassLoader. *//* www .j a v a 2 s. c o m*/ public static URL findURLInClassLoader(String name, ClassLoader loader) { URL url = loader.getResource(name); if (url != null) { logObj.debug("URL found with classloader: " + url); } else { logObj.debug("URL not found with classloader: " + name); } return url; }
From source file:net.lightbody.bmp.proxy.jetty.util.Resource.java
/** Construct a system resource from a string. * The resource is tried as classloader resource before being * treated as a normal resource.// w ww. ja v a 2 s. co m */ public static Resource newSystemResource(String resource) throws IOException { URL url = null; // Try to format as a URL? ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader != null) { url = loader.getResource(resource); if (url == null && resource.startsWith("/")) url = loader.getResource(resource.substring(1)); } if (url == null) { loader = Resource.class.getClassLoader(); if (loader != null) { url = loader.getResource(resource); if (url == null && resource.startsWith("/")) url = loader.getResource(resource.substring(1)); } } if (url == null) { url = ClassLoader.getSystemResource(resource); if (url == null && resource.startsWith("/")) url = loader.getResource(resource.substring(1)); } if (url == null) return null; return newResource(url); }
From source file:com.netflix.config.ConfigurationManager.java
/** * Load resource configName.properties first. Then load configName-deploymentEnvironment.properties * into the system wide configuration. For example, if configName is "application", and deployment environment * is "test", this API will first load "application.properties", then load "application-test.properties" to * override any property that also exist in "application.properties". * /* w ww .j a v a 2 s .c o m*/ * @param configName prefix of the properties file name. * @throws IOException * @see DeploymentContext#getDeploymentEnvironment() */ public static void loadCascadedPropertiesFromResources(String configName) throws IOException { String defaultConfigFileName = configName + ".properties"; if (instance == null) { instance = getConfigInstance(); } ClassLoader loader = Thread.currentThread().getContextClassLoader(); URL url = loader.getResource(defaultConfigFileName); if (url == null) { throw new IOException("Cannot locate " + defaultConfigFileName + " as a classpath resource."); } Properties props = getPropertiesFromFile(url); String environment = getDeploymentContext().getDeploymentEnvironment(); if (environment != null && environment.length() > 0) { String envConfigFileName = configName + "-" + environment + ".properties"; url = loader.getResource(envConfigFileName); if (url != null) { Properties envProps = getPropertiesFromFile(url); if (envProps != null) { props.putAll(envProps); } } } if (instance instanceof AggregatedConfiguration) { ConcurrentMapConfiguration config = new ConcurrentMapConfiguration(); config.loadProperties(props); ((AggregatedConfiguration) instance).addConfiguration(config, configName); } else { ConfigurationUtils.loadProperties(props, instance); } }