com.google.common.reflect.ClassPath Java Examples

The following examples show how to use com.google.common.reflect.ClassPath. 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: ClassPathResourceTest.java    From wisdom with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    File file = new File("src/test/resources/foo.txt");
    ClassPath.ResourceInfo info = getResourceForName("foo.txt");
    assertThat(info).isNotNull();
    ClassPathResource resource = new ClassPathResource(info);
    assertThat(resource.getExtra()).isNullOrEmpty();
    assertThat(resource.lastModified()).isGreaterThanOrEqualTo(file.lastModified());
    assertThat(resource.size()).isEqualTo(file.length());

    InputStream stream = resource.openInputStream();
    String content = IOUtils.toString(stream);
    IOUtils.closeQuietly(stream);

    assertThat(content).isEqualTo(FileUtils.readFileToString(file));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    resource.write(bos);
    content = bos.toString();
    IOUtils.closeQuietly(bos);

    assertThat(content).isEqualTo(FileUtils.readFileToString(file));

}
 
Example #2
Source File: ValidatorsTest.java    From bundletool with 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 #3
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 #4
Source File: SchemaGenerator.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private static void fetchDataSources(String[] args) {
    try {
        final Set<ClassPath.ClassInfo> classInfos = ClassPathHelper.getPackageClasses(Thread.currentThread().getContextClassLoader(), Arrays.asList(args));
        System.out.println("Classes in ClassLoader: " + classInfos.size());
        for (ClassPath.ClassInfo classInfo : classInfos) {
            Class clazz = Class.forName(classInfo.getName());
            if (Modifier.isAbstract(clazz.getModifiers())) {
                continue;
            }

            if (DataSource.class.isAssignableFrom(clazz)) {
                datasources.put(PoseidonLegoSet.getBlockId(clazz).get(), clazz);
            }
        }
    } catch (Exception e) {
        throw new UnsupportedOperationException(e);
    }

}
 
Example #5
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 #6
Source File: Context.java    From NoraUi with 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
Source File: Yaml.java    From java with Apache License 2.0 6 votes vote down vote up
private static void initModelMap() throws IOException {
  initApiGroupMap();
  initApiVersionList();

  ClassPath cp = ClassPath.from(Yaml.class.getClassLoader());
  Set<ClassPath.ClassInfo> allClasses =
      cp.getTopLevelClasses("io.kubernetes.client.openapi.models");

  for (ClassPath.ClassInfo clazz : allClasses) {
    String modelName = "";
    Pair<String, String> nameParts = getApiGroup(clazz.getSimpleName());
    modelName += nameParts.getLeft() == null ? "" : nameParts.getLeft() + "/";

    nameParts = getApiVersion(nameParts.getRight());
    modelName += nameParts.getLeft() == null ? "" : nameParts.getLeft() + "/";
    modelName += nameParts.getRight();

    classes.put(modelName, clazz.load());
  }
}
 
Example #8
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 #9
Source File: GuavaCollectionBuildersTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@Test
public void testImmutableBuilders() throws Exception {
  ClassPath classPath = ClassPath.from(getClass().getClassLoader());
  ImmutableSet<ClassPath.ClassInfo> classes = classPath.getAllClasses();
  int checked = 0;
  for (ClassPath.ClassInfo classInfo : classes) {
    if (classInfo.getPackageName().equals("com.google.common.collect")
        && classInfo.getSimpleName().startsWith("Immutable")
        && !NON_BUILDABLE_COLLECTIONS.contains(classInfo.getSimpleName())) {
      Class<?> c = Class.forName(classInfo.getName());
      if (Modifier.isPublic(c.getModifiers())) {
        checked++;
        checkImmutableClass(c);
      }
    }
  }
  expect.that(checked).isGreaterThan(10);
}
 
Example #10
Source File: ConstantUtil.java    From canon-sdk-java with MIT License 6 votes vote down vote up
/**
 * Kept for test purposes (might move it to test package).
 * <br>
 * ClassPath class does not support jar in jar -> spring boot jar layout does not work for example
 *
 * @return native enum classes that contains native constant values
 * @throws IllegalStateException On IO error
 * @deprecated better to use the manual alternative as this method does not support Spring boot jar packaging
 */
@SuppressWarnings("unchecked")
@Deprecated
static Set<? extends Class<? extends NativeEnum>> getNativeEnumClasses() throws IllegalStateException {
    try {
        final ImmutableSet<ClassPath.ClassInfo> allClasses = ClassPath.from(EdsAccess.class.getClassLoader()).getTopLevelClasses(NATIVE_ENUM_PACKAGE);
        final Set<? extends Class<?>> classes = allClasses.asList().stream()
            .filter(info -> !info.getSimpleName().endsWith("Test"))
            .filter(info -> !info.getSimpleName().equalsIgnoreCase(NativeEnum.class.getSimpleName()))
            .filter(info -> !info.getSimpleName().equalsIgnoreCase(NativeErrorEnum.class.getSimpleName()))
            .map(ClassPath.ClassInfo::load)
            .filter(NativeEnum.class::isAssignableFrom)
            .collect(Collectors.toSet());
        return (Set<? extends Class<? extends NativeEnum>>) classes;
    } catch (IOException e) {
        throw new IllegalStateException("Failed to read native enum classes", e);
    }
}
 
Example #11
Source File: PoseidonLegoSet.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private void bucketize(ClassPath.ClassInfo aClass, List<Class<ServiceClient>> serviceClientClasses, List<Class<Filter>> filterClasses, Set<String> singletonDataSources) {
    try {
        Class klass = Class.forName(aClass.getName());
        if (!isAbstract(klass)) {
            if (DataSource.class.isAssignableFrom(klass)) {
                processDataSource(klass, singletonDataSources);
            } else if (ServiceClient.class.isAssignableFrom(klass)) {
                serviceClientClasses.add(klass);
            } else if (Filter.class.isAssignableFrom(klass)) {
                filterClasses.add(klass);
            } else if (Mapper.class.isAssignableFrom(klass)) {
                Mapper mapper = (Mapper) klass.newInstance();
                mappers.put(getBlockId(klass).orElseThrow(MissingInformationException::new), mapper);
            }
        }
    } catch (Throwable t) {
        logger.error("Unable to instantiate " + aClass.getName(), t);
        throw new PoseidonFailureException("Unable to instantiate " + aClass.getName(), t);
    }
}
 
Example #12
Source File: CommandClassUtil.java    From canon-sdk-java with MIT License 6 votes vote down vote up
private static Set<? extends Class<? extends DecoratorCommand>> getDecoratorCommandClassesInternal() {
        try {
            final ImmutableSet<ClassPath.ClassInfo> allClasses = ClassPath.from(AbstractDecoratorCommand.class.getClassLoader()).getTopLevelClasses(DECORATOR_COMMAND_PACKAGE);

            final Set<? extends Class<?>> classes = allClasses.asList().stream()
                .filter(info -> !info.getSimpleName().endsWith("Test"))
//                .filter(info -> info.getSimpleName().endsWith("Command")) do not put as not all commands end with that
                .map(ClassPath.ClassInfo::load)
                .filter(DecoratorCommand.class::isAssignableFrom)
                .filter(aClass -> !aClass.isInterface())
                .collect(ImmutableSet.toImmutableSet());
            return (Set<? extends Class<? extends DecoratorCommand>>) classes;
        } catch (IOException e) {
            throw new IllegalStateException("Failed to read decorator command classes", e);
        }
    }
 
Example #13
Source File: CommandClassUtil.java    From canon-sdk-java with MIT License 6 votes vote down vote up
private static Set<? extends Class<? extends CanonCommand>> getCommandClassesInternal() {
        try {
            final ImmutableSet<ClassPath.ClassInfo> allClasses = ClassPath.from(AbstractCanonCommand.class.getClassLoader()).getTopLevelClasses(COMMAND_PACKAGE);

            final Set<? extends Class<?>> classes = allClasses.asList().stream()
                .filter(info -> !info.getSimpleName().endsWith("Test"))
//                .filter(info -> info.getSimpleName().endsWith("Command")) do not put as not all commands end with that
                .map(ClassPath.ClassInfo::load)
                .filter(CanonCommand.class::isAssignableFrom)
                .filter(aClass -> !aClass.isInterface())
                .collect(ImmutableSet.toImmutableSet());
            return (Set<? extends Class<? extends CanonCommand>>) classes;
        } catch (IOException e) {
            throw new IllegalStateException("Failed to read command classes", e);
        }
    }
 
Example #14
Source File: PojoTest.java    From commerce-cif-api with 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 #15
Source File: NoraUiLoggingModule.java    From NoraUi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * {@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 #16
Source File: JsonIgnorePropertiesAnnotationTest.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Test
@Description(
        "This test verifies that all model classes within the 'org.eclipse.hawkbit.ddi.json.model' package are annotated with '@JsonIgnoreProperties(ignoreUnknown = true)'")
public void shouldCheckAnnotationsForAllModelClasses() throws IOException {
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String packageName = this.getClass().getPackage().getName();

    ImmutableSet<ClassPath.ClassInfo> topLevelClasses = ClassPath.from(loader).getTopLevelClasses(packageName);
    for (ClassPath.ClassInfo classInfo : topLevelClasses) {
        Class<?> modelClass = classInfo.load();
        if (modelClass.getSimpleName().contains("Test") || modelClass.isEnum()) {
            continue;
        }
        JsonIgnoreProperties annotation = modelClass.getAnnotation(JsonIgnoreProperties.class);
        assertThat(annotation).isNotNull();
        assertThat(annotation.ignoreUnknown()).isTrue();
    }
}
 
Example #17
Source File: DocumentationGenerator.java    From cukes with Apache License 2.0 6 votes vote down vote up
private static Map<CukesComponent, Multimap<StepType, StepDefinition>> collectSteps() throws IOException, ClassNotFoundException {
    Map<CukesComponent, Multimap<StepType, StepDefinition>> steps = createStepsStubs();
    ClassPath classPath = ClassPath.from(DocumentationGenerator.class.getClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClassesRecursive("lv.ctco.cukes");
    for (ClassPath.ClassInfo classInfo : classes) {
        String className = classInfo.getName();
        Class<?> aClass = Class.forName(className);
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            StepType type = StepType.getTypeForMethod(method);
            if (type != null) {
                CukesComponent component = CukesComponent.findByClassName(className);
                steps.get(component).put(type, new StepDefinition(type.getPattern(method), type.getDescription(method)));
            }
        }
    }
    return steps;
}
 
Example #18
Source File: Classpath.java    From bazel-buildfarm with 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 #19
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 #20
Source File: ReplaceManager.java    From ScoreboardStats with 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 #21
Source File: AllureMain.java    From allure1 with Apache License 2.0 6 votes vote down vote up
/**
 * Unpack report face to given directory.
 *
 * @param outputDirectory the output directory to unpack face.
 * @throws IOException if any occurs.
 */
private static void unpackFace(File outputDirectory) throws IOException {
    ClassLoader loader = AllureMain.class.getClassLoader();
    for (ClassPath.ResourceInfo info : ClassPath.from(loader).getResources()) {
        Matcher matcher = REPORT_RESOURCE_PATTERN.matcher(info.getResourceName());
        if (matcher.find()) {
            String resourcePath = matcher.group(1);
            File dest = new File(outputDirectory, resourcePath);
            Files.createParentDirs(dest);
            try (FileOutputStream output = new FileOutputStream(dest);
                 InputStream input = info.url().openStream()) {
                IOUtils.copy(input, output);
                LOGGER.debug("{} successfully copied.", resourcePath);
            }
        }
    }
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
Source File: ChannelAndServerBuilderTest.java    From grpc-nebula-java with Apache License 2.0 6 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<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 #27
Source File: Classpath.java    From bazel with 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 #28
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 #29
Source File: SchemaGenerator.java    From core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Utility method used to fetch Class list based on a package name.
 * 
 * @param packageName
 *            (should be the package containing your annotated beans.
 */
@SuppressWarnings("rawtypes")
private List<Class> getClasses(String packageName) throws Exception {
    
    logger.debug("Start: Classes in "+ packageName);
    List<Class> classes = new ArrayList<Class>();
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();

       for (final ClassPath.ClassInfo info : ClassPath.from(loader).getTopLevelClasses()) 
       {
           if (info.getName().startsWith(packageName)) 
           {
               final Class<?> clazz = info.load();
               logger.debug(info.getName());
               classes.add(clazz);
           } 
       }
       logger.debug("End: Classes in "+ packageName);
   
       
	return classes;
}
 
Example #30
Source File: ASTClassInfoPrinter.java    From j2objc with 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", "");
}