org.reflections.scanners.MethodParameterScanner Java Examples

The following examples show how to use org.reflections.scanners.MethodParameterScanner. 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: HttpRequestParamsValidateManager.java    From common-project with Apache License 2.0 5 votes vote down vote up
public Set<String> getConfigs() {
    Set<String> configs = new HashSet<>();
    Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage(pacakgePath)).setScanners(new MethodParameterScanner()));
    Set<Method> methodsAnnotatedWith = reflections.getMethodsWithAnyParamAnnotated(ParamsValidate.class);
    Iterator<Method> it = methodsAnnotatedWith.iterator();
    while (it.hasNext()) {
        Method method = it.next();
        String classAndMethod = method.getDeclaringClass().getCanonicalName() + "." + method.getName();
        //生成expression配置
        String expression = "execution (* " + classAndMethod + "(..))";
        configs.add(expression);
    }
    return configs;
}
 
Example #2
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 #3
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 #4
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 #5
Source File: ReflectionsApp.java    From tutorials with MIT License 4 votes vote down vote up
public Set<Method> getMethodsWithDateParam() {
    Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
    Set<Method> methodsSet = reflections.getMethodsMatchParams(Date.class);
    return methodsSet;
}
 
Example #6
Source File: ReflectionsApp.java    From tutorials with MIT License 4 votes vote down vote up
public Set<Method> getMethodsWithVoidReturn() {
    Reflections reflections = new Reflections(java.text.SimpleDateFormat.class, new MethodParameterScanner());
    Set<Method> methodsSet = reflections.getMethodsReturn(void.class);
    return methodsSet;
}