Java Code Examples for com.google.common.reflect.ClassPath#from()

The following examples show how to use com.google.common.reflect.ClassPath#from() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NonStaticInnerClassBanTest.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * The full set of classes to check. This set is derived from the classpath, so you must add Buck
 * dependencies on packages that contain classes that you want to test, otherwise they won't be in
 * the classpath!
 */
@Parameterized.Parameters(name = "{0}")
public static Collection<Class<?>> data() throws IOException {
  ClassPath classpath = ClassPath.from(ClassLoader.getSystemClassLoader());
  return classpath.getAllClasses().stream()
      // Exclude anything we didn't write
      .filter(info -> info.getPackageName().startsWith("com.facebook.buck"))
      // Only operate on nested classes
      .filter(info -> info.getName().contains("$"))
      .map(ClassPath.ClassInfo::load)
      // Only operate on nested classes deriving from one or more of the classes we're checking
      .filter(
          clazz ->
              bannedClasses.stream().anyMatch(bannedClass -> bannedClass.isAssignableFrom(clazz)))
      .collect(Collectors.toList());
}
 
Example 2
Source File: AbstractScanner.java    From minnal with Apache License 2.0 6 votes vote down vote up
public void scan(Listener<Class<?>> listener) {
	try {
		ClassPath path = ClassPath.from(classLoader);
		for (String packageName : packages) {
			for (ClassInfo classInfo : path.getTopLevelClassesRecursive(packageName)) {
				Class<?> clazz = classLoader.loadClass(classInfo.getName());
				if (match(clazz)) {
					listener.handle(clazz);
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		// TODO Handle exception
	}
}
 
Example 3
Source File: DefaultWidgetTypesRegistry.java    From Orienteer with Apache License 2.0 6 votes vote down vote up
public IWidgetTypesRegistry register(String packageName, ClassLoader classLoader) {
	ClassPath classPath;
	try {
		classPath = ClassPath.from(classLoader);
	} catch (IOException e) {
		throw new WicketRuntimeException("Can't scan classpath", e);
	}
	ImmutableSet<ClassInfo> classesInPackage = classPath.getTopLevelClassesRecursive(packageName);
	for (ClassInfo classInfo : classesInPackage) {
		Class<?> clazz = classInfo.load();
		Widget widgetDescription = clazz.getAnnotation(Widget.class);
		if (widgetDescription != null) {
			if (!AbstractWidget.class.isAssignableFrom(clazz))
				throw new WicketRuntimeException("@" + Widget.class.getSimpleName() + " should be only on widgets");
			Class<? extends AbstractWidget<Object>> widgetClass = (Class<? extends AbstractWidget<Object>>) clazz;
			register(widgetClass);
		}
	}
	return this;
}
 
Example 4
Source File: ProbeBundleMaker.java    From wisdom with Apache License 2.0 6 votes vote down vote up
private static Jar[] computeClassPath() throws IOException {
    List<Jar> list = new ArrayList<>();
    File tests = new File(TEST_CLASSES);

    if (tests.isDirectory()) {
        list.add(new Jar(".", tests));
    }

    ClassPath classpath = ClassPath.from(ProbeBundleMaker.class.getClassLoader());
    list.add(new JarFromClassloader(classpath));

    Jar[] cp = new Jar[list.size()];
    list.toArray(cp);

    return cp;

}
 
Example 5
Source File: CheckUtil.java    From sonar-checkstyle with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets all checkstyle's modules.
 * @return the set of checkstyle's module classes.
 * @throws IOException if the attempt to read class path resources failed.
 * @see #isCheckstyleModule(Class)
 */
public static Set<Class<?>> getCheckstyleModules() throws IOException {
    final Set<Class<?>> checkstyleModules = new HashSet<>();

    final ClassLoader loader = Thread.currentThread()
            .getContextClassLoader();
    final ClassPath classpath = ClassPath.from(loader);
    final String packageName = "com.puppycrawl.tools.checkstyle";
    final ImmutableSet<ClassPath.ClassInfo> checkstyleClasses = classpath
            .getTopLevelClassesRecursive(packageName);

    for (ClassPath.ClassInfo clazz : checkstyleClasses) {
        final Class<?> loadedClass = clazz.load();
        if (isCheckstyleModule(loadedClass)) {
            checkstyleModules.add(loadedClass);
        }
    }
    return checkstyleModules;
}
 
Example 6
Source File: ClasspathResourceRepository.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Resource> list(String directory) {
    try {
        ClassPath classpath = ClassPath.from(Thread.currentThread().getContextClassLoader());
        List<Resource> resources = Lists.newArrayList();
        for (ClassPath.ResourceInfo resourceInfo : classpath.getResources()) {
            if (resourceInfo.getResourceName().startsWith(basePath)) {
                String name = resourceInfo.getResourceName();
                String path = name.substring(basePath.length());
                if (path.startsWith(directory)) {
                    resources.add(new ClasspathResource(path, name));
                }
            }
        }
        return resources;
    } catch (IOException e) {
        throw new ResourceException(e);
    }
}
 
Example 7
Source File: ModuleManager.java    From PIPE with MIT License 6 votes vote down vote up
/**
 * Finds all the fully qualified (ie: full package names) module classnames
 * by recursively searching the rootDirectories
 *
 * @return
 */
//only load attempt to add .class files
private Collection<Class<? extends GuiModule>> getModuleClasses() {
    Collection<Class<? extends GuiModule>> results = new ArrayList<>();
    try {
        ClassPath classPath = ClassPath.from(this.getClass().getClassLoader());
        ImmutableSet<ClassPath.ClassInfo> set = classPath.getTopLevelClasses(PIPE_GUI_PLUGIN_CONCRETE_PACKAGE);
        for (ClassPath.ClassInfo classInfo : set) {
            Class<?> clazz = classInfo.load();
            if (GuiModule.class.isAssignableFrom(clazz)) {
                results.add((Class<? extends GuiModule>) clazz);
            }
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage());
    }
    return results;
}
 
Example 8
Source File: PluginManager.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void loadCorePlugins() throws IOException, PluginInstantiationException
{
	SplashScreen.stage(.59, null, "Loading Plugins");
	ClassPath classPath = ClassPath.from(getClass().getClassLoader());

	List<Class<?>> plugins = classPath.getTopLevelClassesRecursive(PLUGIN_PACKAGE).stream()
		.map(ClassInfo::load)
		.collect(Collectors.toList());

	loadPlugins(plugins, (loaded, total) ->
		SplashScreen.stage(.60, .70, null, "Loading Plugins", loaded, total, false));
}
 
Example 9
Source File: ScriptRunner.java    From purplejs with Apache License 2.0 5 votes vote down vote up
private static ClassPath initClassPath()
{
    try
    {
        return ClassPath.from( ScriptRunner.class.getClassLoader() );
    }
    catch ( final Exception e )
    {
        throw new Error( e );
    }
}
 
Example 10
Source File: GenrulePremiumListTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_allPremiumLists() throws Exception {
  ClassPath classpath = ClassPath.from(getClass().getClassLoader());
  int numParsed = 0;
  for (ResourceInfo resource : classpath.getResources()) {
    if (resource.getResourceName().startsWith(LISTS_DIRECTORY)
        && resource.getResourceName().endsWith(".txt")) {
      testParseOfPremiumListFile(resource.getResourceName());
      numParsed++;
    }
  }
  assertWithMessage("No premium lists found").that(numParsed).isAtLeast(1);
}
 
Example 11
Source File: GenruleReservedListTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testParse_allReservedLists() throws Exception {
  ClassPath classpath = ClassPath.from(getClass().getClassLoader());
  int numParsed = 0;
  for (ResourceInfo resource : classpath.getResources()) {
    if (resource.getResourceName().startsWith(LISTS_DIRECTORY)
        && resource.getResourceName().endsWith(".txt")) {
      testParseOfReservedListFile(resource.getResourceName());
      numParsed++;
    }
  }
  assertWithMessage("No reserved lists found").that(numParsed).isAtLeast(1);
}
 
Example 12
Source File: ClassPathResourceTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
private static ClassPath.ResourceInfo getResourceForName(String name) throws IOException {
    ClassPath cp = ClassPath.from(ClassPathResourceTest.class.getClassLoader());
    ImmutableSet<ClassPath.ResourceInfo> resources = cp.getResources();
    for (ClassPath.ResourceInfo info : resources) {
        if (info.getResourceName().equals(name)) {
            return info;
        }
    }
    return null;
}
 
Example 13
Source File: DispatcherManager.java    From skywalking with Apache License 2.0 5 votes vote down vote up
/**
 * Scan all classes under `org.apache.skywalking` package,
 * <p>
 * If it implement {@link org.apache.skywalking.oap.server.core.analysis.SourceDispatcher}, then, it will be added
 * into this DispatcherManager based on the Source definition.
 */
public void scan() throws IOException, IllegalAccessException, InstantiationException {
    ClassPath classpath = ClassPath.from(this.getClass().getClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classpath.getTopLevelClassesRecursive("org.apache.skywalking");
    for (ClassPath.ClassInfo classInfo : classes) {
        Class<?> aClass = classInfo.load();

        addIfAsSourceDispatcher(aClass);
    }
}
 
Example 14
Source File: MeterSystem.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public MeterSystem(final ModuleManager manager) {
    this.manager = manager;
    classPool = ClassPool.getDefault();

    ClassPath classpath = null;
    try {
        classpath = ClassPath.from(MeterSystem.class.getClassLoader());
    } catch (IOException e) {
        throw new UnexpectedException("Load class path failure.");
    }
    ImmutableSet<ClassPath.ClassInfo> classes = classpath.getTopLevelClassesRecursive("org.apache.skywalking");
    for (ClassPath.ClassInfo classInfo : classes) {
        Class<?> functionClass = classInfo.load();

        if (functionClass.isAnnotationPresent(MeterFunction.class)) {
            MeterFunction metricsFunction = functionClass.getAnnotation(MeterFunction.class);
            if (!AcceptableValue.class.isAssignableFrom(functionClass)) {
                throw new IllegalArgumentException(
                    "Function " + functionClass.getCanonicalName() + " doesn't implement AcceptableValue.");
            }
            functionRegister.put(
                metricsFunction.functionName(),
                (Class<? extends MeterFunction>) functionClass
            );
        }
    }
}
 
Example 15
Source File: MetricsHolder.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public static void init() throws IOException {
    ClassPath classpath = ClassPath.from(MetricsHolder.class.getClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classpath.getTopLevelClassesRecursive("org.apache.skywalking");
    for (ClassPath.ClassInfo classInfo : classes) {
        Class<?> aClass = classInfo.load();

        if (aClass.isAnnotationPresent(MetricsFunction.class)) {
            MetricsFunction metricsFunction = aClass.getAnnotation(MetricsFunction.class);
            REGISTER.put(
                metricsFunction.functionName(),
                (Class<? extends Metrics>) aClass
            );
        }
    }
}
 
Example 16
Source File: ClasspathWorkflowRepository.java    From copper-engine with Apache License 2.0 5 votes vote down vote up
static Set<Class<?>> findWorkflowClasses(final List<String> wfPackages, final ClassLoader cl) throws Exception {
    final ClassPath cp = ClassPath.from(cl);
    final Set<Class<?>> set = new HashSet<Class<?>>();
    for (String wfPackage : wfPackages) {
        final ImmutableSet<com.google.common.reflect.ClassPath.ClassInfo> x = cp.getTopLevelClassesRecursive(wfPackage);
        for (com.google.common.reflect.ClassPath.ClassInfo ci : x) {
            final Class<?> c = cl.loadClass(ci.getName());
            set.add(c);
            set.addAll(Arrays.asList(c.getDeclaredClasses()));
            loadAnonymousInnerClasses(cl, set, c);
        }
    }
    return set;
}
 
Example 17
Source File: ProductDimensionsTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Test that verifies that {@link ProductDimensions} has a {@code createX} method for every
 * subclass {@code X} of {@link ProductDimension}.
 */
@SuppressWarnings("unchecked")
@Test
public void testCreateMethodExistsForEveryDimensionSubclass() throws Exception {
  String basePackageNameForVersion = ProductDimension.class.getPackage().getName()
      .substring(0, ProductDimension.class.getPackage().getName().length() - ".cm".length());

  ClassPath classPath = ClassPath.from(ProductDimension.class.getClassLoader());
  Set<?> dimensionSubclasses =
      classPath
          .getTopLevelClassesRecursive(basePackageNameForVersion)
          .stream()
          .map(ClassInfo::load)
          .filter(
              classInfoClass ->
                  ProductDimension.class.isAssignableFrom(classInfoClass)
                      && ProductDimension.class != classInfoClass)
          .collect(Collectors.toSet());

  Map<Class<? extends ProductDimension>, Method> factoryMethodsMap =
      getAllProductDimensionFactoryMethods();

  dimensionSubclasses
      .stream()
      .filter(dimensionSubclass -> !DIMENSION_TYPES_TO_IGNORE.contains(dimensionSubclass))
      .forEach(
          dimensionSubclass ->
              assertThat(
                  "No factory method exists for subclass "
                      + dimensionSubclass
                      + " of ProductDimension",
                  (Class<? extends ProductDimension>) dimensionSubclass,
                  Matchers.isIn(factoryMethodsMap.keySet())));
}
 
Example 18
Source File: TestRunner.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all tests to run for the TCK.
 *
 * @return A list of test classes to run.
 */
List<Class<?>> getAllTestClasses() {
  try {
    ClassPath cp = ClassPath.from(getClass().getClassLoader());
    ImmutableSet<ClassInfo> classes =
        cp.getTopLevelClasses("org.apache.calcite.avatica.tck.tests");

    List<Class<?>> testClasses = new ArrayList<>(classes.size());
    for (ClassInfo classInfo : classes) {
      if (classInfo.getSimpleName().equals("package-info")) {
        continue;
      }
      Class<?> clz = Class.forName(classInfo.getName());
      if (Modifier.isAbstract(clz.getModifiers())) {
        // Ignore abstract classes
        continue;
      }
      testClasses.add(clz);
    }

    return testClasses;
  } catch (Exception e) {
    LOG.error("Failed to instantiate test classes", e);
    Unsafe.systemExit(TestRunnerExitCodes.TEST_CASE_INSTANTIATION.ordinal());
    // Unreachable..
    return null;
  }
}
 
Example 19
Source File: OrienteerWebApplication.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
private void mountOrUnmountPackage(String packageName, ClassLoader classLoader, boolean mount) {
	ClassPath classPath;
	try {
		classPath = ClassPath.from(classLoader);
	} catch (IOException e) {
		throw new WicketRuntimeException("Can't scan classpath", e);
	}
	
	for(ClassInfo classInfo : classPath.getTopLevelClassesRecursive(packageName)) {
		Class<?> clazz = classInfo.load();
		MountPath mountPath = clazz.getAnnotation(MountPath.class);
		if(mountPath!=null) {
			if(IRequestablePage.class.isAssignableFrom(clazz)) { 
				Class<? extends IRequestablePage> pageClass = (Class<? extends IRequestablePage>) clazz;
				forEachOnMountPath(mountPath, path -> {
									if(mount) {
										if ("/".equals(path)) {
											mount(new HomePageMapper(pageClass));
										}
										mount(new MountedMapper(path, pageClass));
									} else {
										unmount(path);
									}
								});
			} else if(IResource.class.isAssignableFrom(clazz)) {
				if(mount) {
					String resourceKey = clazz.getName();
					getSharedResources().add(resourceKey, (IResource) getServiceInstance(clazz));
					SharedResourceReference reference = new SharedResourceReference(resourceKey);
					forEachOnMountPath(mountPath, path -> mountResource(path, reference));
				} else {
					forEachOnMountPath(mountPath, this::unmount);
				}
			} else {
				throw new WicketRuntimeException("@"+MountPath.class.getSimpleName()+" should be only on pages or resources");
			}
		}
	}
}
 
Example 20
Source File: InterfaceToImpl.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
/**
 * Return the implementing class.
 *
 * @param implDir
 *          - package name where to search
 * @param interface2check
 *          - class name of the required interface
 * @return implementing class/es
 * @throws IOException
 *           - if the attempt to read class path resources (jar files or directories) failed.
 * @throws ClassNotFoundException
 *           - if no class in implDir implements the interface
 */
public static ArrayList<Class<?>> convert2Impl(String implDir, String interface2check, boolean allowMultiple) throws IOException, ClassNotFoundException {
  ArrayList<Class<?>> impl = new ArrayList<>();
  ArrayList<Class<?>> cachedClazz = clazzCache.get(implDir, interface2check);
  if(cachedClazz != null){
    log.debug("returned " +cachedClazz.size()+" class/es from cache");
    return cachedClazz;
  }
  ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
  ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(implDir);
  Class<?> userImpl = null;
  /** iterate over all classes in the org.folio.rest.impl package to find the one implementing the
   * requested interface */
  for (ClassPath.ClassInfo info : classes) {
    if(userImpl != null && impl.size() == 1){
      /** we found a user impl that matches the interface2check, we are done, since we can only have one of these */
      break;
    }
    try {
      Class<?> clazz = Class.forName(info.getName());
      if(!clazz.getSuperclass().getName().equals("java.lang.Object") && clazz.getSuperclass().getInterfaces().length > 0){ //NOSONAR
        /** user defined class which overrides one of the out of the box RMB implementations
         * set the clazz to the interface. find the correct implementation below */
        userImpl = clazz;
        clazz = clazz.getSuperclass();
      }
      /** loop over all interfaces the class implements */
      for (Class<?> anInterface : clazz.getInterfaces()) {
        if (!anInterface.getName().equals(interface2check)) { //NOSONAR
          /**if userImpl != null here then a user impl exists but does not match the requested interface, so set to null*/
          userImpl = null;
          /** class doesnt implement the requested package, continue to check if it implements other packages */
          continue;
        }
        if(userImpl != null){
          /** we are here if we found a user impl (extends) of an RMB existing interface implementation
           *  load the user implementation and remove previous impl if it was added in previous loop iterations
           * there can only be one impl of an override, but we dont know the order we will get from the classloader
           * will the default RMB impl be passed in here or the user implementation - so once we hit a class whose
           * super class extends a generated interface - clear out the previous impl if any from the array and add
           * the user's impl - once found we are done */
          impl.clear();
          impl.add(userImpl);
          break;
        }
        else if (!allowMultiple && impl.size() > 0) {
          throw new RuntimeException("Duplicate implementation of " + interface2check + " in " + implDir + ": " + impl.get(0).getName() + ", "
              + clazz.getName());
        }
        else{
          /** return the class found that implements the requested package */
          impl.add(clazz);
        }
      }
    } catch (ClassNotFoundException e) {
      log.error(e.getMessage(), e);
    }
  }
  if (impl.isEmpty()) {
    throw new ClassNotFoundException("Implementation of " + interface2check + " not found in " + implDir);
  }
  clazzCache.put(implDir, interface2check, impl);
  return impl;
}