List of usage examples for java.lang Class getResource
@CallerSensitive
public URL getResource(String name)
From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.MainTestCase.java
protected URL getResource(Class clazz, String urlPath) { URL url = clazz.getResource(urlPath); if (url == null) { throw new NullPointerException("URL Location = '" + urlPath + "' not found."); }//w ww . j a v a 2 s . c om return url; }
From source file:com.vmware.qe.framework.datadriven.impl.supplier.XMLDataSupplier.java
/** * Get's data from XML file in classpath in specified format.<br> * First search the/*w ww. j a va 2 s .c om*/ * * @param className ClassName * @param context The context. */ public HierarchicalConfiguration getData(final String className, HierarchicalConfiguration context) { HierarchicalConfiguration dataForTestCase = null; try { Class<?> clazz = Class.forName(className); String dataFilePath = null; URL dataFileURL = null; boolean packageFile = false; Map<String, HierarchicalConfiguration> dataMap = null; String dataFileName = context.getString("supplier.dataFile", null); log.debug("Checking the data file in argument..."); if (dataFileName == null || dataFileName.equals("")) { log.debug("Data file not given in argument..Using DataFileFinder.."); dataFilePath = DDUtils.findDataFile(className, ".xml", context); } else { log.debug("Got data file in argument"); dataFilePath = dataFileName; } log.debug("Data file path: " + dataFilePath); if (dataFilePath == null) { return null;// No data found, hence it's a normal test case. } dataFileURL = clazz.getResource(dataFilePath); if (packageFile) { // The data file is from package file name so check the cache. log.debug("Cache: " + cache.size()); synchronized (XMLDataSupplier.class) { if (loadedFiles.contains(dataFilePath)) { // get it from cache. log.info("File was loaded before !!!"); dataForTestCase = cache.get(clazz.getName()); } else {// not in cache, so load and put it to cache. log.info("File was not loaded before, loading now..."); if (dataFileURL != null) { cache.putAll(XMLDataParser.load(dataFileURL, clazz)); } else { cache.putAll(XMLDataParser.load(dataFilePath, clazz)); } dataForTestCase = cache.get(clazz.getName()); loadedFiles.add(dataFilePath); } } if ((dataForTestCase == null) || dataForTestCase.isEmpty()) { log.info("Data for '{}' is not available!", className); return null; } } else { // data file not from package file so go ahead and load. log.debug("Loading the xml file..."); if (dataFileURL != null) { dataMap = XMLDataParser.load(dataFileURL, clazz); } else { dataMap = XMLDataParser.load(dataFilePath, clazz); } dataForTestCase = dataMap.get(clazz.getName()); } } catch (Exception ex) { throw new DDException("Error in loading the data file", ex); } return dataForTestCase; }
From source file:Main.java
/** * Load a given resources. <p/> This method will try to load the resources * using the following methods (in order): * <ul>// w w w . jav a2 s.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 */ 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) { //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) { // ignore } } ClassLoader cluClassloader = Main.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (!urls.hasMoreElements()) { try { urls = cluClassloader.getResources(resourceName); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = cluClassloader.getResources(resourceName.substring(1)); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements()) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { try { urls = cl.getResources(resourceName); } catch (IOException 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:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Return an array of URLs for 'special' trusted CAs' certificates contained in * the resources folder that need to be loaded into Truststore, so that we can establish trust * into services such as BioCatalogue, BiodiversityCatalogue, heater, etc. by default. * *//*from ww w. j a v a2 s. c o m*/ private static List<URL> getSpecialTrustedCertificates() { List<URL> urls = new ArrayList<>(); Class<?> c = CredentialManager.class; urls.add(c.getResource("/trusted-certificates/TERENASSLCA.crt")); urls.add(c.getResource("/trusted-certificates/UTNAddTrustServer_CA.crt")); urls.add(c.getResource("/trusted-certificates/AddTrustExternalCARoot.crt")); return urls; }
From source file:de.innovationgate.utils.WGUtils.java
/** * Determines the location of the classfile that defines the given class. * This can be useful if a class is in classpath multiple times to determine * which version is really used./*from www . ja va 2 s . c om*/ * * @param className * The class to find. * @param refClass * The class that itself will use this class in its code. It's * classloader will be used to find the location * @return The location of the classfile as path. */ public static String which(String className, Class<?> refClass) { if (!className.startsWith("/")) { className = "/" + className; } className = className.replace('.', '/'); className = className + ".class"; java.net.URL classUrl = refClass.getResource(className); if (classUrl != null) { return classUrl.getFile(); } else { return null; } }
From source file:me.azenet.UHPlugin.UHPluginCommand.java
/** * This command prints some informations about the plugin and the translation. * /* w w w. j a v a 2 s .c o m*/ * Usage: /uh about * * @param sender * @param command * @param label * @param args */ @SuppressWarnings("unused") private void doAbout(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) sender.sendMessage(""); sender.sendMessage( i.t("cmd.titleHelp", p.getDescription().getDescription(), p.getDescription().getVersion())); // Authors String authors = ""; List<String> listAuthors = p.getDescription().getAuthors(); for (String author : listAuthors) { if (author == listAuthors.get(0)) { // Nothing } else if (author == listAuthors.get(listAuthors.size() - 1)) { authors += " " + i.t("about.and") + " "; } else { authors += ", "; } authors += author; } sender.sendMessage(i.t("about.authors", authors)); // Build number String build = null; try { Class<? extends UHPlugin> clazz = p.getClass(); String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); if (classPath.startsWith("jar")) { // Class from JAR String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attr = manifest.getMainAttributes(); build = attr.getValue("Git-Commit"); } } catch (IOException e) { // Build not available. } if (build != null) { sender.sendMessage(i.t("about.build.number", build)); } else { sender.sendMessage(i.t("about.build.notAvailable")); } // Translation sender.sendMessage(i.t("about.i18n.title")); sender.sendMessage( i.t("about.i18n.selected", i.getSelectedLanguage(), i.getTranslator(i.getSelectedLanguage()))); sender.sendMessage( i.t("about.i18n.fallback", i.getDefaultLanguage(), i.getTranslator(i.getDefaultLanguage()))); sender.sendMessage(i.t("about.license.title")); sender.sendMessage(i.t("about.license.license")); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java
/** * Delete the old revoked or unnecessary BioCatalogue, BiodiversityCatalogue * and heater's certificates, if present *//*from ww w . jav a 2s.c o m*/ public void deleteRevokedCertificates() { if (truststore == null) return; if (certificatesRevokedIndicatorFile == null) certificatesRevokedIndicatorFile = new File(credentialManagerDirectory, CERTIFICATES_REVOKED_INDICATOR_FILE_NAME); boolean saveFile = false; if (!certificatesRevokedIndicatorFile.exists()) { List<URL> certURLsToDelete = new ArrayList<>(); Class<?> c = CredentialManager.class; certURLsToDelete.add(c.getResource("/trusted-certificates/www.biocatalogue.org-revoked.pem")); certURLsToDelete.add(c.getResource("/trusted-certificates/www.biodiversitycatalogue.org-revoked.pem")); certURLsToDelete.add(c.getResource("/trusted-certificates/heater.cs.man.ac.uk-not-needed.pem")); for (URL certURLToDelete : certURLsToDelete) { try (InputStream certStreamToDelete = certURLToDelete.openStream()) { // We know there will be only one cert in the chain CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate certToDelete = cf.generateCertificates(certStreamToDelete) .toArray(new Certificate[0])[0]; String aliasToDelete = truststore.getCertificateAlias(certToDelete); if (aliasToDelete != null) { truststore.deleteEntry(aliasToDelete); logger.warn("Deleting revoked/unnecessary certificate " + aliasToDelete); saveFile = true; } } catch (Exception ex) { logger.info("Can't delete revoked certificate " + certURLToDelete, ex); } } // Touch the file try { touch(certificatesRevokedIndicatorFile); } catch (IOException ioex) { // Hmmm, ignore this? logger.error("Failed to touch " + certificatesRevokedIndicatorFile.getAbsolutePath(), ioex); } } if (saveFile) { // Save changes try (FileOutputStream fos = new FileOutputStream(truststoreFile)) { truststore.store(fos, masterPassword.toCharArray()); } catch (Exception ex) { logger.error("Failed to save Truststore after deleting revoked certificates.", ex); } } }
From source file:com.amalto.workbench.utils.Util.java
public static String getPackageFilePath(Class<? extends Object> c, String filename) { return c.getResource(filename).getPath(); }
From source file:com.apdplat.platform.struts.APDPlatPackageBasedActionConfigBuilder.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 *//*w ww . jav a 2s . c o m*/ protected void createActionConfig(PackageConfig.Builder pkgCfg, Class<?> actionClass, String actionName, String actionMethod, Action annotation) { if (annotation != null) { actionName = annotation.value() != null && annotation.value().equals(Action.DEFAULT_VALUE) ? actionName : annotation.value(); actionName = StringUtils.contains(actionName, "/") ? StringUtils.substringAfterLast(actionName, "/") : actionName; } ActionConfig.Builder actionConfig = new ActionConfig.Builder(pkgCfg.getName(), actionName, actionClass.getName()); actionConfig.methodName(actionMethod); if (LOG.isDebugEnabled()) { LOG.debug("Creating action config for class [" + actionClass.toString() + "], name [" + actionName + "] and package name [" + pkgCfg.getName() + "] in namespace [" + 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.loadFile(classFile, false); loadedFileUrls.add(classFile.toString()); } }