Get all components from a jar file

@param jar
@return the list of components from the jar. (Implement 'Execute' annotation)
@throws IOException
@throws ClassNotFoundException
961565
public static List<Class<?>> getComponentClasses(URL jar) throws IOException {
        JarInputStream jarFile = new JarInputStream(jar.openStream());
        URLClassLoader cl = new URLClassLoader(new URL[]{jar}, Thread.currentThread().getContextClassLoader());
        List<Class<?>> idx = new ArrayList<Class<?>>();

        JarEntry jarEntry = jarFile.getNextJarEntry();
        while (jarEntry != null) {
            String classname = jarEntry.getName();
//            System.out.println(classname);
            if (classname.endsWith(".class")) {
                classname = classname.substring(0, classname.indexOf(".class")).replace('/', '.');
                try {
                    Class<?> c = Class.forName(classname, false, cl);
                    for (Method method : c.getMethods()) {
                        if ((method.getAnnotation(Execute.class)) != null) {
                            idx.add(c);
                            break;
                        }
                    }
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                }
            }
            jarEntry = jarFile.getNextJarEntry();
        }
        jarFile.close();
        return idx;
    }
1237548
protected List<File> getClassPath() throws MojoExecutionException {
		if (this.bufferedClasspath == null) {
			final Set<String> classPath = new LinkedHashSet<>();
			final MavenProject project = getProject();
			classPath.add(project.getBuild().getSourceDirectory());
			try {
				classPath.addAll(project.getCompileClasspathElements());
			} catch (DependencyResolutionRequiredException e) {
				throw new MojoExecutionException(e.getLocalizedMessage(), e);
			}
			for (final Artifact dep : project.getArtifacts()) {
				classPath.add(dep.getFile().getAbsolutePath());
			}
			classPath.remove(project.getBuild().getOutputDirectory());
			final List<File> files = new ArrayList<>();
			for (final String filename : classPath) {
				final File file = new File(filename);
				if (file.exists()) {
					files.add(file);
				} else {
					getLog().warn(MessageFormat.format(Messages.AbstractSarlBatchCompilerMojo_10, filename));
				}
			}
			this.bufferedClasspath = files;
		}
		return this.bufferedClasspath;
	}
501646
public final <C extends CalendarComponent> ComponentList<C> getComponents(final String name) {
        return getComponents().getComponents(name);
    }
443393
public static void main(String[] args) throws ClassNotFoundException, IOException {
      // When run off the command-line or a build script, this program takes in two arguments: the path containing
      // class files to scan, and the output file to generate.
      long startTime = System.nanoTime();
      String path = args[0];
      String outputFile = args[1];

      System.out.printf(" [ComponentMetadataPersister] Starting component metadata generation.  Scanning classes in %s%n", path);

      ComponentMetadataRepo repo = new ComponentMetadataRepo();

      File f = new File(path);
      process(repo, f.getAbsolutePath(), f);

      // Test that all dependencies now exist in the component metadata map.
      Map<String, String> dependencies = new HashMap<>(128);
      for (ComponentMetadata md : repo.componentMetadataMap.values()) {
         if (md.getDependencies() != null) dependencies.putAll(md.getDependencies());
      }

      if (Boolean.getBoolean("infinispan.isCoreModule")) {
         // Perform this sanity check
         boolean hasErrors = false;
         for (Map.Entry<String, String> e : dependencies.entrySet()) {
            if (!repo.componentMetadataMap.containsKey(e.getKey())) {
               if (!repo.hasFactory(e.getKey())) {
                  System.out.printf(" [ComponentMetadataPersister]     **** WARNING!!!  Missing components or factories for dependency on %s%n", e.getKey());
                  hasErrors = true;
               }
            }
         }

         if (hasErrors && Boolean.getBoolean("infinispan.isCoreModule"))
            throw new RuntimeException("Could not pass sanity check of all annotated components and their respective factories/dependencies.");
      }
      writeMetadata(repo, outputFile);

      System.out.printf(" [ComponentMetadataPersister] %s components and %s factories.%n%n",
            repo.componentMetadataMap.size(), repo.factories.size());
   }
407518
public void scanJars() throws IOException {

        ClassLoader webappLoader = Thread.currentThread().getContextClassLoader();

        ClassLoader parentLoader = webappLoader.getParent();

        ResourceDelegatingBundleClassLoader classLoader = null;
        if (webappLoader instanceof ResourceDelegatingBundleClassLoader) {
            classLoader = (ResourceDelegatingBundleClassLoader) webappLoader;
        } else if (parentLoader instanceof ResourceDelegatingBundleClassLoader) {
            classLoader = (ResourceDelegatingBundleClassLoader) parentLoader;
        } else if (isTomcatWebLoader()) {
            ClassLoader parent = ((org.apache.catalina.loader.WebappClassLoader) webappLoader).getParent();
            if (parent instanceof ResourceDelegatingBundleClassLoader) {
                classLoader = (ResourceDelegatingBundleClassLoader) parent;
            }
        }

        List<Bundle> bundles = classLoader == null ? Collections.<Bundle>emptyList() : classLoader.getBundles();
        for (Bundle bundle : bundles) {
            Collection<Enumeration<URL>> enumerations;
            BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
            if (bundleWiring == null) {
                Enumeration<URL> urls = bundle.findEntries("META-INF", "*.tld", true);
                enumerations = Collections.singleton(urls);
            } else {
                Collection<String> resources = bundleWiring.listResources("META-INF", "*.tld",
                        BundleWiring.LISTRESOURCES_RECURSE);
                enumerations = new ArrayList<>(resources.size());
                for (String resource : resources) {
                    Enumeration<URL> urls = bundle.getResources(resource);
                    enumerations.add(urls);
                }
            }
            for (Enumeration<URL> urls : enumerations) {
                if (urls != null) {
                    while (urls.hasMoreElements()) {
                        URL url = urls.nextElement();
                        LOG.info("found TLD {}", url);
                        TldResourcePath tldResourcePath = new TldResourcePath(url, null, null);
                        try {
                            parseTld(tldResourcePath);
                        } catch (SAXException e) {
                            throw new IOException(e);
                        }
                    }
                }
            }
        }
    }
262232
public static List<String> getJreJars() {
    String javaHome = System.getProperty("java.home");
    Path libsDir = FileSystems.getDefault().getPath(javaHome, "/lib");
    List<String> retval = GosucUtil.getIbmClasspath();
    try {
      retval.addAll(Files.walk(libsDir)
              .filter( path -> path.toFile().isFile())
              .filter( path -> path.toString().endsWith(".jar"))
              .map( Path::toString )
              .collect(Collectors.toList()));
    } catch (SecurityException | IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    return retval;
  }
36450
public void addJar(String jarName) {
        try {
            list.add(new JarPathEntry(new JarFile(jarName)));
        } catch (IOException ignore) { }
    }
531367
List<File> findNonJdkJars() throws IOException, SAXException, XPathExpressionException, ParserConfigurationException {
        Enumeration<URL> manifests = LibraryVersions.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        String javaHome = System.getProperty("java.home");
        List<File> ret = new LinkedList<File>();
        while (manifests.hasMoreElements()) {
            URL u = manifests.nextElement();
            // jar:file:/home/username/.m2/repository/org/slf4j/slf4j-jdk14/1.5.0/slf4j-jdk14-1.5.0.jar!/META-INF/MANIFEST.MF
            // we're not interested if it's not a jar, although how you'd have a MANIFEST.MF which wasn't in a jar?
            if (u.getProtocol().equals("jar")) {
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar!/META-INF/MANIFEST.MF
                String file = u.getFile();
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(0, file.indexOf("!"));
                // /home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(5);
                // remove %20 etc
                file = URLDecoder.decode(file, "UTF-8");
                File f = new File(file);
                String canonicalPath = f.getCanonicalPath();
                if (!canonicalPath.startsWith(javaHome)) {
                    ret.add(f);
                }
            } else {
                logger.info("Can't include code in checksum which isn't in a JAR: " + u);
            }
        }
        return ret;
    }
1293938
private final void readDirectories(final URL jarFile) {
		JarInputStream jarIn = null;

		try {
			if (!jarFile.getPath().endsWith(".jar")) {
				return;
			}
			if (CClassLoader.sl(CClassLoader.DEBUG)) {
				CClassLoader.log("opening jar : " + jarFile.toExternalForm(),
						CClassLoader.DEBUG);
			}
			jarIn = new JarInputStream(jarFile.openStream());
			JarEntry jarEntry = null;

			while ((jarEntry = jarIn.getNextJarEntry()) != null) {
				if (jarEntry.isDirectory()) {
					continue;
				}

				final URL url = new URL("yahpjarloader://"
						+ CBASE64Codec.encode(
								jarFile.toExternalForm().getBytes("utf-8"))
								.replaceAll("\n", "") + "/"
						+ jarEntry.getName());

				if (CClassLoader.sl(CClassLoader.DEBUG)) {
					CClassLoader.log("found entry : " + url.toString(),
							CClassLoader.DEBUG);
				}

				if (jarEntry.getName().endsWith(".class")) {
					if (!this.classesMap.containsKey(jarEntry.getName())) {
						if (!this.booResourceOnly) {
							this.classesMap.put(jarEntry.getName(), url);
						}
					}

					if (this.resourcesMap.containsKey(jarEntry.getName())) {
						final Object to = this.resourcesMap.get(jarEntry
								.getName());
						if (to instanceof URL) {
							final URL uo = (URL) to;
							final List l = new ArrayList();
							l.add(uo);
							l.add(url);
							this.resourcesMap.put(jarEntry.getName(), l);
						} else if (to instanceof List) {
							final List uo = (List) to;
							uo.add(url);
							this.resourcesMap.put(jarEntry.getName(), uo);
						}
					} else {
						this.resourcesMap.put(jarEntry.getName(), url);
					}
				} else if (jarEntry.getName().startsWith("native/")) {
					String system = jarEntry.getName().substring(7);
					system = system.substring(0, system.indexOf('/'));
					if (!this.dllMap.containsKey(system)) {
						this.dllMap.put(system, url);
					}
					if (this.resourcesMap.containsKey(jarEntry.getName())) {
						final Object to = this.resourcesMap.get(jarEntry
								.getName());
						if (to instanceof URL) {
							final URL uo = (URL) to;
							final List l = new ArrayList();
							l.add(uo);
							l.add(url);
							this.resourcesMap.put(jarEntry.getName(), l);
						} else if (to instanceof List) {
							final List uo = (List) to;
							uo.add(url);
							this.resourcesMap.put(jarEntry.getName(), uo);
						}
					} else {
						this.resourcesMap.put(jarEntry.getName(), url);
					}
				} else {
					if (this.resourcesMap.containsKey(jarEntry.getName())) {
						final Object to = this.resourcesMap.get(jarEntry
								.getName());
						if (to instanceof URL) {
							final URL uo = (URL) to;
							final List l = new ArrayList();
							l.add(uo);
							l.add(url);
							this.resourcesMap.put(jarEntry.getName(), l);
						} else if (to instanceof List) {
							final List uo = (List) to;
							uo.add(url);
							this.resourcesMap.put(jarEntry.getName(), uo);
						}
					} else {
						this.resourcesMap.put(jarEntry.getName(), url);
					}
				}
			}

			if (CClassLoader.sl(CClassLoader.DEBUG)) {
				CClassLoader.log("opening jar : "
						+ jarFile.getFile().toString() + " done.",
						CClassLoader.DEBUG);
			}
		} catch (final MalformedURLException mue) {
			mue.printStackTrace();

			if (CClassLoader.sl(CClassLoader.FATAL)) {
				CClassLoader.log(mue.getMessage(), CClassLoader.FATAL);
			}
		} catch (final IOException ioe) {
			ioe.printStackTrace();

			if (CClassLoader.sl(CClassLoader.FATAL)) {
				CClassLoader.log(ioe.getMessage(), CClassLoader.FATAL);
			}
		} catch (final Exception e) {
			e.printStackTrace();

			if (CClassLoader.sl(CClassLoader.FATAL)) {
				CClassLoader.log(e.getMessage(), CClassLoader.FATAL);
			}
		} finally {
			try {
				jarIn.close();
				jarIn = null;
			} catch (final Exception e) {
			}
		}
	}
1368655
public static URL[] getLibJars(Configuration conf) throws IOException {
    String jars = conf.get("tmpjars");
    if(jars==null) {
      return null;
    }
    String[] files = jars.split(",");
    URL[] cp = new URL[files.length];
    for (int i=0;i<cp.length;i++) {
      Path tmp = new Path(files[i]);
      cp[i] = FileSystem.getLocal(conf).pathToFile(tmp).toURI().toURL();
    }
    return cp;
  }
1015470
ProviderList getJarList(String[] jarClassNames) {
        List<ProviderConfig> newConfigs = new ArrayList<>();
        for (String className : jarClassNames) {
            ProviderConfig newConfig = new ProviderConfig(className);
            for (ProviderConfig config : configs) {
                // if the equivalent object is present in this provider list,
                // use the old object rather than the new object.
                // this ensures that when the provider is loaded in the
                // new thread local list, it will also become available
                // in this provider list
                if (config.equals(newConfig)) {
                    newConfig = config;
                    break;
                }
            }
            newConfigs.add(newConfig);
        }
        ProviderConfig[] configArray = newConfigs.toArray(PC0);
        return new ProviderList(configArray, false);
    }
884678
public static String findMainClass(JarFile jarFile, String classesLocation)
            throws IOException {
        return doWithMainClasses(jarFile, classesLocation,
                new ClassNameCallback<String>() {
                    @Override
                    public String doWith(String className) {
                        return className;
                    }
                });
    }
445265
public static String findSingleMainClass(JarFile jarFile, String classesLocation)
            throws IOException {
        MainClassesCallback callback = new MainClassesCallback();
        MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback);
        return callback.getMainClass();
    }
1260315
public List<ICalComponent> getComponents(T component) {
		return new ArrayList<ICalComponent>(component.getComponents().values());
	}
707914
@Override
    public Collection<Part> getParts() throws IOException, ServletException {
        try {
            collaborator.preInvoke(componentMetaData);
            return request.getParts();
        } finally {
            collaborator.postInvoke();
        }
    }
177056
public static List<Resource> getClasspathResources() {
      synchronized (classpathResources) {
         if (classpathResources.isEmpty()) {
            for (String jar : SystemInfo.JAVA_CLASS_PATH.split(SystemInfo.PATH_SEPARATOR)) {
               File file = new File(jar);
               if (file.isDirectory()) {
                  classpathResources.addAll(new FileResource(file).getChildren(true));
               } else {
                  classpathResources.addAll(getJarContents(Resources.fromFile(jar), v -> true));
               }
            }
         }
         return Collections.unmodifiableList(classpathResources);
      }
   }
361588
public <T extends ICalComponent> List<T> getComponents(Class<T> clazz) {
		return new ICalComponentList<T>(clazz);
	}