Java Code Examples for com.google.common.reflect.ClassPath.ClassInfo

The following examples show how to use com.google.common.reflect.ClassPath.ClassInfo. These examples are extracted from open source projects. 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
/**
 * Javadoc.
 */
@Parameters(name = "class={0}")
public static Collection<Object[]> params() throws Exception {
  ClassLoader loader = ChannelAndServerBuilderTest.class.getClassLoader();
  Collection<ClassInfo> classInfos =
      ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc");
  // Java 9 doesn't expose the URLClassLoader, which breaks searching through the classpath
  if (classInfos.isEmpty()) {
    return new ArrayList<Object[]>();
  }
  List<Object[]> classes = new ArrayList<Object[]>();
  for (ClassInfo classInfo : classInfos) {
    Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader);
    if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) {
      classes.add(new Object[]{clazz});
    } else if (ManagedChannelBuilder.class.isAssignableFrom(clazz)
        && clazz != ManagedChannelBuilder.class) {
      classes.add(new Object[]{clazz});
    }
  }
  Truth.assertWithMessage("Unable to find any builder classes").that(classes).isNotEmpty();
  return classes;
}
 
Example 2
Source Project: hugegraph-common   Source File: PerfUtil.java    License: Apache License 2.0 6 votes vote down vote up
public void profilePackage(String... packages)
                           throws NotFoundException, IOException,
                           ClassNotFoundException, CannotCompileException {
    Set<String> loadedClasses = new HashSet<>();

    Iterator<ClassInfo> classes = ReflectionUtil.classes(packages);
    while (classes.hasNext()) {
        String cls = classes.next().getName();
        // super class first
        for (String s : ReflectionUtil.superClasses(cls)) {
            if (!loadedClasses.contains(s)) {
                profileClass(s);
                loadedClasses.add(s);
            }
        }
        // self class
        if (!loadedClasses.contains(cls)) {
            profileClass(cls);
            loadedClasses.add(cls);
        }
    }
}
 
Example 3
Source Project: hugegraph-common   Source File: ReflectionUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClasses() throws IOException {
    @SuppressWarnings("unchecked")
    List<ClassInfo> classes = IteratorUtils.toList(ReflectionUtil.classes(
                              "com.baidu.hugegraph.util"));
    Assert.assertEquals(16, classes.size());
    classes.sort((c1, c2) -> c1.getName().compareTo(c2.getName()));
    Assert.assertEquals("com.baidu.hugegraph.util.Bytes",
                        classes.get(0).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.CheckSocket",
                        classes.get(1).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.CollectionUtil",
                        classes.get(2).getName());
    Assert.assertEquals("com.baidu.hugegraph.util.VersionUtil",
                        classes.get(15).getName());
}
 
Example 4
Source Project: commerce-cif-api   Source File: PojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSettersAndGetters() throws Exception {
    Set<ClassInfo> classes = ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive(MODEL_PACKAGE);

    classes.stream()
            .map(c -> c.load())
            .filter( clazz -> !(clazz.getSimpleName().contains("Test") || clazz.isEnum() || Modifier.isAbstract(clazz.getModifiers())))
            .forEach(clazz -> {
                try {
                    LOGGER.debug("Checking setter/getter for " + clazz.getName());
                    testSettersAndGettersFor(clazz);
                } catch (Exception e) {
                   LOGGER.error(e.getMessage(), e);
                }
            });
}
 
Example 5
Source Project: bundletool   Source File: ValidatorsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void eachSubValidatorIsRegistered() throws Exception {
  // Load sub-classes of SubValidator that live within the same package as top-level classes.
  ImmutableSet<Class<?>> existingSubValidators =
      ClassPath.from(SubValidator.class.getClassLoader())
          .getTopLevelClasses(Reflection.getPackageName(SubValidator.class))
          .stream()
          .map(ClassInfo::load)
          .filter(clazz -> isConcreteSubValidator(clazz))
          .collect(toImmutableSet());

  ImmutableSet<Class<?>> registeredSubValidators =
      ImmutableSet.<Class<?>>builder()
          .addAll(toClasses(AppBundleValidator.DEFAULT_BUNDLE_FILE_SUB_VALIDATORS))
          .addAll(toClasses(AppBundleValidator.DEFAULT_BUNDLE_SUB_VALIDATORS))
          .addAll(toClasses(BundleModulesValidator.MODULE_FILE_SUB_VALIDATORS))
          .addAll(toClasses(BundleModulesValidator.MODULES_SUB_VALIDATORS))
          .build();

  assertThat(existingSubValidators).containsExactlyElementsIn(registeredSubValidators);
}
 
Example 6
Source Project: NoraUi   Source File: Context.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * statisticsProcessor retrieves specific information from the robot to return it to users statistic feature.
 * 
 * @param loader
 *            is class loader.
 * @param packageName
 *            read for users statistic feature.
 * @return it to users statistic feature.
 */
protected Statistics statisticsProcessor(ClassLoader loader, String packageName) {
    Statistics stat = new Statistics();
    MavenXpp3Reader reader = new MavenXpp3Reader();
    org.apache.maven.model.Model model;
    try {
        model = reader.read(new FileReader("pom.xml"));
        stat.setNorauiVersion(model.getProperties().getProperty("noraui.version"));
        stat.setName(model.getName());
        stat.setGroupId(model.getGroupId());
        stat.setArtifactId(model.getArtifactId());
        stat.setVersion(model.getVersion());
    } catch (IOException | XmlPullParserException e) {
        log.trace("noraui.version not found.");
    }
    stat.setApplications(applications.entrySet().stream().filter(e -> e.getValue().getHomeUrl() != null).collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getHomeUrl(), (a, b) -> b)));
    try {
        Map<String, String> code = ClassPath.from(loader).getTopLevelClassesRecursive(packageName).stream().collect(Collectors.toMap(ClassInfo::getName, c -> read(c.getName()), (a, b) -> b));
        stat.setCucumberMethods(code);
    } catch (IOException e1) {
        log.trace("Cucumber Methods not found.");
    }
    return stat;
}
 
Example 7
/**
 * {@inheritDoc}
 * This configure method does not use Guice binding by far as it only injects static loggers in classes annotated with @see com.github.noraui.log.annotation.Loggable
 */
@Override
public void configure(Binder binder) {
    LOGGER.debug("NORAUI logging listeners binding");
    // @formatter:off
    try {
        ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(packageName).stream()
        .map(ClassInfo::load)
        .filter(c -> !Modifier.isInterface(c.getModifiers()))
        .filter(c -> c.isAnnotationPresent(Loggable.class))
        .forEach(this::injectSlf4JLogger);
    } catch (IOException e) {
        LOGGER.error("NoraUiLoggingModule.configure(Binder: {})", binder, e);

    }
    // @formatter:on
}
 
Example 8
Source Project: bazel-buildfarm   Source File: Classpath.java    License: Apache License 2.0 6 votes vote down vote up
/** Finds all classes that live in or below the given package. */
public static Set<Class<?>> findClasses(String packageName) throws ClassPathException {
  Set<Class<?>> result = new LinkedHashSet<>();
  String packagePrefix = (packageName + '.').replace('/', '.');
  try {
    for (ClassInfo ci : ClassPath.from(Classpath.class.getClassLoader()).getAllClasses()) {
      if (ci.getName().startsWith(packagePrefix)) {
        try {
          result.add(ci.load());
        } catch (UnsatisfiedLinkError | NoClassDefFoundError unused) {
          // Ignore: we're most likely running on a different platform.
        }
      }
    }
  } catch (IOException e) {
    throw new ClassPathException(e.getMessage());
  }
  return result;
}
 
Example 9
Source Project: nomulus   Source File: ToolsTest.java    License: 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 10
Source Project: j2objc   Source File: ASTClassInfoPrinter.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String... args) {
  // Clear saved state for new calls.
  tree = TreeMultimap.create();
  astLookup = Sets.newHashSet();
  ClassPath cp = null;
  try {
    cp = ClassPath.from(ClassLoader.getSystemClassLoader());
  } catch (IOException e) {
    ErrorUtil.error(e.getMessage());
    System.exit(1);
  }
  for (ClassInfo c : cp.getTopLevelClasses("org.eclipse.jdt.core.dom")){
    astLookup.add(c.getSimpleName());
  }
  for (ClassInfo ci : cp.getTopLevelClasses("com.google.devtools.j2objc.ast")) {
    // Ignore package-info and JUnit tests.
    if (ci.getSimpleName().equals("package-info") || TestCase.class.isAssignableFrom(ci.load())) {
      continue;
    }
    walkSuperclassHierarchy(ci.load());
  }
  // Print hierarchy descending from Object.
  printClassHierarchy("Object", "");
}
 
Example 11
Source Project: bazel   Source File: Classpath.java    License: Apache License 2.0 6 votes vote down vote up
/** Finds all classes that live in or below the given package. */
public static Set<Class<?>> findClasses(String packageName) throws ClassPathException {
  Set<Class<?>> result = new LinkedHashSet<>();
  String packagePrefix = (packageName + '.').replace('/', '.');
  try {
    for (ClassInfo ci : ClassPath.from(Classpath.class.getClassLoader()).getAllClasses()) {
      if (ci.getName().startsWith(packagePrefix)) {
        try {
          result.add(ci.load());
        } catch (UnsatisfiedLinkError | NoClassDefFoundError unused) {
          // Ignore: we're most likely running on a different platform.
        }
      }
    }
  } catch (IOException e) {
    throw new ClassPathException(e.getMessage());
  }
  return result;
}
 
Example 12
Source Project: Orienteer   Source File: DefaultWidgetTypesRegistry.java    License: 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 13
Source Project: cloudbreak   Source File: Junit4Scanner.java    License: 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 14
Source Project: minnal   Source File: AbstractScanner.java    License: 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 15
Source Project: ScoreboardStats   Source File: ReplaceManager.java    License: MIT License 6 votes vote down vote up
private void addDefaultReplacers() {
    Set<String> defaultReplacers = Sets.newHashSet();
    try {
        defaultReplacers = ClassPath.from(getClass().getClassLoader())
                .getTopLevelClasses("com.github.games647.scoreboardstats.defaults")
                .stream()
                .map(ClassInfo::load)
                .filter(DefaultReplacers.class::isAssignableFrom)
                .map(clazz -> (Class<DefaultReplacers<?>>) clazz)
                .filter(this::registerDefault)
                .map(Class::getSimpleName)
                .collect(Collectors.toSet());
    } catch (IOException ioEx) {
        logger.error("Failed to register replacers", ioEx);
    }

    logger.info("Registered default replacers: {}", defaultReplacers);
}
 
Example 16
Source Project: hugegraph-common   Source File: ReflectionUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Iterator<ClassInfo> classes(String... packages)
                                          throws IOException {
    ClassPath path = ClassPath.from(ReflectionUtil.class.getClassLoader());
    ExtendableIterator<ClassInfo> results = new ExtendableIterator<>();
    for (String p : packages) {
        results.extend(path.getTopLevelClassesRecursive(p).iterator());
    }
    return results;
}
 
Example 17
Source Project: calcite-avatica   Source File: TestRunner.java    License: 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 18
Source Project: scava   Source File: Standalone.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public void doCopyRuntime() throws Exception {
	
	// Get the output folder for generated code to copy runtime to
	final EmfModel model = getGenerator().getModel();
	final Optional<String> genOutputFolder = model.getAllOfType("Language").stream()
		.map(l -> (Language) l)
		.filter(l -> l.getName().equalsIgnoreCase("java"))
		.map(l -> l.getGenOutputFolder())
		.findFirst();
	
	// Return if folder is not specified
	if (!genOutputFolder.isPresent()) return;
	
	// Retrieve location of runtime Java source and pre-process final output paths
	final ImmutableSet<ClassInfo> classInfo = ClassPath.from(Standalone.class.getClassLoader())
			.getTopLevelClassesRecursive("org.eclipse.scava.crossflow.runtime");
	final Map<String, File> javaFiles = classInfo.stream()
		.map(ci -> ci.url().toString())
		.map(url -> url.replaceFirst("/bin/", "/src/"))
		.map(url -> url.replaceFirst("\\.class", ".java"))
		.map(url -> URI.create(url))
		.map(uri -> new File(uri))
		.collect(Collectors.toMap(
				f -> {
					String absPath = f.getAbsolutePath();
					return absPath.substring((absPath.lastIndexOf("/src/") + 5));
				}, 
				t -> t));
	
	// Do the copying
	for (Map.Entry<String, File> e : javaFiles.entrySet()) {
		File newFile = new File(projectLoc + "/" + genOutputFolder.get() + "/" + e.getKey());
		FileUtils.copyFile(e.getValue(), newFile);
	}
}
 
Example 19
Source Project: runelite   Source File: PluginManager.java    License: 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 20
Source Project: runelite   Source File: PluginManagerTest.java    License: 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 21
Source Project: stendhal   Source File: ListRaids.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fetch classes of available scripts.
 *
 * @param pckgname the package name of scripts
 * @return list of script classes
 * @throws ClassNotFoundException if getting the class loader or reading the
 * 	script resources fail
 */
private static ArrayList<Class<?>> getClasses(final String packageName) throws ClassNotFoundException {
	final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
	try {
		ClassLoader classLoader = ListRaids.class.getClassLoader();
		ImmutableSet<ClassInfo> infos = ClassPath.from(classLoader).getTopLevelClasses(packageName);
		for (ClassInfo info : infos) {
			classes.add(info.load());
		}
		return classes;
	} catch (IOException e) {
		throw new ClassNotFoundException("failed to list classes");
	}
}
 
Example 22
Source Project: stendhal   Source File: ScriptRunner.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fetch classes of available scripts.
 *
 * @param pckgname the package name of scripts
 * @return list of script classes
 * @throws ClassNotFoundException if getting the class loader or reading the
 * 	script resources fail
 */
private static ArrayList<Class<?>> getClasses(final String packageName) throws ClassNotFoundException {
	final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
	try {
		ClassLoader classLoader = ScriptRunner.class.getClassLoader();
		ImmutableSet<ClassInfo> infos = ClassPath.from(classLoader).getTopLevelClasses(packageName);
		for (ClassInfo info : infos) {
			classes.add(info.load());
		}
		return classes;
	} catch (IOException e) {
		throw new ClassNotFoundException("failed to list classes");
	}
}
 
Example 23
Source Project: Oceanus   Source File: Analyzers.java    License: 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 24
Source Project: opc-ua-stack   Source File: DelegateRegistry.java    License: 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 25
Source Project: orcas   Source File: TypeDataContainer.java    License: Apache License 2.0 5 votes vote down vote up
private List<Class> _getClasses( Package pPackage, List<Class> pUsedInterfaces )
{
  try
  {
    ClassLoader lClassLoader = Thread.currentThread().getContextClassLoader();
    ImmutableSet<ClassInfo> lClasseInfosInPackage = ClassPath.from( lClassLoader ).getTopLevelClasses( pPackage.getName() );
    List<Class> lReturn = new ArrayList<Class>();

    for(ClassInfo lClassInfo : lClasseInfosInPackage)
    {
      Class lClass = Class.forName( lClassInfo.getName() );
      if( lClass.isInterface() )
      {
        boolean lUse = false;

        for( Class lInterface : lClass.getInterfaces() )
        {
          if( pUsedInterfaces.contains( lInterface ) )
          {
            lUse = true;
          }
        }

        if( lUse )
        {
          lReturn.add( lClass );
        }
      }
    }

    return lReturn;
  }
  catch( Exception e )
  {
    throw new RuntimeException();
  }
}
 
Example 26
Source Project: SciGraph   Source File: MainApplication.java    License: Apache License 2.0 5 votes vote down vote up
void addWriters(JerseyEnvironment environment) throws Exception {
  for (ClassInfo classInfo: ClassPath.from(getClass().getClassLoader()).getTopLevelClasses("io.scigraph.services.jersey.writers")) {
    if (!Modifier.isAbstract(classInfo.load().getModifiers())) {
      environment.register(factory.getInjector().getInstance(classInfo.load()));
    }
  }
}
 
Example 27
Source Project: bazel   Source File: CodecScanner.java    License: Apache License 2.0 5 votes vote down vote up
/** Return the {@link ClassInfo} objects matching {@code packagePrefix} sorted by name. */
private static Stream<ClassInfo> getClassInfos(String packagePrefix) throws IOException {
  return ClassPath.from(ClassLoader.getSystemClassLoader())
      .getResources()
      .stream()
      .filter(r -> r instanceof ClassInfo)
      .map(r -> (ClassInfo) r)
      .filter(c -> c.getPackageName().startsWith(packagePrefix))
      .sorted(Comparator.comparing(ClassInfo::getName));
}
 
Example 28
Source Project: docker-java   Source File: ModelsSerializableTest.java    License: 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 29
Source Project: Orienteer   Source File: OrienteerWebApplication.java    License: 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 30
Source Project: grpc-java   Source File: ChannelAndServerBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Javadoc.
 */
@Parameters(name = "class={0}")
public static Collection<Object[]> params() throws Exception {
  ClassLoader loader = ChannelAndServerBuilderTest.class.getClassLoader();
  Collection<ClassInfo> classInfos =
      ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc");
  // Java 9 doesn't expose the URLClassLoader, which breaks searching through the classpath
  if (classInfos.isEmpty()) {
    return new ArrayList<>();
  }
  List<Object[]> classes = new ArrayList<>();
  for (ClassInfo classInfo : classInfos) {
    String className = classInfo.getName();
    if (className.contains("io.grpc.netty.shaded.io.netty")) {
      continue;
    }
    Class<?> clazz = Class.forName(className, false /*initialize*/, loader);
    if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) {
      classes.add(new Object[]{clazz});
    } else if (ManagedChannelBuilder.class.isAssignableFrom(clazz)
        && clazz != ManagedChannelBuilder.class) {
      classes.add(new Object[]{clazz});
    }
  }
  Truth.assertWithMessage("Unable to find any builder classes").that(classes).isNotEmpty();
  return classes;
}