List of usage examples for java.lang Class getResource
@CallerSensitive
public URL getResource(String name)
From source file:org.apache.maven.surefire.its.fixture.MavenLauncher.java
private File simpleExtractResources(Class<?> cl, String resourcePath) { if (!resourcePath.startsWith("/")) { resourcePath = "/" + resourcePath; }/*from ww w.java 2s .c o m*/ File tempDir = getUnpackDir(); File testDir = new File(tempDir, resourcePath); try { File parentPom = new File(tempDir.getParentFile(), "pom.xml"); if (!parentPom.exists()) { URL resource = cl.getResource("/pom.xml"); FileUtils.copyURLToFile(resource, parentPom); } FileUtils.deleteDirectory(testDir); File file = ResourceExtractor.extractResourceToDestination(cl, resourcePath, tempDir, true); return file.getCanonicalFile(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.sling.its.ITSTest.java
/** * Get the parent directory.//from w w w .j av a 2s . c o m * * @param clazz * class * @param filepath * file path * @return parent directory */ @SuppressWarnings("rawtypes") private String getParentDir(final Class clazz, final String filepath) { final URL url = clazz.getResource(filepath); String parentDir = null; if (url != null) { try { final File file = new File(url.toURI()); parentDir = Util.ensureSeparator(file.getParent(), true); } catch (final URISyntaxException e) { return null; } } return parentDir; }
From source file:org.apache.struts2.convention.PackageBasedActionConfigBuilder.java
/** * Creates a single ActionConfig object. * * @param pkgCfg The package the action configuration instance will belong to. * @param actionClass The action class. * @param actionName The name of the action. * @param actionMethod The method that the annotation was on (if the annotation is not null) or * the default method (execute). * @param annotation The ActionName annotation that might override the action name and possibly *//*from ww w. j a v a 2 s . c om*/ protected void createActionConfig(PackageConfig.Builder pkgCfg, Class<?> actionClass, String actionName, String actionMethod, Action annotation) { String className = actionClass.getName(); if (annotation != null) { actionName = annotation.value() != null && annotation.value().equals(Action.DEFAULT_VALUE) ? actionName : annotation.value(); actionName = StringUtils.contains(actionName, "/") && !slashesInActionNames ? StringUtils.substringAfterLast(actionName, "/") : actionName; if (!Action.DEFAULT_VALUE.equals(annotation.className())) { className = annotation.className(); } } ActionConfig.Builder actionConfig = new ActionConfig.Builder(pkgCfg.getName(), actionName, className); actionConfig.methodName(actionMethod); if (LOG.isDebugEnabled()) { LOG.debug("Creating action config for class [#0], name [#1] and package name [#2] in namespace [#3]", actionClass.toString(), actionName, pkgCfg.getName(), pkgCfg.getNamespace()); } //build interceptors List<InterceptorMapping> interceptors = interceptorMapBuilder.build(actionClass, pkgCfg, actionName, annotation); actionConfig.addInterceptors(interceptors); //build results Map<String, ResultConfig> results = resultMapBuilder.build(actionClass, annotation, actionName, pkgCfg.build()); actionConfig.addResultConfigs(results); //add params if (annotation != null) actionConfig.addParams(StringTools.createParameterMap(annotation.params())); //add exception mappings from annotation if (annotation != null && annotation.exceptionMappings() != null) actionConfig.addExceptionMappings(buildExceptionMappings(annotation.exceptionMappings(), actionName)); //add exception mapping from class ExceptionMappings exceptionMappings = actionClass.getAnnotation(ExceptionMappings.class); if (exceptionMappings != null) actionConfig.addExceptionMappings(buildExceptionMappings(exceptionMappings.value(), actionName)); //add pkgCfg.addActionConfig(actionName, actionConfig.build()); //check if an action with the same name exists on that package (from XML config probably) PackageConfig existingPkg = configuration.getPackageConfig(pkgCfg.getName()); if (existingPkg != null) { // there is a package already with that name, check action ActionConfig existingActionConfig = existingPkg.getActionConfigs().get(actionName); if (existingActionConfig != null && LOG.isWarnEnabled()) LOG.warn("Duplicated action definition in package [#0] with name [#1].", pkgCfg.getName(), actionName); } //watch class file if (isReloadEnabled()) { URL classFile = actionClass.getResource(actionClass.getSimpleName() + ".class"); fileManager.monitorFile(classFile); loadedFileUrls.add(classFile.toString()); } }
From source file:org.apache.xml.security.utils.ClassLoaderUtils.java
/** * Load a given resource. <p/> This method will try to load the resource * using the following methods (in order): * <ul>/*from w ww . j a va 2s .c o m*/ * <li>From Thread.currentThread().getContextClassLoader() * <li>From ClassLoaderUtil.class.getClassLoader() * <li>callingClass.getClassLoader() * </ul> * * @param resourceName The name of the resource to load * @param callingClass The Class object of the calling object */ public static URL getResource(String resourceName, Class<?> callingClass) { URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null && resourceName.startsWith("/")) { //certain classloaders need it without the leading / url = Thread.currentThread().getContextClassLoader().getResource(resourceName.substring(1)); } ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (url == null) { url = cluClassloader.getResource(resourceName); } if (url == null && resourceName.startsWith("/")) { //certain classloaders need it without the leading / url = cluClassloader.getResource(resourceName.substring(1)); } if (url == null) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { url = cl.getResource(resourceName); } } if (url == null) { url = callingClass.getResource(resourceName); } if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResource('/' + resourceName, callingClass); } return url; }
From source file:org.apache.xml.security.utils.ClassLoaderUtils.java
/** * Load a given resources. <p/> This method will try to load the resources * using the following methods (in order): * <ul>/*from w w w. jav a 2s .c om*/ * <li>From Thread.currentThread().getContextClassLoader() * <li>From ClassLoaderUtil.class.getClassLoader() * <li>callingClass.getClassLoader() * </ul> * * @param resourceName The name of the resource to load * @param callingClass The Class object of the calling object */ public static List<URL> getResources(String resourceName, Class<?> callingClass) { List<URL> ret = new ArrayList<URL>(); Enumeration<URL> urls = new Enumeration<URL>() { public boolean hasMoreElements() { return false; } public URL nextElement() { return null; } }; try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } //ignore } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName.substring(1)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (!urls.hasMoreElements()) { try { urls = cluClassloader.getResources(resourceName); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = cluClassloader.getResources(resourceName.substring(1)); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } if (!urls.hasMoreElements()) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { try { urls = cl.getResources(resourceName); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug(e); } // ignore } } } if (!urls.hasMoreElements()) { URL url = callingClass.getResource(resourceName); if (url != null) { ret.add(url); } } while (urls.hasMoreElements()) { ret.add(urls.nextElement()); } if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResources('/' + resourceName, callingClass); } return ret; }
From source file:org.apereo.portal.utils.ResourceLoader.java
/** * Finds a resource with a given name. This is a convenience method for accessing a resource * from a channel or from the uPortal framework. If a well-formed URL is passed in, * this method will use that URL unchanged to find the resource. * If the URL is not well-formed, this method will look for * the desired resource relative to the classpath. * If the resource name starts with "/", it is unchanged. Otherwise, the package name * of the requesting class is prepended to the resource name. * @param requestingClass the java.lang.Class object of the class that is attempting to load the resource * @param resource a String describing the full or partial URL of the resource to load * @return a URL identifying the requested resource * @throws ResourceMissingException// w ww . j a v a2 s.c o m */ public static URL getResourceAsURL(Class<?> requestingClass, String resource) throws ResourceMissingException { final Tuple<Class<?>, String> cacheKey = new Tuple<Class<?>, String>(requestingClass, resource); //Look for a cached URL final Map<Tuple<Class<?>, String>, URL> resourceUrlCache = ResourceLoader.resourceUrlCache; URL resourceURL = resourceUrlCache != null ? resourceUrlCache.get(cacheKey) : null; if (resourceURL != null) { return resourceURL; } //Look for a failed lookup final Map<Tuple<Class<?>, String>, ResourceMissingException> resourceUrlNotFoundCache = ResourceLoader.resourceUrlNotFoundCache; ResourceMissingException exception = resourceUrlNotFoundCache != null ? resourceUrlNotFoundCache.get(cacheKey) : null; if (exception != null) { throw new ResourceMissingException(exception); } try { resourceURL = new URL(resource); } catch (MalformedURLException murle) { // URL is invalid, now try to load from classpath resourceURL = requestingClass.getResource(resource); if (resourceURL == null) { String resourceRelativeToClasspath = null; if (resource.startsWith("/")) resourceRelativeToClasspath = resource; else resourceRelativeToClasspath = '/' + requestingClass.getPackage().getName().replace('.', '/') + '/' + resource; exception = new ResourceMissingException(resource, resourceRelativeToClasspath, "Resource not found in classpath: " + resourceRelativeToClasspath); if (resourceUrlNotFoundCache != null) { resourceUrlNotFoundCache.put(cacheKey, exception); } throw new ResourceMissingException(exception); } } if (resourceUrlCache != null) { resourceUrlCache.put(cacheKey, resourceURL); } return resourceURL; }
From source file:org.artificer.repository.jcr.JCRRepository.java
/** * Gets the configuration to use for the JCR repository. * @throws Exception//from www.java 2 s . c om */ private URL getModeshapeConfigurationUrl() throws Exception { String configUrl = ArtificerConfig.getConfigProperty("artificer.modeshape.config.url", null); if (configUrl == null) { return null; } if (configUrl.startsWith("classpath:")) { Pattern p = Pattern.compile("classpath:/?/?([^/]*)/(.*)$"); Matcher matcher = p.matcher(configUrl); if (matcher.matches()) { String className = matcher.group(1); String path = "/" + matcher.group(2); Class<?> clazz = Class.forName(className); URL resourceUrl = clazz.getResource(path); if (resourceUrl == null) throw new Exception(Messages.i18n.format("MISSING_CONFIG", configUrl)); return resourceUrl; } throw new Exception(Messages.i18n.format("INVALID_CLASSPATH_URL", configUrl)); } else { try { File f = new File(configUrl); if (f.isFile()) { return f.toURI().toURL(); } } catch (Exception e) { // eat the error and try the next option } try { return new URL(configUrl); } catch (Exception e) { // eat the error and try the next option } return null; } }
From source file:org.atricore.idbus.kernel.planning.jbpm.OsgiProcessFragmentRegistryApplicationContext.java
/** * Load a given resource. <p/> This method will try to load the resource * using the following methods (in order): * <ul>/* w ww. ja va2s . co m*/ * <li>From Thread.currentThread().getContextClassLoader() * <li>From ClassLoaderUtil.class.getClassLoader() * <li>callingClass.getClassLoader() * </ul> * * @param resourceName The name of the resource to load * @param callingClass The Class object of the calling object */ private URL getResource(String resourceName, Class callingClass) { URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); if (url == null && resourceName.startsWith("/")) { //certain classloaders need it without the leading / url = Thread.currentThread().getContextClassLoader().getResource(resourceName.substring(1)); } if (url == null) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { url = cl.getResource(resourceName); } } if (url == null) { url = callingClass.getResource(resourceName); } if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResource('/' + resourceName, callingClass); } return url; }
From source file:org.bimserver.shared.CodeFetcher.java
@Override public String get(Class<?> clazz) { URL url = clazz.getResource(clazz.getSimpleName() + ".java"); if (url == null) { try {/*from w w w . j a v a 2 s. c o m*/ url = new File("../PluginBase/src/" + clazz.getName().replace(".", "/") + ".java").toURI().toURL(); } catch (MalformedURLException e) { LOGGER.error("", e); } } if (url != null) { try { InputStream inputStream = url.openStream(); if (inputStream == null) { return null; } try { StringWriter out = new StringWriter(); IOUtils.copy(inputStream, out); return out.toString(); } finally { inputStream.close(); } } catch (IOException e) { LOGGER.error("", e); } } return null; }
From source file:org.dbflute.intro.app.logic.intro.IntroUpgradeLogic.java
public void upgrade() { File jarPathFile = new File("./dbflute-intro.jar"); Class<?> clazz = this.getClass(); URL location = clazz.getResource("/" + clazz.getName().replaceAll("\\.", "/") + ".class"); String path = location.getPath(); if (path.lastIndexOf("!") != -1) { try {/* w ww. j a va 2 s . c o m*/ jarPathFile = new File(URLDecoder.decode(path.substring("file:/".length(), path.lastIndexOf("!")), StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } try { FileUtils.copyURLToFile( new URL("http://p1us2er0.github.io/dbflute-intro/download/" + jarPathFile.getName()), jarPathFile); } catch (MalformedURLException e) { throw new IllegalStateException(e); } catch (IOException e) { throw new IllegalStateException(e); } }