List of usage examples for com.google.common.reflect ClassPath from
public static ClassPath from(ClassLoader classloader) throws IOException
From source file:org.lightjason.agentspeak.common.CCommon.java
/** * get all classes within an Java package as action * * @param p_package full-qualified package name or empty for default package * @return action stream/*from w w w . ja v a 2 s. c o m*/ */ @SuppressWarnings("unchecked") public static Stream<IAction> actionsFromPackage(final String... p_package) { return ((p_package == null) || (p_package.length == 0) ? Stream.of(MessageFormat.format("{0}.{1}", PACKAGEROOT, "action.buildin")) : Arrays.stream(p_package)).flatMap(j -> { try { return ClassPath.from(Thread.currentThread().getContextClassLoader()) .getTopLevelClassesRecursive(j).parallelStream().map(ClassPath.ClassInfo::load) .filter(i -> !Modifier.isAbstract(i.getModifiers())) .filter(i -> !Modifier.isInterface(i.getModifiers())) .filter(i -> Modifier.isPublic(i.getModifiers())) .filter(IAction.class::isAssignableFrom).map(i -> { try { return (IAction) i.newInstance(); } catch (final IllegalAccessException | InstantiationException l_exception) { LOGGER.warning(CCommon.languagestring(CCommon.class, "actioninstantiate", i, l_exception)); return null; } }) // action can be instantiate .filter(Objects::nonNull) // check usable action name .filter(CCommon::actionusable); } catch (final IOException l_exception) { throw new UncheckedIOException(l_exception); } }); }
From source file:io.scigraph.services.MainApplication.java
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())); }// w w w . j a v a2s . co m } }
From source file:org.assertj.assertions.generator.util.ClassUtil.java
private static Set<Class<?>> getPackageClassesFromClasspathJars(String packageName, ClassLoader classLoader) throws IOException { ImmutableSet<ClassInfo> classesInfo = ClassPath.from(classLoader).getTopLevelClassesRecursive(packageName); Set<Class<?>> classesInPackage = new HashSet<Class<?>>(); for (ClassInfo classInfo : classesInfo) { classesInPackage.add(classInfo.load()); }//from www .j ava2 s .c o m Set<Class<?>> filteredClassesInPackage = new HashSet<Class<?>>(); for (Class<?> classFromJar : classesInPackage) { if (isClassCandidateToAssertionsGeneration(classFromJar)) { filteredClassesInPackage.add(classFromJar); } } return filteredClassesInPackage; }
From source file:nl.knaw.huygens.timbuctoo.config.TypeRegistry.java
private ClassPath getClassPath() { try {// www .ja v a 2s.co m return ClassPath.from(this.getClass().getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.flipkart.masquerade.util.Helper.java
public static Set<ClassPath.ClassInfo> getPackageClasses(ClassLoader classLoader, List<String> packagesToScan) throws IOException { ClassPath classpath = ClassPath.from(classLoader); Set<ClassPath.ClassInfo> classDescriptions = new HashSet<>(); for (String basePackage : packagesToScan) { classDescriptions.addAll(classpath.getTopLevelClassesRecursive(basePackage)); }/*w ww . ja v a 2 s. c o m*/ return classDescriptions; }
From source file:org.diqube.consensus.ConsensusStateMachineManager.java
@PostConstruct public void initialize() { ImmutableSet<ClassInfo> classInfos; try {/*from www . ja v a 2 s .c o m*/ classInfos = ClassPath.from(this.getClass().getClassLoader()).getTopLevelClassesRecursive(BASE_PKG); } catch (IOException e) { throw new RuntimeException("Could not inspect classpath", e); } Set<Class<?>> stateMachineInterfaces = new HashSet<>(); Set<Class<?>> stateMachineImplementations = new HashSet<>(); for (ClassInfo classInfo : classInfos) { Class<?> clazz = classInfo.load(); boolean isStateMachineInterface = clazz.isInterface() && clazz.getDeclaredAnnotation(ConsensusStateMachine.class) != null; boolean isStateMachineImplementation = !clazz.isInterface() && clazz.getDeclaredAnnotation(ConsensusStateMachineImplementation.class) != null; if (isStateMachineInterface) stateMachineInterfaces.add(clazz); else if (isStateMachineImplementation) stateMachineImplementations.add(clazz); } interfaceToImpl = new HashMap<>(); for (Class<?> implClass : stateMachineImplementations) interfaceToImpl.put(findStateMachineInterface(implClass, stateMachineInterfaces), implClass); if (interfaceToImpl.keySet().size() != stateMachineInterfaces.size()) throw new RuntimeException("There are StateMachine interfaces that do not have any implementation: " + Sets.difference(stateMachineInterfaces, interfaceToImpl.keySet())); dataClassToInterfaceAndMethodNameAndParameters = new HashMap<>(); interfaceToOperations = new HashMap<>(); allAdditionalSerializationClasses = new HashSet<>(); Class<?>[] expectedParamTypes = new Class<?>[] { Commit.class }; for (Class<?> interfaceClass : interfaceToImpl.keySet()) { interfaceToOperations.put(interfaceClass, new HashSet<>()); for (Method m : interfaceClass.getMethods()) { if (Modifier.isStatic(m.getModifiers())) continue; ConsensusMethod consensusMethod = m.getAnnotation(ConsensusMethod.class); if (consensusMethod != null) { if (!Arrays.equals(expectedParamTypes, m.getParameterTypes())) throw new RuntimeException("Method '" + m.toString() + "' has wrong parameter types to be a " + ConsensusMethod.class.getSimpleName()); Class<? extends Operation<?>> dataClass = consensusMethod.dataClass(); dataClassToInterfaceAndMethodNameAndParameters.put(dataClass, new Triple<Class<?>, String, Class<?>[]>(interfaceClass, m.getName(), m.getParameterTypes())); interfaceToOperations.get(interfaceClass).add(dataClass); allAdditionalSerializationClasses .addAll(Arrays.asList(consensusMethod.additionalSerializationClasses())); } } } allAdditionalSerializationClasses.remove(Object.class); // remove default value of annotation logger.debug("Loaded {} consensus operations of {} interfaces", dataClassToInterfaceAndMethodNameAndParameters.keySet().size(), interfaceToImpl.keySet().size()); }
From source file:com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry.java
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); }/*from ww w . j a v a 2 s.c o m*/ }
From source file:com.github.lukaszbudnik.gugis.GugisModule.java
private List<Class<?>> getClassesAnnotatedWith(final Class<? extends Annotation> annotationClass) { List<Class<?>> foundClasses; try {//from ww w . jav a 2 s. com foundClasses = FluentIterable.from(ClassPath.from(this.getClass().getClassLoader()).getAllClasses()) .filter(new Predicate<ClassPath.ClassInfo>() { @Override public boolean apply(ClassPath.ClassInfo input) { try { return input.load().isAnnotationPresent(annotationClass); } catch (Throwable t) { return false; } } }).transform(new Function<ClassPath.ClassInfo, Class<?>>() { @Override public Class<?> apply(ClassPath.ClassInfo input) { return input.load(); } }).toList(); } catch (IOException e) { throw new GugisCreationException("Could not load classes ", e); } return foundClasses; }
From source file:com.github.cassandra.jdbc.provider.datastax.DataStaxSessionFactory.java
private static DataStaxSessionWrapper newSession(CassandraConfiguration config, String keyspace) { keyspace = Strings.isNullOrEmpty(keyspace) || config.getKeyspace().equals(keyspace) ? config.getKeyspace() : keyspace;//from ww w . j av a 2 s . co m Logger.debug("Connecting to [{}]...", config.getConnectionUrl()); Cluster.Builder builder = Cluster.builder(); // add contact points for (String host : Splitter.on(',').trimResults().omitEmptyStrings().split(config.getHosts())) { builder.addContactPoint(host); } // set port if specified if (config.getPort() > 0) { builder.withPort(config.getPort()); } // set socket options SocketOptions socketOptions = new SocketOptions(); socketOptions.setConnectTimeoutMillis(config.getConnectionTimeout()); socketOptions.setReadTimeoutMillis(config.getReadTimeout()); socketOptions.setKeepAlive(config.isKeepAlive()); builder.withSocketOptions(socketOptions); // set query options QueryOptions queryOptions = new QueryOptions(); queryOptions.setConsistencyLevel(ConsistencyLevel.valueOf(config.getConsistencyLevel().name())); if (config.getFetchSize() > 0) { queryOptions.setFetchSize(config.getFetchSize()); } builder.withQueryOptions(queryOptions); // set pool options - use same defaults as in V3 PoolingOptions poolOptions = new PoolingOptions(); poolOptions.setConnectionsPerHost(HostDistance.LOCAL, config.getAdditionalProperty("corePoolLocal", 1), config.getAdditionalProperty("maxPoolLocal", 1)); poolOptions.setConnectionsPerHost(HostDistance.REMOTE, config.getAdditionalProperty("corePoolRemote", 1), config.getAdditionalProperty("maxPoolRemote", 1)); poolOptions.setIdleTimeoutSeconds( config.getAdditionalProperty("idleTimeoutSeconds", poolOptions.getIdleTimeoutSeconds())); poolOptions.setPoolTimeoutMillis( config.getAdditionalProperty("poolTimeoutMillis", poolOptions.getPoolTimeoutMillis())); poolOptions.setHeartbeatIntervalSeconds(config.getAdditionalProperty("heartbeatIntervalSeconds", poolOptions.getHeartbeatIntervalSeconds())); poolOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, config.getAdditionalProperty("maxRequestsPerConnectionLocal", 800)); poolOptions.setMaxRequestsPerConnection(HostDistance.REMOTE, config.getAdditionalProperty("maxRequestsPerConnectionRemote", 200)); poolOptions.setNewConnectionThreshold(HostDistance.LOCAL, config.getAdditionalProperty("newConnectionThresholdLocal", 1024)); poolOptions.setNewConnectionThreshold(HostDistance.REMOTE, config.getAdditionalProperty("newConnectionThresholdRemote", 256)); builder.withPoolingOptions(poolOptions); // set compression builder.withCompression(ProtocolOptions.Compression.valueOf(config.getCompression().name())); // add custom codecs CodecRegistry registry = new CodecRegistry(); registry.register(LocalDateCodec.instance, LocalTimeCodec.instance, InstantCodec.instance); String packageName = JavaSqlTimeCodec.class.getPackage().getName(); try { // FIXME one exception will stop loading the rest codecs for (ClassPath.ClassInfo info : ClassPath.from(DataStaxSessionFactory.class.getClassLoader()) .getTopLevelClasses()) { if (packageName.equals(info.getPackageName())) { Logger.debug("Registering codec: {}", info.getName()); registry.register((TypeCodec) info.load().getField("instance").get(null)); } } } catch (Exception e) { Logger.warn(e, "Failed to register codec"); } builder.withCodecRegistry(registry); // FIXME set policies based on configuration if (!Strings.isNullOrEmpty(config.getLocalDc())) { builder.withLoadBalancingPolicy( DCAwareRoundRobinPolicy.builder().withLocalDc(config.getLocalDc()).build()); } else { builder.withLoadBalancingPolicy(new RoundRobinPolicy()); } // build the cluster Cluster cluster = builder.withCredentials(config.getUserName(), config.getPassword()).build(); Logger.debug("Connected to [{}({})] successfully", config.getConnectionUrl(), cluster.hashCode()); Metadata metadata = cluster.getMetadata(); Logger.info("Connected to cluster@{}: {}", cluster.hashCode(), metadata.getClusterName()); for (Host host : metadata.getAllHosts()) { Logger.info("-> Datacenter: {}, Host: {}, Rack: {}", host.getDatacenter(), host.getAddress(), host.getRack()); } return new DataStaxSessionWrapper(cluster.connect(keyspace)); }
From source file:com.puppycrawl.tools.checkstyle.internal.CheckUtil.java
/** * Gets all checkstyle's non-abstract checks. * @return the set of checkstyle's non-abstract check classes. * @throws IOException if the attempt to read class path resources failed. * @see #isValidCheckstyleClass(Class, String) * @see #isCheckstyleCheck(Class)// w w w . j a v a 2 s . c om */ public static Set<Class<?>> getCheckstyleChecks() throws IOException { final Set<Class<?>> checkstyleChecks = 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 String className = clazz.getSimpleName(); final Class<?> loadedClass = clazz.load(); if (isValidCheckstyleClass(loadedClass, className) && isCheckstyleCheck(loadedClass)) { checkstyleChecks.add(loadedClass); } } return checkstyleChecks; }