org.reflections.scanners.MethodAnnotationsScanner Java Examples

The following examples show how to use org.reflections.scanners.MethodAnnotationsScanner. 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: DataScopeSqlConfigService.java    From smart-admin with MIT License 7 votes vote down vote up
/**
 * 刷新 所有添加数据范围注解的接口方法配置<class.method,DataScopeSqlConfigDTO></>
 *
 * @return
 */
private Map<String, DataScopeSqlConfigDTO> refreshDataScopeMethodMap() {
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(scanPackage)).setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(DataScope.class);
    for (Method method : methods) {
        DataScope dataScopeAnnotation = method.getAnnotation(DataScope.class);
        if (dataScopeAnnotation != null) {
            DataScopeSqlConfigDTO configDTO = new DataScopeSqlConfigDTO();
            configDTO.setDataScopeType(dataScopeAnnotation.dataScopeType().getType());
            configDTO.setJoinSql(dataScopeAnnotation.joinSql());
            configDTO.setWhereIndex(dataScopeAnnotation.whereIndex());
            dataScopeMethodMap.put(method.getDeclaringClass().getSimpleName() + "." + method.getName(), configDTO);
        }
    }
    return dataScopeMethodMap;
}
 
Example #2
Source File: ExoTransactionRouter.java    From exo-demo with MIT License 6 votes vote down vote up
/**
 * Scans a package, e.g. "com.txmq.exo.messaging.rest" for 
 * @ExoTransaction annotations using reflection and sets up the
 * internal mapping of transaction type to processing method.
 */
public ExoTransactionRouter addPackage(String transactionPackage) {
	/*
	Reflections reflections = new Reflections(new ConfigurationBuilder()
	     .setUrls(ClasspathHelper.forPackage(transactionPackage))
	     .setScanners(new MethodAnnotationsScanner())
	);*/
	Reflections reflections = new Reflections(transactionPackage, new MethodAnnotationsScanner());			
	
	Set<Method> methods = reflections.getMethodsAnnotatedWith(ExoTransaction.class);
	for (Method method : methods) {
		ExoTransaction annotation = method.getAnnotation(ExoTransaction.class);
		this.transactionMap.put(annotation.value(), method);
	}
	
	return this;
}
 
Example #3
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 #4
Source File: AnnotationUrlProvider.java    From play-sitemap-module.edulify.com with Apache License 2.0 6 votes vote down vote up
@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);
    }
  }
}
 
Example #5
Source File: StepFormatter.java    From akita with Apache License 2.0 6 votes vote down vote up
/**
 * Метод осуществляет снятие скришота и прикрепление его к cucumber отчету.
 * Скриншот снимается после шагов, помеченных аннотацией @Screenshot,
 * либо после каждого шага, если задана системная переменная takeScreenshotAfterSteps=true
 * @param testStep - текущий шаг
 *
 */
private void afterStep(TestStep testStep) {
    String fullMethodLocation = testStep.getCodeLocation();
    String currentMethodName = fullMethodLocation.substring(fullMethodLocation.indexOf('.') + 1, fullMethodLocation.indexOf('('));

    List<Method> methodsWithScreenshotAnnotation = new Reflections(new MethodAnnotationsScanner())
        .getMethodsAnnotatedWith(Screenshot.class)
        .stream()
        .filter(m -> m.getName().contains(currentMethodName))
        .collect(Collectors.toList());

    boolean isScreenshotAnnotationPresent = methodsWithScreenshotAnnotation.size() > 0;

    boolean isTakeScreenshotAfterStepsProperty = System.getProperty(SCREENSHOT_AFTER_STEPS) != null
        ? Boolean.valueOf(System.getProperty(SCREENSHOT_AFTER_STEPS)) : false;

    if (isScreenshotAnnotationPresent || isTakeScreenshotAfterStepsProperty) {
        final byte[] screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.BYTES);
        AkitaScenario.getInstance().getScenario().embed(screenshot, "image/png");
    }
}
 
Example #6
Source File: UniqueTestMethodNameTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
/**
 * As we are using test method names as tags on cloud resources, we must be sure that they are unique.
 */
@Test
public void testMethodNamesShouldBeUnique() {
    Reflections reflections = new Reflections(UniqueTestMethodNameTest.class.getPackageName(), new MethodAnnotationsScanner());
    Map<String, List<Method>> methodsByName = reflections.getMethodsAnnotatedWith(Test.class).stream()
            .collect(Collectors.groupingBy(Method::getName));

    String errorMessage = methodsByName.entrySet()
            .stream()
            .filter(methodsEntry -> methodsEntry.getValue().size() > 1)
            .map(methodsEntry -> getErrorMessage(methodsEntry.getKey(), methodsEntry.getValue()))
            .collect(Collectors.joining(System.lineSeparator()));

    if (!errorMessage.isEmpty()) {
        fail(errorMessage);
    }
}
 
Example #7
Source File: BeanAggregateAutoConfiguration.java    From spring-boot-data-aggregator with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public DataBeanAggregateService dataBeanAggregateQueryService (
        @Qualifier("dataProviderRepository") DataProviderRepository dataProviderRepository) {
    if(properties.getBasePackages() != null) {
        Map<String,Set<String>> provideDependMap = new HashMap<>(64);
        for (String basePackage : properties.getBasePackages()) {
            Reflections reflections = new Reflections(basePackage, new MethodAnnotationsScanner());
            Set<Method> providerMethods = reflections.getMethodsAnnotatedWith(DataProvider.class);
            for (Method method : providerMethods) {
                DataProvider beanProvider = AnnotationUtils.findAnnotation(method, DataProvider.class);
                @SuppressWarnings("ConstantConditions")
                String dataId = beanProvider.id();
                Assert.isTrue(Modifier.isPublic(method.getModifiers()),"data provider method must be public");
                Assert.isTrue(! StringUtils.isEmpty(dataId),"data id must be not null!");
                DataProvideDefinition provider = DefinitionUtils.getProvideDefinition(method);

                provider.setId(dataId);
                provider.setIdempotent(beanProvider.idempotent());
                provider.setTimeout(beanProvider.timeout() > 0 ? beanProvider.timeout() : properties.getDefaultTimeout());
                Assert.isTrue(! dataProviderRepository.contains(dataId), "Data providers with the same name are not allowed. dataId: " + dataId);
                provideDependMap.put(dataId,provider.getDepends().stream().map(DataConsumeDefinition::getId).collect(Collectors.toSet()));
                dataProviderRepository.put(provider);
            }
        }
        checkCycle(provideDependMap);
    }

    DataBeanAggregateServiceImpl service = new DataBeanAggregateServiceImpl();
    RuntimeSettings runtimeSettings = new RuntimeSettings();
    runtimeSettings.setIgnoreException(properties.isIgnoreException());
    runtimeSettings.setTimeout(properties.getDefaultTimeout());
    service.setRepository(dataProviderRepository);
    service.setRuntimeSettings(runtimeSettings);
    service.setExecutorService(aggregateExecutorService());
    service.setInterceptorChain(aggregateQueryInterceptorChain());
    service.setTaskWrapperClazz(properties.getTaskWrapperClass());
    service.setApplicationContext(applicationContext);
    return service;
}
 
Example #8
Source File: TestRunner.java    From at.info-knowledge-base with MIT License 5 votes vote down vote up
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;
}
 
Example #9
Source File: AbstractAssertTestsClass.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
@Test
public void checkTestClasses(){
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(getPackageName()))
            .setScanners(new MethodAnnotationsScanner()));
    Set<Method> methods = reflections.getMethodsAnnotatedWith(Test.class);
    Set<Class<?>> s = new HashSet<>();
    for(Method m : methods){
        s.add(m.getDeclaringClass());
    }

    List<Class<?>> l = new ArrayList<>(s);
    Collections.sort(l, new Comparator<Class<?>>() {
        @Override
        public int compare(Class<?> aClass, Class<?> t1) {
            return aClass.getName().compareTo(t1.getName());
        }
    });

    int count = 0;
    for(Class<?> c : l){
        if(!getBaseClass().isAssignableFrom(c) && !getExclusions().contains(c)){
            log.error("Test {} does not extend {} (directly or indirectly). All tests must extend this class for proper memory tracking and timeouts",
                    c, getBaseClass());
            count++;
        }
    }
    assertEquals("Number of tests not extending BaseND4JTest", 0, count);
}
 
Example #10
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 #11
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 #12
Source File: GlobalContext.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If you're creating a GlobalContext object and it's not part of a TestCase
 * you're not doing it correctly, GlobalContext is a Singleton
 */
protected GlobalContext() {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("org.drftpd"))
            .setScanners(new MethodAnnotationsScanner()));

    hooksMethods = reflections.getMethodsAnnotatedWith(CommandHook.class);
    logger.debug("We have annotated (found) [{}] hook methods", hooksMethods.size());
}
 
Example #13
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 #14
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 #15
Source File: GlobalContext.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If you're creating a GlobalContext object and it's not part of a TestCase
 * you're not doing it correctly, GlobalContext is a Singleton
 */
protected GlobalContext() {
    Reflections reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage("org.drftpd"))
            .setScanners(new MethodAnnotationsScanner()));

    hooksMethods = reflections.getMethodsAnnotatedWith(CommandHook.class);
    logger.debug("We have annotated (found) [{}] hook methods", hooksMethods.size());
}
 
Example #16
Source File: CustomProviderVerifier.java    From code-examples with MIT License 5 votes vote down vote up
@Override
public boolean verifyResponseByInvokingProviderMethods(ProviderInfo providerInfo, ConsumerInfo consumer,
																											 Object interaction, String interactionMessage, Map failures) {
	try {

		ConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
						.setScanners(new MethodAnnotationsScanner())
						.forPackages(packagesToScan.toArray(new String[]{}));

		Reflections reflections = new Reflections(configurationBuilder);
		Set<Method> methodsAnnotatedWith = reflections.getMethodsAnnotatedWith(PactVerifyProvider.class);
		Set<Method> providerMethods = methodsAnnotatedWith.stream()
						.filter(m -> {
							PactVerifyProvider annotation = m.getAnnotation(PactVerifyProvider.class);
							return annotation.value().equals(((Interaction)interaction).getDescription());
						})
						.collect(Collectors.toSet());

		if (providerMethods.isEmpty()) {
			throw new RuntimeException("No annotated methods were found for interaction " +
							"'${interaction.description}'. You need to provide a method annotated with " +
							"@PactVerifyProvider(\"${interaction.description}\") that returns the message contents.");
		} else {
			if (interaction instanceof Message) {
				verifyMessagePact(providerMethods, (Message) interaction, interactionMessage, failures);
			} else {
				throw new RuntimeException("only supports Message interactions!");
			}
		}
	} catch (Exception e) {
		throw new RuntimeException("verification failed", e);
	}
	return true;
}
 
Example #17
Source File: AnnotationHandlerImpl.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
@Override
public Set<Method> findFunctions(final List<URL> urls) {
    return new Reflections(
            new ConfigurationBuilder()
                    .addUrls(urls)
                    .setScanners(new MethodAnnotationsScanner())
                    .addClassLoader(getClassLoader(urls)))
            .getMethodsAnnotatedWith(FunctionName.class);
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: ReflectionsApp.java    From tutorials with MIT License 4 votes vote down vote up
public Set<Method> getDateDeprecatedMethods() {
    Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
    Set<Method> deprecatedMethodsSet = reflections.getMethodsAnnotatedWith(Deprecated.class);
    return deprecatedMethodsSet;
}
 
Example #23
Source File: ReflectionsApp.java    From tutorials with MIT License 4 votes vote down vote up
@SuppressWarnings("rawtypes")
public Set<Constructor> getDateDeprecatedConstructors() {
    Reflections reflections = new Reflections(java.util.Date.class, new MethodAnnotationsScanner());
    Set<Constructor> constructorsSet = reflections.getConstructorsAnnotatedWith(Deprecated.class);
    return constructorsSet;
}