org.reflections.scanners.TypeAnnotationsScanner Java Examples

The following examples show how to use org.reflections.scanners.TypeAnnotationsScanner. 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: GuiceBundle.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link org.reflections.Reflections} with the given packages (configuration)
 *
 * @param scanPackages
 */
private void createReflections(String[] scanPackages) {
    if (scanPackages.length < 1) {
        LOGGER.warn("No package defined in configuration (scanPackages)!");
        return;
    }
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    FilterBuilder filterBuilder = new FilterBuilder();
    for (String packageName : scanPackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(packageName));
        filterBuilder.include(FilterBuilder.prefix(packageName));
    }

    configurationBuilder.filterInputsBy(filterBuilder).setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    this.reflections = new Reflections(configurationBuilder);

}
 
Example #2
Source File: TypeScriptDtoGenerator.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Init stuff is responsible to grab all DTOs found in classpath (classloader) and setup model for
 * String Template
 */
protected void init() {

  ConfigurationBuilder configurationBuilder =
      new ConfigurationBuilder().setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
  if (useClassPath) {
    configurationBuilder.setUrls(forJavaClassPath());
  } else {
    configurationBuilder.setUrls(forClassLoader());
  }

  // keep only DTO interfaces
  Reflections reflections = new Reflections(configurationBuilder);
  List<Class<?>> annotatedWithDtos =
      new ArrayList<>(reflections.getTypesAnnotatedWith(DTO.class));
  List<Class<?>> interfacesDtos =
      annotatedWithDtos
          .stream()
          .filter(clazz -> clazz.isInterface())
          .collect(Collectors.toList());
  interfacesDtos.stream().forEach(this::analyze);
}
 
Example #3
Source File: RoleClassLoader.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private void scanConceptsWithReflections() throws ObjectStoreConfigException {
    logger.debug("Search for concepts with reflections");
    Set<URL> classpath = new HashSet<>();
    classpath.addAll(ClasspathHelper.forClassLoader());
    classpath.addAll(ClasspathHelper.forJavaClassPath());
    classpath.addAll(ClasspathHelper.forManifest());
    classpath.addAll(ClasspathHelper.forPackage(""));
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(classpath)
.useParallelExecutor()
.filterInputsBy(FilterBuilder.parsePackages("-java, -javax, -sun, -com.sun"))
            .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner()));

    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Iri.class, true);
    logger.debug("Search for concepts with reflections resulted in " + annotated.size() + " classes");
    for (Class clazz : annotated) {
        logger.debug("Found concept class: " + clazz.getCanonicalName());
        roleMapper.addConcept(clazz);
    }
}
 
Example #4
Source File: AnnotationLoader.java    From livingdoc-core with GNU General Public License v3.0 6 votes vote down vote up
public void addLoader(ClassLoader loader) {
    if (builder == null) {
        this.builder = new ConfigurationBuilder();
        builder.setScanners(new SubTypesScanner(), new TypeAnnotationsScanner());
    }
    builder.addClassLoader(loader);
    builder.addUrls(ClasspathHelper.forClassLoader(loader));

    if(loader instanceof JoinClassLoader) {
        // When the object "reflections" is created in the method scanClassPath(), are scanned the URLs so
        // it is necessary to add the URLs from the enclosing class loader in the JoinClassLoader that it
        // contains the fixture classpath (see org.reflections.Reflections.scan()).
        builder.addUrls(ClasspathHelper.forClassLoader(((JoinClassLoader) loader).getEnclosingClassLoader()));
    }

    scanClassPath(builder);
}
 
Example #5
Source File: ReflectionsServiceDiscovery.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
public ReflectionsServiceDiscovery(String resourceSearchPackages, JsonServiceLocator locator) {
	this.locator = locator;

	ConfigurationBuilder builder = new ConfigurationBuilder();

	PreconditionUtil.assertNotNull("no resourceSearchPackage configured", resourceSearchPackages);

	FilterBuilder filter = new FilterBuilder();
	for (String resourceSearchPackage : resourceSearchPackages.split(",")) {
		builder = builder.addUrls(ClasspathHelper.forPackage(resourceSearchPackage));
		filter.includePackage(resourceSearchPackage);
	}
	filter.includePackage(Repository.class.getPackage().getName());
	filter.includePackage(ResourceRepository.class.getPackage().getName());
	builder = builder.filterInputsBy(filter);

	builder = builder.addUrls(ClasspathHelper.forClass(Repository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepository.class));
	builder = builder.addUrls(ClasspathHelper.forClass(ResourceRepositoryV2.class));

	builder = builder.setScanners(new SubTypesScanner(false), new TypeAnnotationsScanner());
	reflections = new Reflections(builder);
}
 
Example #6
Source File: ClassloaderScanner.java    From yawp with MIT License 6 votes vote down vote up
private Reflections buildReflections(String packages) {
    String[] packagesArray = packages.replaceAll(" ", "").split(",");

    FilterBuilder filter = new FilterBuilder();

    Set<URL> urls = new HashSet();

    for (String packageStr : packagesArray) {
        urls.addAll(ClasspathHelper.forPackage(packageStr));
        filter.include(FilterBuilder.prefix(packageStr));
    }

    return new Reflections(new ConfigurationBuilder()
            .addUrls(urls)
            .filterInputsBy(filter)
            .setScanners(new TypeAnnotationsScanner(), new SubTypesScanner()));
}
 
Example #7
Source File: JaxRSScanner.java    From swagger-maven-plugin with MIT License 6 votes vote down vote up
Application applicationInstance() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Set<Class<? extends Application>> applicationClasses = reflections.getSubTypesOf(Application.class)
            .stream()
            .filter(this::filterClassByResourcePackages)
            .collect(Collectors.toSet());
    if (applicationClasses.isEmpty()) {
        return null;
    }
    if (applicationClasses.size() > 1) {
        log.warn("More than one javax.ws.rs.core.Application classes found on the classpath, skipping");
        return null;
    }
    return ClassUtils.createInstance(applicationClasses.iterator().next());
}
 
Example #8
Source File: AnnotationStatementScanner.java    From mybatis-jpa with Apache License 2.0 6 votes vote down vote up
public void scan() {
  for (String basePackage : basePackages) {
    Reflections reflections = new Reflections(basePackage, new TypeAnnotationsScanner(),
        new SubTypesScanner(), new MethodAnnotationsScanner());
    Set<Class<?>> mappers = reflections.getTypesAnnotatedWith(Mapper.class);
    for (Class<?> mapperClass : mappers) {
      Method[] methods = mapperClass.getMethods();
      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
          StatementFactory statementFactory = annotationStatementRegistry
              .findFactory(annotation.annotationType());
          if (statementFactory != null) {
            MappedStatement statement = statementFactory.parseStatement(configuration, method, mapperClass);
            configuration.addMappedStatement(statement);
          }
        }

      }
    }
  }
  parsePendingMethods();
}
 
Example #9
Source File: StreamsScalaSourceGenerator.java    From streams with Apache License 2.0 6 votes vote down vote up
/**
 * StreamsScalaSourceGenerator constructor.
 * @param config StreamsScalaGenerationConfig
 */
public StreamsScalaSourceGenerator(StreamsScalaGenerationConfig config) {
  this.config = config;
  this.outDir = config.getTargetDirectory().getAbsolutePath();
  reflections = new Reflections(
      new ConfigurationBuilder()
          // TODO
          .forPackages(
              config.getSourcePackages()
                  .toArray(new String[config.getSourcePackages().size()])
          )
          .setScanners(
              new SubTypesScanner(),
              new TypeAnnotationsScanner()));

}
 
Example #10
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 #11
Source File: MethodStorage.java    From Orienteer with Apache License 2.0 5 votes vote down vote up
public void reload(){
	Reflections reflections = new Reflections(paths,
											  OrienteerClassLoader.getClassLoader(),
											  new MethodAnnotationsScanner(),
											  new TypeAnnotationsScanner(),
											  new SubTypesScanner());
	methodFields = reflections.getMethodsAnnotatedWith(OMethod.class);
	
	methodClasses = reflections.getTypesAnnotatedWith(OMethod.class);
	methodClasses.removeIf(c -> !IMethod.class.isAssignableFrom(c) && !Command.class.isAssignableFrom(c));
}
 
Example #12
Source File: ReflectionScanner.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** scanner which will look in the given urls 
 * (or if those are null attempt to infer from the first entry in the classloaders,
 * although currently that seems to only pick up directories, not JAR's),
 * optionally filtering for the given prefix;
 * any or all arguments can be null to accept all (and use default classpath for classloading).
 **/
public ReflectionScanner(
        final Iterable<URL> urlsToScan, 
        final String optionalPrefix,
        final Predicate<String> filter,
        final ClassLoader ...classLoaders) {
    if (Reflections.log==null) {
        Reflections.log = log;
    }
    reflections = new Reflections(new ConfigurationBuilder() {
        {
            if (urlsToScan!=null)
                setUrls(ImmutableSet.copyOf(urlsToScan));
            else if (classLoaders.length>0 && classLoaders[0]!=null)
                setUrls(
                        ClasspathHelper.forPackage(Strings.isNonEmpty(optionalPrefix) ? optionalPrefix : "",
                                asClassLoaderVarArgs(classLoaders[0])));
            
            if (filter!=null) filterInputsBy(filter);

            Scanner typeScanner = new TypeAnnotationsScanner();
            if (filter!=null) typeScanner = typeScanner.filterResultsBy(filter);
            Scanner subTypeScanner = new SubTypesScanner();
            if (filter!=null) subTypeScanner = subTypeScanner.filterResultsBy(filter);
            setScanners(typeScanner, subTypeScanner);
            
            for (ClassLoader cl: classLoaders)
                if (cl!=null) addClassLoader(cl);
        }
    });
    this.classLoaders = Iterables.toArray(Iterables.filter(Arrays.asList(classLoaders), Predicates.notNull()), ClassLoader.class);
}
 
Example #13
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 #14
Source File: SpiderBeanFactory.java    From gecco with MIT License 5 votes vote down vote up
/**
 * 动态增加的spiderBean
 */
private void dynamic() {
	GeccoClassLoader gcl = GeccoClassLoader.get();
	for (String className : gcl.getClasses().keySet()) {
		reflections.getStore().get(TypeAnnotationsScanner.class.getSimpleName()).put(Gecco.class.getName(),
				className);
	}
}
 
Example #15
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 #16
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 #17
Source File: GUIWriter.java    From niftyeditor with Apache License 2.0 5 votes vote down vote up
public GUIWriter(GUI gui)throws JAXBException, ClassNotFoundException, IOException{
    this.gui = gui;
    Reflections reflections = new Reflections ("jada.ngeditor.model",ClasspathHelper.forClass(GElement.class), 
                         new SubTypesScanner(false), new TypeAnnotationsScanner());
    Set<Class<?>> setXmlRoot = reflections.getTypesAnnotatedWith(XmlRootElement.class);
    Class[] classes = setXmlRoot.toArray(new Class[0]);
    
    JAXBContext jc = JAXBContext.newInstance("jada.ngeditor.model:jada.ngeditor.model.elements:jada.ngeditor.model.elements.specials:jada.ngeditor.model.elements.effects",this.getClass().getClassLoader());       
   
    m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "https://raw.githubusercontent.com/void256/nifty-gui/1.4/nifty-core/src/main/resources/nifty.xsd https://raw.githubusercontent.com/void256/nifty-gui/1.4/nifty-core/src/main/resources/nifty.xsd");
}
 
Example #18
Source File: ClassTools.java    From spring-boot-starter-micro-job with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定package下的接口实现类
 *
 * @param scannerPackage 扫描的package
 * @return 实现类集合
 */
public static Set<Class<? extends JobTrigger>> getJobs(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    Reflections reflections = new Reflections(scannerPackage);
    return reflections.getSubTypesOf(JobTrigger.class);
}
 
Example #19
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 #20
Source File: JaxRSScanner.java    From swagger-maven-plugin with MIT License 5 votes vote down vote up
Set<Class<?>> classes() {
    ConfigurationBuilder config = ConfigurationBuilder
            .build(resourcePackages)
            .setScanners(new ResourcesScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
    Reflections reflections = new Reflections(config);
    Stream<Class<?>> apiClasses = reflections.getTypesAnnotatedWith(Path.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    Stream<Class<?>> defClasses = reflections.getTypesAnnotatedWith(OpenAPIDefinition.class)
            .stream()
            .filter(this::filterClassByResourcePackages);
    return Stream.concat(apiClasses, defClasses).collect(Collectors.toSet());
}
 
Example #21
Source File: ClassTools.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化反射对象
 *
 * @param scannerPackage 扫描的package
 * @return 反射对象
 */
static Reflections initReflections(String scannerPackage) {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setScanners(new TypeAnnotationsScanner(), new SubTypesScanner());
    configurationBuilder.filterInputsBy(new FilterBuilder().includePackage(scannerPackage));
    configurationBuilder.addUrls(ClasspathHelper.forPackage(scannerPackage));
    return new Reflections(scannerPackage);
}
 
Example #22
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());
}
 
Example #23
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 #24
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 #25
Source File: PluginManager.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<String> scan(final Class<? extends Annotation> annotation) {
    Iterable<String> annotated = store.get(TypeAnnotationsScanner.class.getSimpleName(), annotation.getName());
    return getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), false);
}
 
Example #26
Source File: JarManagerService.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public Iterable<String> scan(final Class<? extends Annotation> annotation) {
    Iterable<String> annotated = store.get(TypeAnnotationsScanner.class.getSimpleName(), annotation.getName());
    return getAllAnnotated(annotated, annotation.isAnnotationPresent(Inherited.class), false);
}
 
Example #27
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 4 votes vote down vote up
public synchronized TestRunResult run()
        throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
        InterruptedException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // The DNS resolver is not really a per sinttest run setting. It is not even a per connection setting. Instead
    // it is a global setting, but we treat it like a per sinttest run setting.
    switch (config.dnsResolver) {
    case minidns:
        MiniDnsResolver.setup();
        break;
    case javax:
        JavaxResolver.setup();
        break;
    case dnsjava:
        DNSJavaResolver.setup();
        break;
    }
    testRunResult = new TestRunResult();

    // Create a connection manager *after* we created the testRunId (in testRunResult).
    this.connectionManager = new XmppConnectionManager(this);

    LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId + ']' + ": Starting\nSmack version: " + SmackConfiguration.getVersion());
    if (config.debugger != Configuration.Debugger.none) {
        // JUL Debugger will not print any information until configured to print log messages of
        // level FINE
        // TODO configure JUL for log?
        SmackConfiguration.addDisabledSmackClass("org.jivesoftware.smack.debugger.JulDebugger");
        SmackConfiguration.DEBUG = true;
    }
    if (config.replyTimeout > 0) {
        SmackConfiguration.setDefaultReplyTimeout(config.replyTimeout);
    }
    if (config.securityMode != SecurityMode.required && config.accountRegistration == AccountRegistration.inBandRegistration) {
        AccountManager.sensitiveOperationOverInsecureConnectionDefault(true);
    }
    // TODO print effective configuration

    String[] testPackages;
    if (config.testPackages == null || config.testPackages.isEmpty()) {
        testPackages = new String[] { "org.jivesoftware.smackx", "org.jivesoftware.smack" };
    }
    else {
        testPackages = config.testPackages.toArray(new String[config.testPackages.size()]);
    }
    Reflections reflections = new Reflections(testPackages, new SubTypesScanner(),
                    new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new MethodParameterScanner());
    Set<Class<? extends AbstractSmackIntegrationTest>> inttestClasses = reflections.getSubTypesOf(AbstractSmackIntegrationTest.class);
    Set<Class<? extends AbstractSmackLowLevelIntegrationTest>> lowLevelInttestClasses = reflections.getSubTypesOf(AbstractSmackLowLevelIntegrationTest.class);

    Set<Class<? extends AbstractSmackIntTest>> classes = new HashSet<>(inttestClasses.size()
                    + lowLevelInttestClasses.size());
    classes.addAll(inttestClasses);
    classes.addAll(lowLevelInttestClasses);

    {
        // Remove all abstract classes.
        // TODO: This may be a good candidate for Java stream filtering once Smack is Android API 24 or higher.
        Iterator<Class<? extends AbstractSmackIntTest>> it = classes.iterator();
        while (it.hasNext()) {
            Class<? extends AbstractSmackIntTest> clazz = it.next();
            if (Modifier.isAbstract(clazz.getModifiers())) {
                it.remove();
            }
        }
    }

    if (classes.isEmpty()) {
        throw new IllegalStateException("No test classes found");
    }

    LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId
                    + "]: Finished scanning for tests, preparing environment");
    environment = prepareEnvironment();

    try {
        runTests(classes);
    }
    catch (Throwable t) {
        // Log the thrown Throwable to prevent it being shadowed in case the finally block below also throws.
        LOGGER.log(Level.SEVERE, "Unexpected abort because runTests() threw throwable", t);
        throw t;
    }
    finally {
        // Ensure that the accounts are deleted and disconnected before we continue
        connectionManager.disconnectAndCleanup();
    }

    return testRunResult;
}
 
Example #28
Source File: BrainFactory.java    From spring-boot-chatbot with MIT License 4 votes vote down vote up
private Reflections findPackage(String packageName) {
    return new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packageName)).setScanners(
                    new TypeAnnotationsScanner(), new SubTypesScanner()));
}
 
Example #29
Source File: DefaultEbeanConfig.java    From play-ebean with Apache License 2.0 3 votes vote down vote up
/**
 * Create {@link org.reflections.Configuration} object for given package name and class loader.
 *
 * @param packageName the root package to scan
 * @param classLoader class loader to be used in reflections
 * @return the configuration builder
 */
private static ConfigurationBuilder getReflectionsConfiguration(String packageName, ClassLoader classLoader) {
    return new ConfigurationBuilder()
            .addUrls(ClasspathHelper.forPackage(packageName, classLoader))
            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(packageName + ".")))
            .setScanners(new TypeElementsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner());
}