public AlgorithmServiceImpl() { map = new HashMap<>(); List<URL> urlList = new ArrayList<>(); for(String f:System.getProperty("java.class.path").split(":")){ System.err.println(f); try { urlList.add(new File(f).toURI().toURL()); } catch (IOException e) { e.printStackTrace(); } } URL[] urls = urlList.toArray(new URL[0]); Reflections reflections = new Reflections("jobreading.algorithm.experiment",new MethodAnnotationsScanner(),urls); for(Method method : reflections.getMethodsAnnotatedWith(Algorithm.class)){ final Algorithm my = method.getAnnotation(Algorithm.class); Class<?> clazz = method.getDeclaringClass(); if (null != my) { map.put(my.name(), clazz); } } }
private Set<Class<?>> scanTypes(String packageName) { Reflections reflections = new Reflections(packageName, new MethodAnnotationsScanner()); Set<Class<?>> types = new HashSet<>(); types.addAll(typesAnnotatedWith(reflections, Given.class)); types.addAll(typesAnnotatedWith(reflections, When.class)); types.addAll(typesAnnotatedWith(reflections, Then.class)); types.addAll(typesAnnotatedWith(reflections, Before.class)); types.addAll(typesAnnotatedWith(reflections, After.class)); types.addAll(typesAnnotatedWith(reflections, BeforeScenario.class)); types.addAll(typesAnnotatedWith(reflections, AfterScenario.class)); types.addAll(typesAnnotatedWith(reflections, BeforeStory.class)); types.addAll(typesAnnotatedWith(reflections, AfterStory.class)); types.addAll(typesAnnotatedWith(reflections, BeforeStories.class)); types.addAll(typesAnnotatedWith(reflections, AfterStories.class)); types.addAll(typesAnnotatedWith(reflections, AsParameterConverter .class)); return types; }
public void scan(String base) { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(base)) .setScanners(new MethodAnnotationsScanner()) ); Set<Method> predicateMethods = reflections.getMethodsAnnotatedWith(Predicate.class); for (Method method : predicateMethods) { String name = method.getAnnotation(Predicate.class).name(); if (name.isEmpty()) { name = method.getName(); } this.register(method, name); } }
private String getKeywordClassList(URLClassLoader cl) throws Exception { URL url = cl.getURLs()[0]; try { Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(url) .addClassLoader(cl).setScanners(new MethodAnnotationsScanner())); Set<Method> methods = reflections.getMethodsAnnotatedWith(Keyword.class); Set<String> kwClasses = new HashSet<>(); for(Method method:methods) { kwClasses.add(method.getDeclaringClass().getName()); } StringBuilder kwClassnamesBuilder = new StringBuilder(); kwClasses.forEach(kwClassname->kwClassnamesBuilder.append(kwClassname+";")); return kwClassnamesBuilder.toString(); } catch (Exception e) { String errorMsg = "Error while looking for methods annotated with @Keyword in "+url.toString(); throw new Exception(errorMsg, e); } }
private static Set<Class<?>> getReflected() { synchronized (LOCK) { if (reflected != null) { return reflected; } Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("com.jivesoftware")) .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner())); Set<Class<?>> result = reflections.getTypesAnnotatedWith(Path.class); Set<Method> methods = reflections.getMethodsAnnotatedWith(Path.class); for (Method method : methods) { result.add(method.getDeclaringClass()); } reflected = Collections.unmodifiableSet(result); return reflected; } }
public void test() { final Reflections reflections = new Reflections(new ConfigurationBuilder() .addUrls(ClasspathHelper.forClassLoader()) .setScanners(new MethodAnnotationsScanner()) ); final Set<Method> methods = reflections.getMethodsAnnotatedWith(Cached.class); System.out.println("Found " + methods.size() + " methods annotated with " + Cached.class); for (final Method method : methods) { testMethod(method); } assertNoExceptions(); }
/** * Scans the specified packages for annotated classes, and applies Config values to them. * * @param config the Config to derive values from * @param packageNamePrefix the prefix to limit scanning to - e.g. "com.github" * @return The constructed TypesafeConfigModule. */ public static TypesafeConfigModule fromConfigWithPackage(Config config, String packageNamePrefix) { ConfigurationBuilder configBuilder = new ConfigurationBuilder() .filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix)) .setUrls(ClasspathHelper.forPackage(packageNamePrefix)) .setScanners( new TypeAnnotationsScanner(), new MethodParameterScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner() ); Reflections reflections = new Reflections(configBuilder); return new TypesafeConfigModule(config, reflections); }
private Set<ActionData> getActionContext(String controllerPackageScan) { Set<ActionData> resourceContext = new HashSet<ActionData>(); if (controllerPackageScan.isEmpty()) return resourceContext; Reflections reflections = new Reflections(new ConfigurationBuilder() .addUrls(ClasspathHelper.forPackage(controllerPackageScan)) .setScanners(new MethodAnnotationsScanner())); Set<Method> methodSet = reflections.getMethodsAnnotatedWith(Action.class); for (Method method : methodSet) { Secured authenticated = (Secured)method.getAnnotation(Secured.class); Action action = (Action)method.getAnnotation(Action.class); if (null != action) { resourceContext.add(new ActionData(action.uri(), action.method(), authenticated != null, method)); } } return resourceContext; }
public void invokeAnnotatedMethods( Object inObject, Class<? extends Annotation> inAnnotation ) throws InvokeAnnotatedMethodException { // Retrieve all methods annotated with the given annotation Reflections reflections = new Reflections( inObject.getClass().getName(), new MethodAnnotationsScanner() ); Set<Method> methods = reflections.getMethodsAnnotatedWith( inAnnotation ); // Invoke them for( Method method : methods ) { try { method.invoke( inObject, new Object[]{} ); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new InvokeAnnotatedMethodException( method ); } } }
@Override public void addUrlsTo(WebSitemapGenerator generator) { String baseUrl = configuration.getString("sitemap.baseUrl"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Reflections reflections = new Reflections("controllers", new MethodAnnotationsScanner()); Set<Method> actions = reflections.getMethodsAnnotatedWith(SitemapItem.class); for(Method method : actions) { String actionUrl = actionUrl(classLoader, method); SitemapItem annotation = method.getAnnotation(SitemapItem.class); if(annotation != null) { WebSitemapUrl url = webSitemapUrl(baseUrl, actionUrl, annotation); generator.addUrl(url); } } }
private void init(String packageName) { FilterBuilder filters = new FilterBuilder().includePackage(packageName); Scanner[] scanners = { new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new MethodParameterScanner(), new FieldAnnotationsScanner(), new SubTypesScanner().filterResultsBy(filters) }; reflections = new ConfigurationBuilder() .addUrls(ClasspathHelper.forPackage(packageName)) .addScanners(scanners) .filterInputsBy(filters) .build(); }
/** * {@link Reflections} bean. * * @return bean */ @Bean public Reflections reflections() { return new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(SCAN_PACKAGE)) .setScanners(new MethodAnnotationsScanner())); }
public void generateReport(String packageName,List<String> flagList) throws IOException { URL testClassesURL = Paths.get("target/test-classes").toUri().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{testClassesURL}, ClasspathHelper.staticClassLoader()); reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(packageName,classLoader)) .addClassLoader(classLoader) .filterInputsBy(new FilterBuilder().includePackage(packageName)) .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()) ); List<Map<String, TestClass>> list = new ArrayList<>(); for (String flag : flagList) { list.add(printMethods(flag)); } Gson gson = new Gson(); String overviewTemplate = IOUtils.toString(getClass().getResourceAsStream("/index.tpl.html")); String editedTemplate = overviewTemplate.replace("##TEST_DATA##", gson.toJson(list)); FileUtils.writeStringToFile(new File("target/test-list-html-report/index.html"), editedTemplate); logger.info("report file generated"); }
@Override public Set<Method> findFunctions(final URL url) { return new Reflections( new ConfigurationBuilder() .addUrls(url) .setScanners(new MethodAnnotationsScanner()) .addClassLoader(getClassLoader(url))) .getMethodsAnnotatedWith(FunctionName.class); }
@Override public ReflectionsWrapper configure() { reflections = (Reflections) cache.get(Reflections.class.getName()); if (reflections == null) { ConfigurationBuilder cb = new ConfigurationBuilder(); Set<URL> classLocations = new LinkedHashSet<>(); try { List<URL> urls = Collections.list(Thread.currentThread().getContextClassLoader().getResources("")); for (URL url : urls) { if (url.getPath().contains("/geemvc/target/")) { classLocations.add(url); } } } catch (IOException e) { throw new IllegalStateException(e); } cb = cb.addUrls(classLocations).addClassLoader(Thread.currentThread().getContextClassLoader()); cb = cb.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new SubTypesScanner()); reflections = cb.build(); // Reflections cachedReflections = (Reflections) cache.putIfAbsent(Reflections.class.getName(), reflections); // if (cachedReflections != null) // reflections = cachedReflections; } return this; }
/** * Retrieves a static method with a String return value that is either annotated with {@link Description}, or using the naming convention * getDescription(). * * @param commandClass the class to retrieve the method from * @return the description method, or null if none is found */ static Method getStaticDescriptionMethod(Class<? extends Command> commandClass) { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(forClass(commandClass)) .filterInputsBy(in -> in.endsWith("java") || in.endsWith("class")) .setScanners(new MethodAnnotationsScanner()) ); Set<Method> methodsWithDescriptionAnnotation = reflections.getMethodsAnnotatedWith(Description.class).stream() .filter(x -> x.getDeclaringClass().getCanonicalName().equals(commandClass.getCanonicalName())) .collect(Collectors.toSet()); Method staticDescriptionMethod = null; if (!methodsWithDescriptionAnnotation.isEmpty()) { LOGGER.debug("Found annotated method for description for " + commandClass); staticDescriptionMethod = methodsWithDescriptionAnnotation.iterator().next(); } else { try { staticDescriptionMethod = commandClass.getMethod("getDescription"); } catch (NoSuchMethodException e) { // This case doesn't have to be handled, because it is perfectly fine, when such a method // does not exist LOGGER.trace(e); } } if (staticDescriptionMethod != null) { LOGGER.debug("Dynamic description found and used for " + commandClass); } return staticDescriptionMethod; }
public Anno4j(Repository repository, IDGenerator idGenerator, URI defaultContext, boolean persistSchemaAnnotations, Set<URL> additionalClasses) throws RepositoryConfigException, RepositoryException { this.idGenerator = idGenerator; this.defaultContext = defaultContext; classpath = new HashSet<>(); classpath.addAll(ClasspathHelper.forClassLoader()); classpath.addAll(ClasspathHelper.forJavaClassPath()); classpath.addAll(ClasspathHelper.forManifest()); classpath.addAll(ClasspathHelper.forPackage("")); if(additionalClasses != null) { classpath.addAll(additionalClasses); } Reflections annotatedClasses = new Reflections(new ConfigurationBuilder() .setUrls(classpath) .useParallelExecutor() .filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun")) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner())); // Bugfix: Searching for Reflections creates a lot ot Threads, that are not closed at the end by themselves, // so we close them manually. annotatedClasses.getConfiguration().getExecutorService().shutdown(); // find classes with @Partial annotation this.partialClasses = annotatedClasses.getTypesAnnotatedWith(Partial.class, true); scanForEvaluators(annotatedClasses); if(!repository.isInitialized()) { repository.initialize(); } this.setRepository(repository, additionalClasses, additionalClasses); // Persist schema information to repository: if(persistSchemaAnnotations) { persistSchemaAnnotations(annotatedClasses); } }
@Test public void testMatchingExistingSchema() throws Exception { Anno4j anno4j = new Anno4j(); OWLClazz myPerson = anno4j.createObject(OWLClazz.class, (Resource) new URIImpl("http://example.de/#validly_annotated_person")); RDFSProperty bossProperty = anno4j.createObject(RDFSProperty.class, (Resource) new URIImpl("http://example.de/#has_boss")); Restriction bossAllValuesFromRestr = anno4j.createObject(Restriction.class); bossAllValuesFromRestr.setOnClazz(Sets.newHashSet(myPerson)); bossAllValuesFromRestr.setOnProperty(Sets.newHashSet(bossProperty)); bossAllValuesFromRestr.setAllValuesFrom(Sets.<OWLClazz>newHashSet(myPerson)); Reflections types = new Reflections( new ConfigurationBuilder() .setUrls( ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()), ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader()) ) .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()) ); Transaction transaction = anno4j.createTransaction(); transaction.begin(); SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection()); boolean exceptionThrown = false; try { persistingManager.persistSchema(types); } catch (SchemaPersistingManager.ContradictorySchemaException e) { exceptionThrown = true; } assertFalse(exceptionThrown); }
@Test public void testContradictoryExistingSchema() throws Exception { Anno4j anno4j = new Anno4j(); Transaction setupTransaction = anno4j.createTransaction(); setupTransaction.begin(); setupTransaction.getConnection().prepareUpdate("INSERT DATA {" + " <http://example.de/#validly_annotated_person> rdfs:subClassOf _:restr . " + " _:restr a owl:Restriction . " + " _:restr owl:onProperty <http://example.de/#id> . " + " _:restr owl:minCardinality '42'^^xsd:nonNegativeInteger . " + "}").execute(); setupTransaction.commit(); Transaction transaction = anno4j.createTransaction(); transaction.begin(); SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection()); Reflections types = new Reflections( new ConfigurationBuilder() .setUrls( ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()), ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader()) ) .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()) ); boolean exceptionThrown = false; try { persistingManager.persistSchema(types); } catch (SchemaPersistingManager.ContradictorySchemaException e) { exceptionThrown = true; } assertTrue(exceptionThrown); }
/** * Looks for methods annotated with the given annotation. * * @param annotation an annotation to look for. * @param bundle a bundle to look in. * @return a list of moethods, annotated with the given annotation */ public static Set<Method> getMethods(Class<? extends Annotation> annotation, Bundle bundle) { LOGGER.debug("Searching for methods with annotations: {}", annotation.getName()); Reflections reflections = configureReflection(bundle, new WrappedBundleClassLoader(bundle), new MethodAnnotationsScanner()); Set<Method> methods = reflections.getMethodsAnnotatedWith(annotation); LOGGER.debug("Searched for methods with annotations: {}", annotation.getName()); LOGGER.trace("Found {} methods with annotations: {}", methods.size(), annotation.getName()); return methods; }
@GET @Path("getclasses") public List<GenericClassDescription> getSupportedClasses() { List<GenericClassDescription> classes=new ArrayList<GenericClassDescription>(); Reflections reflections = new Reflections( new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("cm.homeautomation")).setScanners( new SubTypesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner())); // MethodAnnotationsScanner Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Entity.class); for (Class<?> declaringClass : typesAnnotatedWith) { GenericClassDescription clazz=new GenericClassDescription(); clazz.setName(declaringClass.getName()); Field[] fields = declaringClass.getDeclaredFields(); for (Field field : fields) { clazz.getFields().put(field.getName(), field.getType().getSimpleName()); } /*Method[] methods = declaringClass.getDeclaredMethods(); for (Method method : methods) { clazz.getMethods().put(method.getName(), method.getParameters()); }*/ classes.add(clazz); } return classes; }
public void run() { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("cm.homeautomation")).setScanners(new MethodAnnotationsScanner())); // MethodAnnotationsScanner Set<Method> resources = reflections.getMethodsAnnotatedWith(Subscribe.class); for (Method method : resources) { Class<?> declaringClass = method.getDeclaringClass(); // check if the class has already been initialized if (!instances.containsKey(declaringClass)) { LogManager.getLogger(this.getClass()).info("Creating class: " + declaringClass.getName()); Runnable singleInstanceCreator = new Runnable() { public void run() { try { Object classInstance = declaringClass.newInstance(); instances.put(declaringClass, classInstance); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); LogManager.getLogger(this.getClass()).info("Failed creating class"); } } }; new Thread(singleInstanceCreator).start(); } } }
/** * findClasses all the classes that are found within a list of packages. * @param packageLocations List<URL> of all URLs to the package locations * to be searched through. * @return Set<Class<?>> of all unique classes that are to be tested found * within the given packages. */ public static final Set<Class<?>> findClasses(List<URL> packageLocations) { Reflections reflections = new Reflections(new ConfigurationBuilder() .addUrls(packageLocations) .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner(), new MethodAnnotationsScanner())); return Scanner.findClasses(reflections); }
/** * findClasses all the classes that are found that have a specific prefix. * @param prefix String that is to be of all classes' packages to be tested. * @return Set<Class<?>> of all unique classes within packages with the given prefix. */ public static final Set<Class<?>> findClasses(String prefix) { Reflections reflections = new Reflections(prefix, new TypeAnnotationsScanner(), new SubTypesScanner(), new MethodAnnotationsScanner()); return Scanner.findClasses(reflections); }
private static Set<Method> getMethodsForTag(String tag) { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage("info.at.tagging")) .setScanners(new MethodAnnotationsScanner())); Set<Method> testMethods = new HashSet<>(); Set<Method> allMethods = reflections.getMethodsAnnotatedWith(Tag.class); for (Method klass : allMethods) { if (Arrays.asList(klass.getAnnotation(Tag.class).value()).contains(tag)) { testMethods.add(klass); } } return testMethods; }
public EStream<Method, Exception> annotatedMethods(Class<? extends Annotation> annotation) { return EStream.from(new Reflections(new ConfigurationBuilder() .forPackages(packages) .addScanners(new MethodAnnotationsScanner())) .getMethodsAnnotatedWith(annotation)); }
@Override public Reflections provide() { Reflections reflections = null; try { ConfigurationBuilder cb = new ConfigurationBuilder(); URL webappClassesPath = webappClassesPath(); URL geemvcLibPath = geemvcLibPath(); // TODO: Offer configuration for extra libs. URL gensonLibPath = gensonLibPath(); cb = cb.addUrls(webappClassesPath, geemvcLibPath).addClassLoader(mainClassLoader()); if (gensonLibPath != null && !isExcluded(gensonLibPath.getPath())) { cb = cb.addUrls(gensonLibPath); } // Add configured libraries configured. cb = addConfiguredIncludes(cb); // Give the developer a chance to add his own URLs. Set<URL> urls = appendURLs(); if (urls != null && !urls.isEmpty()) { for (URL url : urls) { if (url != null) { cb = cb.addUrls(url); } } } // Give the developer a chance to add his own class-loaders. Set<ClassLoader> classLoaders = appendClassLoaders(); if (classLoaders != null && !classLoaders.isEmpty()) { cb = cb.addClassLoaders(classLoaders); } // Set all scanners. Can be changed in the extend() method if necessary. cb = cb.setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new SubTypesScanner()); // Give the developer a chance to extend the ConfigurationBuilder without having to re-implement the whole class. extend(cb); // Finally build the reflections. reflections = cb.build(); } catch (Exception e) { throw new IllegalStateException(e); } return reflections; }
/** * Initializes the instance based on what is returned by {@link #ignoreAllAnnotationsAssociatedWithTheseProjectClasses()} * and {@link #specificAnnotationDeclarationExclusionsForProject()}. This is time consuming and should only be done * once per project if possible - see the usage info in the {@link ReflectionBasedJsr303AnnotationTrollerBase} * class-level javadocs. * * <p>The given set of extra packages for constraint annotation searching will be passed into {@link * #getFinalPackagesToSearchForConstraintAnnotations(Set)} to generate the final set of packages that are searched. * If you don't want the {@link #DEFAULT_CONSTRAINT_SEARCH_PACKAGES} default packages to be searched you can * override {@link #getDefaultPackagesToSearchForConstraintAnnotations()}. */ public ReflectionBasedJsr303AnnotationTrollerBase(Set<String> extraPackagesForConstraintAnnotationSearch) { /* * Set up the {@link #ignoreAllAnnotationsAssociatedWithTheseClasses} and * {@link #specificAnnotationDeclarationsExcludedFromStrictMessageRequirement} fields so we know which * annotations are project-relevant vs. unit-test-only. */ ignoreAllAnnotationsAssociatedWithTheseClasses = new ArrayList<>(setupIgnoreAllAnnotationsAssociatedWithTheseClasses()); specificAnnotationDeclarationsExcludedFromStrictMessageRequirement = new ArrayList<>(setupSpecificAnnotationDeclarationExclusions()); /* * Set up the {@link #reflections}, {@link #constraintAnnotationClasses}, and * {@link #allConstraintAnnotationsMasterList} fields. This is where the crazy reflection magic happens to troll * the project for the JSR 303 annotation declarations. */ // Create the ConfigurationBuilder to search the relevant set of packages. ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); for (String packageToAdd : getFinalPackagesToSearchForConstraintAnnotations( extraPackagesForConstraintAnnotationSearch)) { configurationBuilder.addUrls(ClasspathHelper.forPackage(packageToAdd)); } // Create the Reflections object so it scans for all validation annotations we care about and all project // classes that might have annotations on them. reflections = new Reflections(configurationBuilder.setScanners( new SubTypesScanner(), new MethodParameterScanner(), new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new FieldAnnotationsScanner() )); // Gather the list of all JSR 303 validation annotations in the project. Per the JSR 303 spec this is any // annotation class type that is marked with @Constraint. constraintAnnotationClasses = new ArrayList<>(); for (Class<?> constraintAnnotatedType : reflections.getTypesAnnotatedWith(Constraint.class, true)) { if (constraintAnnotatedType.isAnnotation()) { //noinspection unchecked constraintAnnotationClasses.add((Class<? extends Annotation>) constraintAnnotatedType); } } // We're not done gathering validation annotations though, unfortunately. JSR 303 also says that *any* // annotation (whether it is a Constraint or not) that has a value field that returns an array of actual // Constraints is treated as a "multi-value constraint", and the validation processor will run each // of the Constraints in the array as if they were declared separately on the annotated element. Therefore, // we have to dig through all the annotations in the project, find any that fall into this "multi-value // constraint" category, and include them in our calculations. for (Class<? extends Annotation> annotationClass : reflections.getSubTypesOf(Annotation.class)) { if (isMultiValueConstraintClass(annotationClass)) constraintAnnotationClasses.add(annotationClass); } // Setup the master constraint list allConstraintAnnotationsMasterList = new ArrayList<>(setupAllConstraintAnnotationsMasterList(reflections, constraintAnnotationClasses)); /* * Finally use the info we've gathered/constructed previously to populate the * {@link #projectRelevantConstraintAnnotationsExcludingUnitTestsList} field, which is the main chunk of data * that extensions of this class will care about. */ projectRelevantConstraintAnnotationsExcludingUnitTestsList = Collections.unmodifiableList( getSubAnnotationListUsingExclusionFilters(allConstraintAnnotationsMasterList, ignoreAllAnnotationsAssociatedWithTheseClasses, specificAnnotationDeclarationsExcludedFromStrictMessageRequirement)); }
public void setPackage(String pkg) { this.reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(pkg)) .setScanners(new MethodAnnotationsScanner()) .filterInputsBy(new FilterBuilder().includePackage(pkg))); }
public void afterPropertiesSet() throws Exception { Preconditions.checkArgument(!Strings.isNullOrEmpty(basePackage),"base package must not be null or empty."); Reflections reflections = new Reflections( new ConfigurationBuilder().setUrls( ClasspathHelper.forPackage(basePackage)).setScanners( new MethodAnnotationsScanner())); Set<Method> methods = reflections.getMethodsAnnotatedWith(Limiter.class); for(Method method:methods){ String methodAbsPath = MethodUtil.getAsbMethodCacheKey(method); if(!Strings.isNullOrEmpty(methodAbsPath)){ Limiter limiter = method.getAnnotation(Limiter.class); double value = limiter.value(); RateLimiter rateLimiter = RateLimiter.create(value); RateLimiterCache.put(methodAbsPath,rateLimiter); } } }
@Test public void testAnnotationPersisting() throws Exception { Anno4j anno4j = new Anno4j(); Reflections types = new Reflections( new ConfigurationBuilder() .setUrls( ClasspathHelper.forClass(Person.class, ClasspathHelper.staticClassLoader()), ClasspathHelper.forClass(PersonSupport.class, ClasspathHelper.staticClassLoader()) ) .setScanners(new MethodAnnotationsScanner(), new FieldAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()) ); Transaction transaction = anno4j.createTransaction(); transaction.begin(); SchemaPersistingManager persistingManager = new OWLSchemaPersistingManager(transaction.getConnection()); persistingManager.persistSchema(types); // Query property characteristics: String q = QUERY_PREFIX + "ASK { " + " <http://example.de/#id> a owl:FunctionalProperty . " + " <http://example.de/#id> a owl:InverseFunctionalProperty . " + " <http://example.de/#partner> a owl:SymmetricProperty . " + " <http://example.de/#has_subordinate> a owl:TransitiveProperty . " + " <http://example.de/#has_boss> a owl:TransitiveProperty . " + " <http://example.de/#has_boss> owl:inverseOf <http://example.de/#has_subordinate> . " + " <http://example.de/#has_subordinate> owl:inverseOf <http://example.de/#has_boss> . " + "}"; BooleanQuery characteristicsQuery = transaction.getConnection().prepareBooleanQuery(QueryLanguage.SPARQL, q); assertTrue(characteristicsQuery.evaluate()); // Query property restrictions: q = QUERY_PREFIX + "ASK { " + " ?r1 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r1 . " + " ?r1 owl:onProperty <http://example.de/#id> . " + " ?r1 owl:minCardinality ?v1 . " + " FILTER ( ?v1 = 1 )" + " ?r2 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r2 . " + " ?r2 owl:onProperty <http://example.de/#id> . " + " ?r2 owl:maxCardinality ?v2 . " + " FILTER ( ?v2 = 1 )" + " ?r3 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r3 . " + " ?r3 owl:onProperty <http://example.de/#partner> . " + " ?r3 owl:onClass <http://example.de/#validly_annotated_person> . " + " ?r3 owl:minQualifiedCardinality ?v3 . " + " FILTER ( ?v3 = 0 )" + " ?r4 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r4 . " + " ?r4 owl:onProperty <http://example.de/#has_boss> . " + " ?r4 owl:allValuesFrom <http://example.de/#validly_annotated_person> . " + " ?r5 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r5 . " + " ?r5 owl:onProperty <http://example.de/#has_activity> . " + " ?r5 owl:minCardinality ?v5 . " + " FILTER( ?v5 = 2 )" + " ?r6 a owl:Restriction . " + " <http://example.de/#validly_annotated_person> rdfs:subClassOf ?r6 . " + " ?r6 owl:onProperty <http://example.de/#has_activity> . " + " ?r6 owl:minQualifiedCardinality ?v6 . " + " ?r6 owl:onClass <http://example.de/#job> . " + " FILTER( ?v6 = 1 )" + "}"; BooleanQuery restrictionQuery = transaction.getConnection().prepareBooleanQuery(QueryLanguage.SPARQL, q); assertTrue(restrictionQuery.evaluate()); }
public static void scanner(String scannerPackageName) { // 构建查找器 Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(scannerPackageName)) .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner())); // 选出所有带有 @NessianAPI 注解的方法 Set<Method> methods = reflections.getMethodsAnnotatedWith(NessianAPI.class); Method urlMethod = null; try { urlMethod = UrlService.class.getMethod("getAllUrl"); } catch (NoSuchMethodException e) { e.printStackTrace(); } // 加入获取URL的api methodToUrlMap.put("top.nessian.client.service.UrlService.getAllUrl", "/all/urls"); methodMap.put("/all/urls", urlMethod); // 遍历所有带有注解的方法,然后操作. for (Method method : methods) { String url = method.getAnnotation(NessianAPI.class).value(); // 校验URL格式 if (!url.startsWith("/")) { url += "/"; } // 检查URL是不是重复了. if (methodMap.containsKey(url)) { throw new RuntimeException("url有重复."); } String fullMethodName = String.format("%s.%s", method.getDeclaringClass().getName(), method.getName()); methodToUrlMap.put(fullMethodName, url); // 把方法和URL对应起来,然后缓存起来. methodMap.put(url, method); } }
public boolean runMethodParallelAppium(List<String> test, String pack, int devicecount, String executionType) throws Exception { URL newUrl = null; List<URL> newUrls = new ArrayList<>(); Collections.addAll(items, pack.split("\\s*,\\s*")); int a = 0; Collection<URL> urls = ClasspathHelper.forPackage(items.get(a)); Iterator<URL> iter = urls.iterator(); URL url = iter.next(); urls.clear(); for (int i = 0; i < items.size(); i++) { newUrl = new URL(url.toString() + items.get(i).replaceAll("\\.", "/")); newUrls.add(newUrl); a++; } Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(newUrls) .setScanners(new MethodAnnotationsScanner())); Set<Method> resources = reflections.getMethodsAnnotatedWith(org.testng.annotations.Test.class); boolean hasFailure; String runnerLevel = System.getenv("RUNNER_LEVEL") != null ? System.getenv("RUNNER_LEVEL") : prop.getProperty("RUNNER_LEVEL"); if (executionType.equalsIgnoreCase("distribute")) { if (runnerLevel != null && runnerLevel.equalsIgnoreCase("class")) { constructXmlSuiteForDistribution(pack, test, createTestsMap(resources), devicecount); } else { constructXmlSuiteForDistributionMethods(pack, test, createTestsMap(resources), devicecount); } hasFailure = runMethodParallel(); } else { constructXmlSuiteForParallel(pack, test, createTestsMap(resources), devicecount, deviceAllocationManager.getDevices()); hasFailure = runMethodParallel(); } System.out.println("Finally complete"); ParallelThread.figlet("Test Completed"); //ImageUtils.creatResultsSet(); //ImageUtils.createJSonForHtml(); return hasFailure; }
public TypesFinder(){ reflections = new Reflections(new FieldAnnotationsScanner(), new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner()); }