Search in sources :

Example 36 with Executable

use of java.lang.reflect.Executable in project spring-framework by spring-projects.

the class SpringExtension method supportsParameter.

/**
 * Determine if the value for the {@link Parameter} in the supplied {@link ParameterContext}
 * should be autowired from the test's {@link ApplicationContext}.
 * <p>A parameter is considered to be autowirable if one of the following
 * conditions is {@code true}.
 * <ol>
 * <li>The {@linkplain ParameterContext#getDeclaringExecutable() declaring
 * executable} is a {@link Constructor} and
 * {@link TestConstructorUtils#isAutowirableConstructor(Constructor, Class, PropertyProvider)}
 * returns {@code true}. Note that {@code isAutowirableConstructor()} will be
 * invoked with a fallback {@link PropertyProvider} that delegates its lookup
 * to {@link ExtensionContext#getConfigurationParameter(String)}.</li>
 * <li>The parameter is of type {@link ApplicationContext} or a sub-type thereof.</li>
 * <li>The parameter is of type {@link ApplicationEvents} or a sub-type thereof.</li>
 * <li>{@link ParameterResolutionDelegate#isAutowirable} returns {@code true}.</li>
 * </ol>
 * <p><strong>WARNING</strong>: If a test class {@code Constructor} is annotated
 * with {@code @Autowired} or automatically autowirable (see {@link TestConstructor}),
 * Spring will assume the responsibility for resolving all parameters in the
 * constructor. Consequently, no other registered {@link ParameterResolver}
 * will be able to resolve parameters.
 * @see #resolveParameter
 * @see TestConstructorUtils#isAutowirableConstructor(Constructor, Class)
 * @see ParameterResolutionDelegate#isAutowirable
 */
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
    Parameter parameter = parameterContext.getParameter();
    Executable executable = parameter.getDeclaringExecutable();
    Class<?> testClass = extensionContext.getRequiredTestClass();
    PropertyProvider junitPropertyProvider = propertyName -> extensionContext.getConfigurationParameter(propertyName).orElse(null);
    return (TestConstructorUtils.isAutowirableConstructor(executable, testClass, junitPropertyProvider) || ApplicationContext.class.isAssignableFrom(parameter.getType()) || supportsApplicationEvents(parameterContext) || ParameterResolutionDelegate.isAutowirable(parameter, parameterContext.getIndex()));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) PropertyProvider(org.springframework.test.context.support.PropertyProvider) Autowired(org.springframework.beans.factory.annotation.Autowired) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) ParameterResolutionDelegate(org.springframework.beans.factory.annotation.ParameterResolutionDelegate) Constructor(java.lang.reflect.Constructor) AfterAll(org.junit.jupiter.api.AfterAll) AfterEachCallback(org.junit.jupiter.api.extension.AfterEachCallback) MergedAnnotations(org.springframework.core.annotation.MergedAnnotations) BeforeAll(org.junit.jupiter.api.BeforeAll) Parameter(java.lang.reflect.Parameter) Executable(java.lang.reflect.Executable) Nullable(org.springframework.lang.Nullable) Method(java.lang.reflect.Method) Namespace(org.junit.jupiter.api.extension.ExtensionContext.Namespace) SearchStrategy(org.springframework.core.annotation.MergedAnnotations.SearchStrategy) TestContextManager(org.springframework.test.context.TestContextManager) TestConstructor(org.springframework.test.context.TestConstructor) MethodFilter(org.springframework.util.ReflectionUtils.MethodFilter) AfterTestExecutionCallback(org.junit.jupiter.api.extension.AfterTestExecutionCallback) Store(org.junit.jupiter.api.extension.ExtensionContext.Store) ApplicationContext(org.springframework.context.ApplicationContext) BeforeTestExecutionCallback(org.junit.jupiter.api.extension.BeforeTestExecutionCallback) ParameterContext(org.junit.jupiter.api.extension.ParameterContext) RepeatableContainers(org.springframework.core.annotation.RepeatableContainers) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) BeforeAllCallback(org.junit.jupiter.api.extension.BeforeAllCallback) AfterAllCallback(org.junit.jupiter.api.extension.AfterAllCallback) ReflectionUtils(org.springframework.util.ReflectionUtils) Modifier(java.lang.reflect.Modifier) Annotation(java.lang.annotation.Annotation) BeforeEachCallback(org.junit.jupiter.api.extension.BeforeEachCallback) Testable(org.junit.platform.commons.annotation.Testable) ApplicationEvents(org.springframework.test.context.event.ApplicationEvents) TestConstructorUtils(org.springframework.test.context.support.TestConstructorUtils) ParameterResolver(org.junit.jupiter.api.extension.ParameterResolver) TestInstancePostProcessor(org.junit.jupiter.api.extension.TestInstancePostProcessor) Assert(org.springframework.util.Assert) PropertyProvider(org.springframework.test.context.support.PropertyProvider) Parameter(java.lang.reflect.Parameter) Executable(java.lang.reflect.Executable)

Example 37 with Executable

use of java.lang.reflect.Executable in project Payara by payara.

the class AnnotationReader method compute.

private <R> R compute(InjectionPoint point, AnnotatedParameter<?> parameter, BiFunction<T, String, R> func) {
    // NB: This is a workaround as arquillians InjectionPoint implementation for parameters does return null for getJavaParameter
    Executable annotated = (Executable) point.getMember();
    Member member = new MemberParameter(annotated.getParameters()[parameter.getPosition()]);
    return compute(member.getDeclaringClass(), member, parameter::getAnnotation, func);
}
Also used : Executable(java.lang.reflect.Executable) AnnotatedMember(javax.enterprise.inject.spi.AnnotatedMember) Member(java.lang.reflect.Member)

Example 38 with Executable

use of java.lang.reflect.Executable in project bayou by capergroup.

the class Enumerator method enumerate.

private TypedExpression enumerate(SearchTarget target, int argDepth, List<Variable> toSearch) {
    Enumerator enumerator = new Enumerator(ast, env, mode);
    Type targetType = target.getType();
    // if a predefined constant exists for this type, just use it
    if (env.predefinedConstants.hasPredefinedConstant(targetType.C()))
        return env.predefinedConstants.getTypedExpression(targetType.C(), ast);
    /* first, see if we can create a new object of target type directly */
    List<Executable> constructors = new ArrayList<>(Arrays.asList(targetType.C().getConstructors()));
    /* static methods that return the target type are considered "constructors" here */
    for (Method m : targetType.C().getMethods()) if (Modifier.isStatic(m.getModifiers()) && targetType.isAssignableFrom(m.getReturnType()))
        constructors.add(m);
    sortExecutablesByCost(constructors);
    List<TypedExpression> candidates = new ArrayList<>();
    for (Executable constructor : constructors) {
        if (Modifier.isAbstract(targetType.C().getModifiers()) || Modifier.isInterface(targetType.C().getModifiers())) {
            for (Object o : env.reflections.getSubTypesOf(targetType.C())) {
                TypedExpression tExpr = enumerator.enumerate(new SearchTarget(new Type((Class) o)), argDepth, toSearch);
                if (tExpr != null) {
                    // concretize the type before finalizing candidate
                    tExpr.getType().concretizeType(env);
                    candidates.add(tExpr);
                }
            }
            break;
        }
        if (!Modifier.isPublic(constructor.getModifiers()))
            continue;
        if (constructor instanceof Constructor) {
            /* an actual constructor */
            ClassInstanceCreation creation = ast.newClassInstanceCreation();
            TypedExpression tExpr = new TypedExpression(creation, targetType);
            creation.setType(ast.newSimpleType(ast.newSimpleName(targetType.C().getSimpleName())));
            int i;
            for (i = 0; i < constructor.getParameterCount(); i++) {
                Class argType = constructor.getParameterTypes()[i];
                String name = constructor.getParameters()[i].getName();
                SearchTarget newTarget = new SearchTarget(new Type(argType)).setAPICallName(constructor.getName()).setParamName(name).setSingleUseVariable(true);
                TypedExpression tArg = enumerator.search(newTarget, argDepth + 1);
                if (tArg == null)
                    break;
                tExpr.addReferencedVariables(tArg.getReferencedVariables());
                tExpr.addAssociatedImports(tArg.getAssociatedImports());
                creation.arguments().add(tArg.getExpression());
            }
            if (i == constructor.getParameterCount()) {
                tExpr.addAssociatedImport(targetType.C());
                candidates.add(tExpr);
            }
        } else {
            /* a static method that returns the object type */
            MethodInvocation invocation = ast.newMethodInvocation();
            TypedExpression tExpr = new TypedExpression(invocation, targetType);
            int i;
            invocation.setExpression(ast.newSimpleName(targetType.C().getSimpleName()));
            invocation.setName(ast.newSimpleName(constructor.getName()));
            for (i = 0; i < constructor.getParameterCount(); i++) {
                Class argType = constructor.getParameterTypes()[i];
                String name = constructor.getParameters()[i].getName();
                SearchTarget newTarget = new SearchTarget(new Type(argType)).setAPICallName(constructor.getName()).setParamName(name).setSingleUseVariable(true);
                TypedExpression tArg = enumerator.search(newTarget, argDepth + 1);
                if (tArg == null)
                    break;
                tExpr.addReferencedVariables(tArg.getReferencedVariables());
                tExpr.addAssociatedImports(tArg.getAssociatedImports());
                invocation.arguments().add(tArg.getExpression());
            }
            if (i == constructor.getParameterCount()) {
                tExpr.addAssociatedImport(targetType.C());
                candidates.add(tExpr);
            }
        }
    }
    if (!candidates.isEmpty()) {
        // sort according to cost heuristic and get the top-most one
        sortTypedExpressionsByCost(candidates);
        TypedExpression retExpr = candidates.get(0);
        // remove all $ variables added by OTHER candidates
        for (int i = 1; i < candidates.size(); i++) for (Variable var : candidates.get(i).getReferencedVariables()) if (var.isDefaultInit() && var.getRefCount() == 0)
            env.removeVariable(var);
        return retExpr;
    }
    if (mode == Synthesizer.Mode.CONDITIONAL_PROGRAM_GENERATOR) {
        return null;
    }
    /* otherwise, start recursive search for expression of target type */
    List<ExpressionChain> chains = new ArrayList<>();
    for (Variable var : toSearch) chains.addAll(searchForChains(targetType, var));
    sortChainsByCost(chains);
    int i, j;
    for (ExpressionChain chain : chains) {
        /* for each chain, see if we can synthesize all arguments in all methods in the chain */
        MethodInvocation invocation = ast.newMethodInvocation();
        Expression expr = chain.var.createASTNode(ast);
        Set<Variable> referencedVariables = new HashSet<>();
        Set<Class> associatedImports = new HashSet<>();
        for (i = 0; i < chain.methods.size(); i++) {
            Method m = chain.methods.get(i);
            invocation.setExpression(expr);
            invocation.setName(ast.newSimpleName(m.getName()));
            for (j = 0; j < m.getParameterCount(); j++) {
                Class argType = m.getParameterTypes()[j];
                String name = m.getParameters()[j].getName();
                SearchTarget newTarget = new SearchTarget(new Type(argType)).setAPICallName(m.getName()).setParamName(name).setSingleUseVariable(true);
                TypedExpression tArg;
                try {
                    tArg = enumerator.search(newTarget, argDepth + 1);
                } catch (SynthesisException e) {
                    // could not synthesize some argument, ignore this chain
                    break;
                }
                if (tArg == null)
                    break;
                referencedVariables.addAll(tArg.getReferencedVariables());
                associatedImports.addAll(tArg.getAssociatedImports());
                invocation.arguments().add(tArg.getExpression());
            }
            if (j != m.getParameterCount())
                break;
            expr = invocation;
            invocation = ast.newMethodInvocation();
        }
        if (i == chain.methods.size()) {
            return new TypedExpression(expr, targetType).addReferencedVariables(referencedVariables).addAssociatedImports(associatedImports);
        }
    }
    return null;
}
Also used : Constructor(java.lang.reflect.Constructor) Method(java.lang.reflect.Method) Executable(java.lang.reflect.Executable)

Example 39 with Executable

use of java.lang.reflect.Executable in project SpongeCommon by SpongePowered.

the class InjectionPointProvider method findInjectionPoint.

@Nullable
private static SpongeInjectionPoint findInjectionPoint(final List<com.google.inject.spi.DependencyAndSource> dependencyChain) {
    if (dependencyChain.size() < 3) {
        throw new AssertionError("Provider is not included in the dependency chain");
    }
    // @Inject InjectionPoint is the last, so we can skip it
    for (int i = dependencyChain.size() - 2; i >= 0; i--) {
        final Dependency<?> dependency = dependencyChain.get(i).getDependency();
        if (dependency == null) {
            return null;
        }
        final com.google.inject.spi.InjectionPoint spiInjectionPoint = dependency.getInjectionPoint();
        if (spiInjectionPoint != null) {
            final Type source = spiInjectionPoint.getDeclaringType().getType();
            final Member member = spiInjectionPoint.getMember();
            if (member instanceof Field) {
                final Field field = (Field) member;
                return new SpongeInjectionPoint(source, field.getGenericType(), field.getAnnotations());
            } else if (member instanceof Executable) {
                final Executable executable = (Executable) member;
                final Annotation[][] parameterAnnotations = executable.getParameterAnnotations();
                final Type[] parameterTypes = executable.getGenericParameterTypes();
                final int index = dependency.getParameterIndex();
                return new SpongeInjectionPoint(source, parameterTypes[index], parameterAnnotations[index]);
            } else {
                throw new IllegalStateException("Unsupported Member type: " + member.getClass().getName());
            }
        }
    }
    return null;
}
Also used : Annotation(java.lang.annotation.Annotation) Field(java.lang.reflect.Field) Type(java.lang.reflect.Type) Executable(java.lang.reflect.Executable) Member(java.lang.reflect.Member) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Aggregations

Executable (java.lang.reflect.Executable)39 Method (java.lang.reflect.Method)14 Constructor (java.lang.reflect.Constructor)9 Parameter (java.lang.reflect.Parameter)8 Field (java.lang.reflect.Field)6 Member (java.lang.reflect.Member)5 Annotation (java.lang.annotation.Annotation)4 List (java.util.List)4 AnalysisField (com.oracle.graal.pointsto.meta.AnalysisField)2 CEntryPointOptions (com.oracle.svm.core.c.function.CEntryPointOptions)2 JNIAccessibleMethodDescriptor (com.oracle.svm.jni.access.JNIAccessibleMethodDescriptor)2 AnnotatedType (java.lang.reflect.AnnotatedType)2 TypeVariable (java.lang.reflect.TypeVariable)2 Arrays (java.util.Arrays)2 HashSet (java.util.HashSet)2 Nullable (javax.annotation.Nullable)2 AnnotatedParameter (javax.enterprise.inject.spi.AnnotatedParameter)2 Named (javax.inject.Named)2 ResolvedJavaMethod (jdk.vm.ci.meta.ResolvedJavaMethod)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2