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

The following examples show how to use com.google.common.reflect.ClassPath.ClassInfo#load() . 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: ToolsTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the set of all non-abstract classes implementing the {@link Command} interface (abstract
 * class and interface subtypes of Command aren't expected to have cli commands). Note that this
 * also filters out HelpCommand and ShellCommand, which have special handling in {@link
 * RegistryCli} and aren't in the command map.
 *
 * @throws IOException if reading the classpath resources fails.
 */
@SuppressWarnings("unchecked")
private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException {
  ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>();
  for (ClassInfo classInfo : ClassPath
      .from(getClass().getClassLoader())
      .getTopLevelClassesRecursive(getPackageName(getClass()))) {
    Class<?> clazz = classInfo.load();
    if (Command.class.isAssignableFrom(clazz)
        && !Modifier.isAbstract(clazz.getModifiers())
        && !Modifier.isInterface(clazz.getModifiers())
        && !clazz.equals(HelpCommand.class)
        && !clazz.equals(ShellCommand.class)) {
      builder.add((Class<? extends Command>) clazz);
    }
  }
  return builder.build();
}
 
Example 2
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 3
Source File: Junit4Scanner.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
void checkIllegalJUnit4Usage() throws IOException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    List<String> errorMessages = new ArrayList<>();
    for (ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) {
        if (info.getName().startsWith("com.sequenceiq.environment.") && info.getName().endsWith("Test")) {
            Class<?> clazz = info.load();
            checkRunWith(clazz, errorMessages);
            checkTestMethods(clazz, errorMessages);
            checkRuleFields(clazz, errorMessages);
        }
    }
    if (!errorMessages.isEmpty()) {
        throw new IllegalStateException(String.format("Found %d forbidden JUnit4-related annotations:%n%s",
                errorMessages.size(), String.join("\n", errorMessages)));
    }
}
 
Example 4
Source File: PluginManagerTest.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Before
public void before() throws IOException
{
	OkHttpClient okHttpClient = mock(OkHttpClient.class);
	when(okHttpClient.newCall(any(Request.class)))
		.thenThrow(new RuntimeException("in plugin manager test"));

	Injector injector = Guice.createInjector(Modules
		.override(new RuneLiteModule(okHttpClient, () -> null, true, false,
			RuneLite.DEFAULT_SESSION_FILE,
			RuneLite.DEFAULT_CONFIG_FILE))
		.with(BoundFieldModule.of(this)));

	RuneLite.setInjector(injector);

	// Find plugins and configs we expect to have
	pluginClasses = new HashSet<>();
	configClasses = new HashSet<>();
	Set<ClassInfo> classes = ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(PLUGIN_PACKAGE);
	for (ClassInfo classInfo : classes)
	{
		Class<?> clazz = classInfo.load();
		PluginDescriptor pluginDescriptor = clazz.getAnnotation(PluginDescriptor.class);
		if (pluginDescriptor != null)
		{
			pluginClasses.add(clazz);
			continue;
		}

		if (Config.class.isAssignableFrom(clazz))
		{
			configClasses.add(clazz);
		}
	}
}
 
Example 5
Source File: Analyzers.java    From Oceanus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void initAnalizers() {

	ImmutableSet<ClassInfo> classInfos = null;
	try {
		classInfos = ClassPath.from(Analyzers.class.getClassLoader())
				.getTopLevelClassesRecursive(
						Analyzers.class.getPackage().getName());
		for (ClassInfo classInfo : classInfos) {
			Class<?> claz = classInfo.load();
			try {

				if (NodeAnalyzer.class.isAssignableFrom(claz)
						&& !claz.isInterface()
						&& !Modifier.isAbstract(claz.getModifiers())) {
					register((NodeAnalyzer<QueryTreeNode, AnalyzeResult>) claz
							.newInstance());
				}
			} catch (Exception e) {
				// TODO LOG Auto-generated catch block
				e.printStackTrace();
				System.out.println(claz);
			}
		}
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}

}
 
Example 6
Source File: DelegateRegistry.java    From opc-ua-stack with Apache License 2.0 5 votes vote down vote up
private static void loadGeneratedClasses(ClassLoader classLoader) throws IOException, ClassNotFoundException {
    ClassPath classPath = ClassPath.from(classLoader);

    ImmutableSet<ClassInfo> structures =
            classPath.getTopLevelClasses("com.digitalpetri.opcua.stack.core.types.structured");

    ImmutableSet<ClassInfo> enumerations =
            classPath.getTopLevelClasses("com.digitalpetri.opcua.stack.core.types.enumerated");

    for (ClassInfo classInfo : Sets.union(structures, enumerations)) {
        Class<?> clazz = classInfo.load();
        Class.forName(clazz.getName(), true, classLoader);
    }
}
 
Example 7
Source File: ModelsSerializableTest.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void allModelsSerializable() throws IOException, NoSuchFieldException, IllegalAccessException {
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (ClassInfo classInfo : from(contextClassLoader).getAllClasses()) {
        if (!classInfo.getPackageName().equals("com.github.dockerjava.api.model")) {
            continue;
        }

        if (classInfo.getName().endsWith("Test")) {
            continue;
        }

        final Class<?> aClass = classInfo.load();
        if (aClass.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith("test-classes/")
                || aClass.isEnum()) {
            continue;
        }

        LOG.debug("Checking: {}", aClass);
        assertThat(aClass, typeCompatibleWith(Serializable.class));

        final Object serialVersionUID = FieldUtils.readDeclaredStaticField(aClass, "serialVersionUID", true);
        if (!excludeClasses.contains(aClass.getName())) {
            assertThat(serialVersionUID, instanceOf(Long.class));
            assertThat("Follow devel docs for " + aClass, (Long) serialVersionUID, is(1L));
        }
    }
}
 
Example 8
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");
			}
		}
	}
}