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

The following examples show how to use com.google.common.reflect.ClassPath.ClassInfo. 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: PerfUtil.java    From hugegraph-common with 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 #2
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 #3
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", "");
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: ReflectionUtilTest.java    From hugegraph-common with 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 #15
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 #16
Source File: SignatureCollector.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a stream of Skylark function signatures (identified by {@link SkylarkCallable}
 * annotation found in the current classpath.
 *
 * @param classInfoPredicate predicate to use in order to filter out classes that should not be
 *     loaded. It's best to make it as precise as possible to avoid expensive loading - checking
 *     for class name and package is ideal.
 */
public static Stream<SkylarkCallable> getSkylarkCallables(Predicate<ClassInfo> classInfoPredicate)
    throws IOException {
  return ClassPath.from(ClassPath.class.getClassLoader()).getAllClasses().stream()
      .filter(classInfoPredicate)
      .map(ClassInfo::load)
      .flatMap(clazz -> Arrays.stream(clazz.getMethods()))
      .map(field -> field.getAnnotation(SkylarkCallable.class))
      .filter(Objects::nonNull);
}
 
Example #17
Source File: ChannelAndServerBuilderTest.java    From grpc-java with 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;
}
 
Example #18
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 #19
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 #20
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 #21
Source File: CodecScanner.java    From bazel with 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 #22
Source File: MainApplication.java    From SciGraph with 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 #23
Source File: TypeDataContainer.java    From orcas with 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 #24
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 #25
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 #26
Source File: ScriptRunner.java    From stendhal with 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 #27
Source File: ListRaids.java    From stendhal with 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 #28
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 #29
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 #30
Source File: Standalone.java    From scava with 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);
	}
}