List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:com.publicuhc.pluginframework.util.YamlUtil.java
/** * Attempts to pull a Yaml file from the JAR * * @param path the path to check for/* ww w .j a va 2s . c o m*/ * @param loader the classloader to look in * @return optional. Present if found, null if not * * @throws IOException * @throws InvalidConfigurationException if the file can't be parsed */ public static Optional<YamlConfiguration> loadYamlFromJAR(String path, ClassLoader loader) throws IOException, InvalidConfigurationException { Validate.notNull(path, "Path to file cannot be null"); URL url = loader.getResource(path); if (url == null) { return Optional.absent(); } StringBuilder builder = new StringBuilder(); CharStreams.copy(Resources.newReaderSupplier(url, Charsets.UTF_8), builder); return Optional.of(loadYamlFromString(builder.toString())); }
From source file:eu.planets_project.services.utils.cli.CliMigrationPaths.java
/** * @param resourceName The XML file containing the path configuration * @return The paths defined in the XML file * @throws ParserConfigurationException//from ww w .j a va 2 s .co m * @throws IOException * @throws SAXException * @throws URISyntaxException */ // TODO: Clean up this exception-mess. Something like "InitialisationException" or "ConfigurationErrorException" should cover all these exceptions. public static CliMigrationPaths initialiseFromFile(String resourceName) throws ParserConfigurationException, IOException, SAXException, URISyntaxException { InputStream instream; 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); throw new FileNotFoundException(msg); } CliMigrationPaths paths = new CliMigrationPaths(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc = builder.parse(instream); Element fileformats = doc.getDocumentElement(); if (fileformats != null) { NodeList children = fileformats.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName().equals("path")) { CliMigrationPath pathdef = decodePathNode(child); paths.add(pathdef); } } } } IOUtils.closeQuietly(instream); return paths; }
From source file:org.zalando.problem.ProblemMixInTest.java
private static URL getResource(final String name) { final ClassLoader loader = Thread.currentThread().getContextClassLoader(); return Objects.requireNonNull(loader.getResource(name), () -> "resource " + name + " not found."); }
From source file:net.ymate.platform.commons.util.ResourceUtils.java
/** * //from w ww. j a v a2 s . c o m * @param resourceName * @param callingClass * @return */ public static URL getResource(String resourceName, Class<?> callingClass) { URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null) { url = ClassUtils.getDefaultClassLoader().getResource(resourceName); } if (url == null) { url = callingClass.getResource(resourceName); if (url == null) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { url = cl.getResource(resourceName); } } } if ((url == null) && (resourceName != null) && (((resourceName.length() == 0) || (resourceName.charAt(0) != '/')))) { return getResource('/' + resourceName, callingClass); } return url; }
From source file:org.apache.hadoop.security.ProviderUtils.java
/** * The password is either found in the environment or in a file. This * routine implements the logic for locating the password in these * locations.//from w w w .j a va 2s . co m * * @param envWithPass The name of the environment variable that might * contain the password. Must not be null. * @param fileWithPass The name of a file that could contain the password. * Can be null. * @return The password as a char []; null if not found. * @throws IOException If fileWithPass is non-null and points to a * nonexistent file or a file that fails to open and be read properly. */ public static char[] locatePassword(String envWithPass, String fileWithPass) throws IOException { char[] pass = null; if (System.getenv().containsKey(envWithPass)) { pass = System.getenv(envWithPass).toCharArray(); } if (pass == null) { if (fileWithPass != null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL pwdFile = cl.getResource(fileWithPass); if (pwdFile == null) { // Provided Password file does not exist throw new IOException("Password file does not exist"); } try (InputStream is = pwdFile.openStream()) { pass = IOUtils.toString(is).trim().toCharArray(); } } } return pass; }
From source file:io.apiman.gateway.engine.jdbc.JdbcMetricsTest.java
/** * Initialize the DB with the apiman gateway DDL. * @param connection//from w ww. j ava 2s . c o m */ private static void initDB(Connection connection) throws Exception { ClassLoader cl = JdbcMetricsTest.class.getClassLoader(); URL resource = cl.getResource("ddls/apiman-gateway_h2.ddl"); try (InputStream is = resource.openStream()) { System.out.println("======================================="); System.out.println("Initializing database."); DdlParser ddlParser = new DdlParser(); List<String> statements = ddlParser.parse(is); for (String sql : statements) { System.out.println(sql); PreparedStatement statement = connection.prepareStatement(sql); statement.execute(); } System.out.println("======================================="); } }
From source file:ResourcesUtils.java
/** * Returns the URL of the resource on the classpath * //from www. j a v a2s . c o m * @param resource * The resource to find * @throws IOException * If the resource cannot be found or read * @return The resource */ public static URL getResourceURL(String resource) throws IOException { URL url = null; ClassLoader loader = ResourcesUtils.class.getClassLoader(); if (loader != null) { url = loader.getResource(resource); } if (url == null) { url = ClassLoader.getSystemResource(resource); } if (url == null) { throw new IOException("Could not find resource " + resource); } return url; }
From source file:com.sonicle.webtop.core.app.util.LogbackHelper.java
public static void writeProperties(ClassLoader classLoader, Properties properties) throws IOException, URISyntaxException { FileOutputStream out = null;//ww w.j av a2 s .c o m try { out = new FileOutputStream(new File(classLoader.getResource(LOGBACK_PROPERTIES_FILE).toURI())); properties.store(out, ""); } finally { IOUtils.close(out); } }
From source file:org.apache.axis2.metadata.registry.MetadataFactoryRegistry.java
/** * This method will load a file, if it exists, that contains a list * of interfaces and custom implementations. This allows for non- * programmatic registration of custom interface implementations * with the MDQ layer./*from w ww.ja v a2 s. co m*/ */ private static void loadConfigFromFile() { String pairSeparator = "|"; try { ClassLoader classLoader = getContextClassLoader(null); URL url = null; url = classLoader.getResource(configurationFileLoc); if (url == null) { File file = new File(configurationFileLoc); url = file.toURL(); } // the presence of this file is optional if (url != null) { if (log.isDebugEnabled()) { log.debug("Found URL to MetadataFactoryRegistry configuration file: " + configurationFileLoc); } BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); // the separator of the file is the '|' character // to the left of the separator will be the interface and // to the right will be the custom implementation if (line != null && line.indexOf("|") != -1) { String interfaceName = line.substring(0, line.indexOf(pairSeparator)); String implName = line.substring(line.indexOf(pairSeparator) + 1, line.length()); if (log.isDebugEnabled()) { log.debug("For registered class: " + interfaceName + " the " + "following implementation was found: " + implName); } Class intf = classLoader.loadClass(interfaceName); Class impl = classLoader.loadClass(implName); // if we could load both we need to register them with our // internal registry if (intf != null && impl != null) { if (log.isDebugEnabled()) { log.debug("Loaded both interface and implementation class: " + interfaceName + ":" + implName); } if (impl.getEnclosingClass() == null) { table.put(intf, impl.newInstance()); } else { if (log.isWarnEnabled()) { log.warn("The implementation class: " + impl.getClass().getName() + " could not be lregistered because it is an inner class. " + "In order to register file-based overrides, implementations " + "must be public outer classes."); } } } else { if (log.isDebugEnabled()) { log.debug("Could not load both interface and implementation class: " + interfaceName + ":" + implName); } } } else { if (log.isDebugEnabled()) { log.debug("Did not find File for MetadataFactoryRegistry configuration " + "file: " + configurationFileLoc); } } } else { if (log.isDebugEnabled()) { log.debug("Did not find URL for MetadataFactoryRegistry configuration " + "file: " + configurationFileLoc); } } } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("The MetadataFactoryRegistry could not process the configuration file: " + configurationFileLoc + " because of the following error: " + t.toString()); } } }
From source file:com.netsteadfast.greenstep.bsc.util.BscReportSupportUtils.java
public static byte[] getByteIcon(KpiVO kpi, float score) throws Exception { byte[] datas = null; SysExpressionVO sysExpression = exprThreadLocal02.get(); if (null == sysExpression) { return datas; }/*from ww w . ja v a2 s . c om*/ Map<String, Object> parameters = new HashMap<String, Object>(); Map<String, Object> results = new HashMap<String, Object>(); parameters.put("kpi", kpi); parameters.put("score", score); results.put("icon", " "); ScriptExpressionUtils.execute(sysExpression.getType(), sysExpression.getContent(), results, parameters); String iconResource = (String) results.get("icon"); ClassLoader classLoader = BscReportSupportUtils.class.getClassLoader(); datas = IOUtils.toByteArray(classLoader.getResource(iconResource).openStream()); return datas; }