List of usage examples for java.lang ClassLoader getResource
public URL getResource(String name)
From source file:org.openmrs.module.kenyaemr.metadata.MetadataManager.java
/** * Checks whether the given version of the MDS package has been installed yet, and if not, install it * @param groupUuid the package group UUID * @param filename the package filename//w w w.j a va 2s . c om * @param loader the class loader to use for loading the packages (null to use the default) * @return whether any changes were made to the db * @throws IOException */ protected static boolean installMetadataPackageIfNecessary(String groupUuid, String filename, ClassLoader loader) throws IOException { try { Matcher matcher = Pattern.compile("[\\w/-]+-(\\d+).zip").matcher(filename); if (!matcher.matches()) throw new RuntimeException("Filename must match PackageNameWithNoSpaces-X.zip"); Integer version = Integer.valueOf(matcher.group(1)); ImportedPackage installed = Context.getService(MetadataSharingService.class) .getImportedPackageByGroup(groupUuid); if (installed != null && installed.getVersion() >= version) { log.info("Metadata package " + filename + " is already installed with version " + installed.getVersion()); return false; } if (loader == null) { loader = MetadataManager.class.getClassLoader(); } if (loader.getResource(filename) == null) { throw new RuntimeException("Cannot find " + filename + " for group " + groupUuid); } PackageImporter metadataImporter = MetadataSharing.getInstance().newPackageImporter(); metadataImporter.setImportConfig(ImportConfig.valueOf(ImportMode.MIRROR)); metadataImporter.loadSerializedPackageStream(loader.getResourceAsStream(filename)); metadataImporter.importPackage(); return true; } catch (Exception ex) { log.error("Failed to install metadata package " + filename, ex); return false; } }
From source file:net.librec.util.FileUtil.java
/** * Return the BufferedReader List of files in a specified directory. * * @param path The path of the specified directory or file. * Relative and absolute paths are both supported. * @return the BufferedReader List of files. * @throws IOException if I/O error occurs * @throws URISyntaxException if URI Syntax error occurs */// www .jav a 2s.com public static List<BufferedReader> getReader(String path) throws IOException, URISyntaxException { File file = new File(path); List<BufferedReader> readerList = new ArrayList<BufferedReader>(); boolean isRelativePath = !(path.startsWith("/") || path.indexOf(":") > 0); if (isRelativePath) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = FileUtil.class.getClassLoader(); } URL url = classLoader.getResource(path); if (null != url) { file = new File(url.toURI()); } } if (file.isFile()) { BufferedReader reader = new BufferedReader(new FileReader(file)); readerList.add(reader); } else if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { BufferedReader reader = new BufferedReader(new FileReader(files[i])); readerList.add(reader); } } } return readerList; }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java
/** * Resolve a location (which can be many things) to an URL. If the location starts with * {@code classpath:} the location is interpreted as a classpath location. Otherwise it is tried * as a URL, file and at last UIMA resource. If the location is treated as a classpath or file * location, an URL is only returned if the target exists. If it is an URL, it is possible that * the target may not actually exist.// www . j av a 2 s. co m * * @param aLocation * a location (classpath, URL, file or UIMA resource location). * @param aClassLoader * the class loader to be used for classpath URLs. * @param aContext * a UIMA context. * @return the resolved URL. * @throws IOException * if the target could not be found. */ public static URL resolveLocation(String aLocation, ClassLoader aClassLoader, UimaContext aContext) throws IOException { // if we have a caller, we use it's classloader ClassLoader classLoader = aClassLoader; if (classLoader == null) { classLoader = ResourceUtils.class.getClassLoader(); } // If a location starts with "classpath:" String prefixClasspath = "classpath:"; if (aLocation.startsWith(prefixClasspath)) { String cpLocation = aLocation.substring(prefixClasspath.length()); if (cpLocation.startsWith("/")) { cpLocation = cpLocation.substring(1); } URL url = classLoader.getResource(cpLocation); if (url == null) { throw new FileNotFoundException("No file found at [" + aLocation + "]"); } return url; } // If it is a true well-formed URL, we assume that it is just that. try { return new URL(aLocation); } catch (MalformedURLException e) { // Ok - was not an URL. } // Otherwise we try if it is a file. File file = new File(aLocation); if (file.exists()) { return file.toURI().toURL(); } // Otherwise we look into the context (if there was one) if (aContext != null) { Exception ex = null; URL url = null; try { url = aContext.getResourceURL(aLocation); } catch (ResourceAccessException e) { ex = e; } if (url == null) { FileNotFoundException e = new FileNotFoundException("No file found at [" + aLocation + "]"); if (ex != null) { e.initCause(ex); } throw e; } return url; } // Otherwise bail out throw new FileNotFoundException("No file found at [" + aLocation + "]"); }
From source file:com.comoyo.emjar.EmJarTest.java
protected File getResourceFile(String name) throws URISyntaxException { final ClassLoader cl = getClass().getClassLoader(); final URI base = cl.getResource("com/comoyo/emjar/").toURI(); URIBuilder builder = new URIBuilder(base); builder.setPath(builder.getPath() + name); final URI uri = builder.build(); if (!"file".equals(uri.getScheme())) { throw new IllegalArgumentException("Resource " + name + " not present as file (" + uri + ")"); }/*w ww. ja v a 2s. co m*/ return new File(uri.getSchemeSpecificPart()); }
From source file:com.navercorp.volleyextensions.cache.universalimageloader.disc.CountingInputStreamTest.java
private InputStream openFromClassPath(String testFile) throws IOException { ClassLoader classLoader = this.getClass().getClassLoader(); return classLoader.getResource(testFile).openStream(); }
From source file:nl.nn.adapterframework.util.ClassUtils.java
static private URL getResourceURL(ClassLoader classLoader, Class klass, String resource) { resource = Misc.replace(resource, "%20", " "); URL url = null;/*from w w w. ja va2 s . co m*/ if (classLoader == null) { if (klass == null) { klass = ClassUtils.class; } classLoader = klass.getClassLoader(); } // Remove slash like Class.getResource(String name) is doing before // delegation to ClassLoader if (resource.startsWith("/")) { resource = resource.substring(1); } // first try to get the resource as a resource url = classLoader.getResource(resource); // then try to get it as a URL if (url == null) { try { url = new URL(Misc.replace(resource, " ", "%20")); } catch (MalformedURLException e) { log.debug("Could not find resource as URL [" + resource + "]: " + e.getMessage()); } } if (url == null) { log.warn("cannot find URL for resource [" + resource + "]"); } else { // Spaces must be escaped to %20. But ClassLoader.getResource(String) // has a bug in Java 1.3 and 1.4 and doesn't do this escaping. // See also: // // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4778185 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4785848 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4273532 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4496398 // // Escaping spaces to %20 if spaces are found. String urlString = url.toString(); if (urlString.indexOf(' ') >= 0 && !urlString.startsWith("jar:")) { urlString = Misc.replace(urlString, " ", "%20"); try { URL escapedURL = new URL(urlString); log.debug("resolved resource-string [" + resource + "] to URL [" + escapedURL.toString() + "]"); return escapedURL; } catch (MalformedURLException e) { log.warn("Could not find URL from space-escaped url [" + urlString + "], will use unescaped original version [" + url.toString() + "] "); } } } return url; }
From source file:Main.java
public static String getApplicationPath(Class cls) { if (cls == null) throw new java.lang.IllegalArgumentException("parameter is not null !"); ClassLoader loader = cls.getClassLoader(); String clsName = cls.getName() + ".class"; Package pack = cls.getPackage(); System.out.println("package name is : " + (pack == null)); String path = ""; if (pack != null) { String packName = pack.getName(); if (packName.startsWith("java.") || packName.startsWith("javax.")) throw new java.lang.IllegalArgumentException("This is system class"); clsName = clsName.substring(packName.length() + 1); if (packName.indexOf(".") < 0) path = packName + "/"; else {/*from w w w. j a v a2 s.c om*/ int start = 0, end = 0; end = packName.indexOf("."); while (end != -1) { path = path + packName.substring(start, end) + "/"; start = end + 1; end = packName.indexOf(".", start); } path = path + packName.substring(start) + "/"; } } java.net.URL url = loader.getResource(path + clsName); String realPath = url.getPath(); int pos = realPath.indexOf("file:"); if (pos > -1) realPath = realPath.substring(pos + 5); pos = realPath.indexOf(path + clsName); realPath = realPath.substring(0, pos - 1); if (realPath.endsWith("!")) realPath = realPath.substring(0, realPath.lastIndexOf("/")); try { realPath = java.net.URLDecoder.decode(realPath, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } return realPath; }
From source file:edu.depaul.armada.Armada.java
public void startServer(String[] args) throws Exception { server = new Server(8083); ResourceHandler resourceHandler = new ResourceHandler(); resourceHandler.setDirectoriesListed(true); resourceHandler.setWelcomeFiles(new String[] { "index.html" }); // loads dashboard from classpath ClassLoader loader = Armada.class.getClassLoader(); URL resource = loader.getResource("assets/"); String webDir = resource.toExternalForm(); resourceHandler.setResourceBase(webDir); ServletHandler servletHandler = new ServletHandler(); DispatcherServlet dispatcherServlet = new DispatcherServlet(); dispatcherServlet.setContextConfigLocation("classpath:/beans/armada-config.xml"); ServletHolder servletHolder = new ServletHolder(dispatcherServlet); servletHandler.addServlet(servletHolder); WebAppContext webApp = new WebAppContext(); webApp.setResourceBase(webDir);/*from w w w. j a v a2s . c om*/ webApp.setContextPath("/"); webApp.addServlet(servletHolder, "/"); HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { resourceHandler, webApp }); server.setHandler(handlers); server.start(); server.join(); }
From source file:io.fabric8.mq.controller.coordination.ReplicationControllerTest.java
@Test public void testCreateReplicationController() throws Exception { ObjectMapper mapper = new ObjectMapper(); /*/*from w ww . j a v a2 s . c o m*/ String basedir = System.getProperty("basedir", "apps/fabric8-mq-controller"); String fileName = basedir + "/src/main/resources/replication-template.json"; */ ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource("META-INF/replicator-template.json"); ReplicationController result = mapper.reader(ReplicationController.class).readValue(url); Assert.assertNotNull(result); }
From source file:io.fabric8.mq.coordination.ReplicationControllerTest.java
@Test public void testCreateReplicationController() throws Exception { ObjectMapper mapper = KubernetesFactory.createObjectMapper(); /*//from ww w. j a v a 2 s .c o m String basedir = System.getProperty("basedir", "apps/fabric8-mq-controller"); String fileName = basedir + "/src/main/resources/replication-template.json"; */ ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource("META-INF/replicator-template.json"); ReplicationController result = mapper.reader(ReplicationController.class).readValue(url); Assert.assertNotNull(result); }