org.reflections.scanners.FieldAnnotationsScanner Java Examples

The following examples show how to use org.reflections.scanners.FieldAnnotationsScanner. 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: EsMapper.java    From soundwave with Apache License 2.0 6 votes vote down vote up
/**
 * Get fields for a type. It extracts all JsonProperty fields
 * @param type
 * @return
 */
public static String[] getIncludeFields(Class type) {
  if (!fieldsCache.containsKey(type.getTypeName())) {
    Reflections
        reflections =
        new Reflections(type.getCanonicalName(), new FieldAnnotationsScanner());
    List<String> ret = new ArrayList<>();
    for (Field field : reflections.getFieldsAnnotatedWith(JsonProperty.class)) {
      JsonProperty property = field.getAnnotation(JsonProperty.class);
      ret.add(property.value());
    }

    if (type.getSuperclass() != null) {
      ret.addAll(Arrays.asList(getIncludeFields(type.getSuperclass())));
    }

    fieldsCache.putIfAbsent(type.getTypeName(), ret.toArray(new String[ret.size()]));
  }
  return fieldsCache.get(type.getTypeName());
}
 
Example #2
Source File: EnumeratedTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIfThereAreEnumeratedAnnotations() {
    Reflections reflections = new Reflections("com.sequenceiq",
            new FieldAnnotationsScanner());

    Map<String, Set<String>> enumeratedFields = new HashMap<>();
    reflections.getFieldsAnnotatedWith(Enumerated.class).forEach(field -> {
        try {
            String className = field.getDeclaringClass().getName();
            enumeratedFields.computeIfAbsent(className, key -> new HashSet<>()).add(field.toString());
        } catch (RuntimeException e) {
            // ignore if cannot check fields
        }
    });

    Set<String> fields = new HashSet<>();

    enumeratedFields.forEach((key, value) -> {
        fields.add(key + ": " + String.join(", ", value));
    });

    Assert.assertTrue(
            String.format("Classes with @Enumerated fields: %s%s%s%s", lineSeparator(),
                    String.join(lineSeparator(), fields), lineSeparator(), "Use @Converter instead of @Enumerated"), enumeratedFields.isEmpty());
}
 
Example #3
Source File: ReflectionsCache.java    From java-flagz with MIT License 5 votes vote down vote up
static synchronized Reflections reflectionsForPrefixes(List<String> prefixes) {
  if (packagePrefixesToReflections.containsKey(prefixes)) {
    return packagePrefixesToReflections.get(prefixes);
  }
  ConfigurationBuilder builder = new ConfigurationBuilder()
      .setUrls(urlsToReflect(prefixes))
      .setScanners(
          new FieldAnnotationsScanner(),
          new SubTypesScanner());
  Reflections reflections = new Reflections(builder);
  packagePrefixesToReflections.put(prefixes, reflections);
  return reflections;
}
 
Example #4
Source File: OWLSchemaPersistingManagerTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #5
Source File: OWLSchemaPersistingManagerTest.java    From anno4j with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #6
Source File: TypesafeConfigModule.java    From typesafeconfig-guice with Apache License 2.0 5 votes vote down vote up
public static Reflections createPackageScanningReflections(String packageNamePrefix){
	ConfigurationBuilder configBuilder =
			new ConfigurationBuilder()
					.filterInputsBy(new FilterBuilder().includePackage(packageNamePrefix))
					.setUrls(ClasspathHelper.forPackage(packageNamePrefix))
					.setScanners(
							new TypeAnnotationsScanner(),
							new MethodParameterScanner(),
							new MethodAnnotationsScanner(),
							new FieldAnnotationsScanner()
					);
	return new Reflections(configBuilder);
}
 
Example #7
Source File: ClassFinder.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static <T extends BrooklynObject> Set<Class<? extends T>> findClasses(Collection<URL> urls, Class<T> clazz) {
    ClassLoader classLoader = new UrlClassLoader(urls.toArray(new URL[urls.size()]));
    
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .addClassLoader(classLoader)
            .addScanners(new SubTypesScanner(), new TypeAnnotationsScanner(), new FieldAnnotationsScanner())
            .addUrls(urls));
    
    Set<Class<? extends T>> types = reflections.getSubTypesOf(clazz);
    
    return types;
}
 
Example #8
Source File: InjectTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testIfThereAreUnusedInjections() {
    Reflections reflections = new Reflections("com.sequenceiq",
            new FieldAnnotationsScanner(),
            new TypeAnnotationsScanner(),
            new SubTypesScanner(),
            new MemberUsageScanner());

    Map<String, Set<String>> unusedFields = new HashMap<>();
    reflections.getFieldsAnnotatedWith(Inject.class).forEach(field -> {
        try {
            Set<Member> usages = reflections.getFieldUsage(field);
            if (usages.isEmpty()) {
                String className = field.getDeclaringClass().getName();
                unusedFields.computeIfAbsent(className, key -> new HashSet<>()).add(field.toString());
            }
        } catch (RuntimeException e) {
            // ignore if cannot check fields
        }
    });

    Set<String> fields = new HashSet<>();

    unusedFields.forEach((key, value) -> {
        fields.add(key + ": " + String.join(", ", value));
    });

    Assert.assertTrue(
            String.format("Classes with unused injected fields: %s%s", lineSeparator(), String.join(lineSeparator(), fields)), unusedFields.isEmpty());
}
 
Example #9
Source File: DefaultEnumConverterCompatibilityTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultEnumConverterCompatibility() {
    Reflections reflections = new Reflections("com.sequenceiq",
            new FieldAnnotationsScanner());

    Map<String, Set<String>> incompatibleFields = new HashMap<>();
    reflections.getFieldsAnnotatedWith(Convert.class).forEach(field -> {
        try {
            var defaultEnumConverterType = Optional.of((field.getAnnotation(Convert.class).converter()).getGenericSuperclass())
                    .filter(t -> ((ParameterizedType) t).getRawType().getTypeName().equals(DefaultEnumConverter.class.getTypeName()));

            if (defaultEnumConverterType.isPresent()) {
                boolean hasCompatibleGenericParameter = Stream.of(((ParameterizedType) defaultEnumConverterType.get()).getActualTypeArguments())
                        .allMatch(a -> a.getTypeName().equals(field.getType().getTypeName()));

                if (!hasCompatibleGenericParameter) {
                    String className = field.getDeclaringClass().getName();
                    incompatibleFields.computeIfAbsent(className, key -> new HashSet<>()).add(field.toString());
                }
            }
        } catch (RuntimeException e) {
            // ignore if cannot check fields
        }
    });

    Set<String> fields = new HashSet<>();

    incompatibleFields.forEach((key, value) -> {
        fields.add(key + ": " + String.join(", ", value));
    });

    Assert.assertTrue(String.format("Classes with incompatible DefaultEnumConverter: %s%s", lineSeparator(),
                    String.join(lineSeparator(), fields)), incompatibleFields.isEmpty());
}
 
Example #10
Source File: LogSearchDocumentationGenerator.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
private static ShipperConfigDescriptionDataHolder createShipperConfigDescriptions(List<String> shipperConfigPackagesToScan) {
  final List<ShipperConfigDescriptionData> shipperConfigDescription = new ArrayList<>();
  Reflections reflections = new Reflections(shipperConfigPackagesToScan, new FieldAnnotationsScanner());
  Set<Field> fields = reflections.getFieldsAnnotatedWith(ShipperConfigElementDescription.class);
  for (Field field : fields) {
    ShipperConfigElementDescription description = field.getAnnotation(ShipperConfigElementDescription.class);
    shipperConfigDescription.add(new ShipperConfigDescriptionData(description.path(), description.description(),
      description.examples(), description.defaultValue()));
  }
  shipperConfigDescription.sort(Comparator.comparing(ShipperConfigDescriptionData::getPath));

  final List<ShipperConfigDescriptionData> topLevelConfigSections = shipperConfigDescription.stream()
    .filter(
      s -> (s.getPath().equals("/filter") || s.getPath().equals("/input") || s.getPath().equals("/output")))
    .distinct()
    .collect(Collectors.toList());

  final List<ShipperConfigDescriptionData> inputConfigSection = shipperConfigDescription.stream()
    .filter(
      s -> (s.getPath().startsWith("/input") && !s.getPath().equals("/input")))
    .distinct()
    .collect(Collectors.toList());

  final List<ShipperConfigDescriptionData> filterConfigSection = shipperConfigDescription.stream()
    .filter(
      s -> (s.getPath().startsWith("/filter") && !s.getPath().equals("/filter") && !s.getPath().startsWith("/filter/[]/post_map_values")) || s.getPath().equals("/filter/[]/post_map_values"))
    .distinct()
    .collect(Collectors.toList());

  final List<ShipperConfigDescriptionData> postMapValuesConfigSection = shipperConfigDescription.stream()
    .filter(
      s -> (s.getPath().startsWith("/filter/[]/post_map_values") && !s.getPath().equals("/filter/[]/post_map_values")))
    .distinct()
    .collect(Collectors.toList());

  final List<ShipperConfigDescriptionData> outputConfigSection = shipperConfigDescription.stream()
    .filter(
      s -> s.getPath().startsWith("/output/[]"))
    .distinct()
    .collect(Collectors.toList());

  return new ShipperConfigDescriptionDataHolder(topLevelConfigSections, inputConfigSection, filterConfigSection,
    postMapValuesConfigSection, outputConfigSection);
}
 
Example #11
Source File: ReflectionBasedJsr303AnnotationTrollerBase.java    From backstopper with Apache License 2.0 4 votes vote down vote up
/**
 * 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));
}
 
Example #12
Source File: Anno4j.java    From anno4j with Apache License 2.0 4 votes vote down vote up
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();

    // Index conceptsByIri with @Iri annotation:
    indexConcepts(annotatedClasses);

    // 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);
    }
}
 
Example #13
Source File: OWLSchemaPersistingManagerTest.java    From anno4j with Apache License 2.0 4 votes vote down vote up
@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());
}