Search in sources :

Example 1 with AnnotatedMethod

use of jakarta.enterprise.inject.spi.AnnotatedMethod in project core by weld.

the class QualifierInstance method createValues.

private static Map<String, Object> createValues(final Annotation instance, final MetaAnnotationStore store) {
    final Class<? extends Annotation> annotationClass = instance.annotationType();
    final QualifierModel<? extends Annotation> model = store.getBindingTypeModel(annotationClass);
    if (model.getAnnotatedAnnotation().getMethods().size() == 0) {
        return Collections.emptyMap();
    }
    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();
    for (final AnnotatedMethod<?> method : model.getAnnotatedAnnotation().getMethods()) {
        if (!model.getNonBindingMembers().contains(method)) {
            try {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(SetAccessibleAction.of(method.getJavaMember()));
                } else {
                    method.getJavaMember().setAccessible(true);
                }
                builder.put(method.getJavaMember().getName(), method.getJavaMember().invoke(instance));
            } catch (IllegalArgumentException e) {
                // it may happen that we are in EAR and have stored the annotation's method from different WAR class loader
                // an invocation will then lead to IAE, we can re-try with reflection
                Method[] methods;
                builder = ImmutableMap.builder();
                if (System.getSecurityManager() != null) {
                    methods = AccessController.doPrivileged(new GetDeclaredMethodsAction(annotationClass));
                } else {
                    methods = annotationClass.getDeclaredMethods();
                }
                for (Method m : methods) {
                    if (m.getAnnotation(Nonbinding.class) == null) {
                        try {
                            builder.put(m.getName(), m.invoke(instance));
                        } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ex) {
                            throw ResolutionLogger.LOG.cannotCreateQualifierInstanceValues(instance, Formats.formatAsStackTraceElement(method.getJavaMember()), ex);
                        }
                    }
                }
            } catch (InvocationTargetException | IllegalAccessException e) {
                throw ResolutionLogger.LOG.cannotCreateQualifierInstanceValues(instance, Formats.formatAsStackTraceElement(method.getJavaMember()), e);
            }
        }
    }
    return builder.build();
}
Also used : AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Method(java.lang.reflect.Method) ImmutableMap(org.jboss.weld.util.collections.ImmutableMap) InvocationTargetException(java.lang.reflect.InvocationTargetException) GetDeclaredMethodsAction(org.jboss.weld.security.GetDeclaredMethodsAction)

Example 2 with AnnotatedMethod

use of jakarta.enterprise.inject.spi.AnnotatedMethod in project core by weld.

the class ObserverMethodConfiguratorImpl method read.

@Override
public ObserverMethodConfigurator<T> read(AnnotatedMethod<?> method) {
    checkArgumentNotNull(method);
    Set<AnnotatedParameter<?>> eventParameters = method.getParameters().stream().filter((p) -> p.isAnnotationPresent(Observes.class) || p.isAnnotationPresent(ObservesAsync.class)).collect(Collectors.toSet());
    checkEventParams(eventParameters, method.getJavaMember());
    AnnotatedParameter<?> eventParameter = eventParameters.iterator().next();
    Observes observesAnnotation = eventParameter.getAnnotation(Observes.class);
    if (observesAnnotation != null) {
        reception(observesAnnotation.notifyObserver());
        transactionPhase(observesAnnotation.during());
        async(false);
    } else {
        reception(eventParameter.getAnnotation(ObservesAsync.class).notifyObserver());
        async(true);
    }
    Priority priority = method.getAnnotation(Priority.class);
    if (priority != null) {
        priority(priority.value());
    }
    beanClass(eventParameter.getDeclaringCallable().getDeclaringType().getJavaClass());
    observedType(eventParameter.getBaseType());
    qualifiers(Configurators.getQualifiers(eventParameter));
    return this;
}
Also used : EventLogger(org.jboss.weld.logging.EventLogger) Observes(jakarta.enterprise.event.Observes) ObserverMethodConfigurator(jakarta.enterprise.inject.spi.configurator.ObserverMethodConfigurator) Preconditions.checkArgumentNotNull(org.jboss.weld.util.Preconditions.checkArgumentNotNull) Reception(jakarta.enterprise.event.Reception) ObservesAsync(jakarta.enterprise.event.ObservesAsync) HashSet(java.util.HashSet) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Extension(jakarta.enterprise.inject.spi.Extension) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Parameter(java.lang.reflect.Parameter) ObserverException(jakarta.enterprise.event.ObserverException) Formats(org.jboss.weld.util.reflection.Formats) Priority(jakarta.annotation.Priority) Method(java.lang.reflect.Method) TransactionPhase(jakarta.enterprise.event.TransactionPhase) SyntheticObserverMethod(org.jboss.weld.event.SyntheticObserverMethod) CovariantTypes(org.jboss.weld.resolution.CovariantTypes) ImmutableSet(org.jboss.weld.util.collections.ImmutableSet) Set(java.util.Set) ObserverMethod(jakarta.enterprise.inject.spi.ObserverMethod) Collectors(java.util.stream.Collectors) EventContext(jakarta.enterprise.inject.spi.EventContext) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) ObservesAsync(jakarta.enterprise.event.ObservesAsync) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Observes(jakarta.enterprise.event.Observes) Priority(jakarta.annotation.Priority)

Example 3 with AnnotatedMethod

use of jakarta.enterprise.inject.spi.AnnotatedMethod in project hibernate-validator by hibernate.

the class ValidationExtension method determineConstrainedMethods.

private <T> void determineConstrainedMethods(AnnotatedType<T> type, BeanDescriptor beanDescriptor, Set<AnnotatedCallable<? super T>> callables) {
    List<Method> overriddenAndImplementedMethods = InheritedMethodsHelper.getAllMethods(type.getJavaClass());
    for (AnnotatedMethod<? super T> annotatedMethod : type.getMethods()) {
        Method method = annotatedMethod.getJavaMember();
        Optional<String> correspondingProperty = getterPropertySelectionStrategyHelper.getProperty(method);
        // obtain @ValidateOnExecution from the top-most method in the hierarchy
        Method methodForExecutableTypeRetrieval = replaceWithOverriddenOrInterfaceMethod(method, overriddenAndImplementedMethods);
        EnumSet<ExecutableType> classLevelExecutableTypes = executableTypesDefinedOnType(methodForExecutableTypeRetrieval.getDeclaringClass());
        EnumSet<ExecutableType> memberLevelExecutableType = executableTypesDefinedOnMethod(methodForExecutableTypeRetrieval, correspondingProperty.isPresent());
        ExecutableType currentExecutableType = correspondingProperty.isPresent() ? ExecutableType.GETTER_METHODS : ExecutableType.NON_GETTER_METHODS;
        // validation occurs
        if (veto(classLevelExecutableTypes, memberLevelExecutableType, currentExecutableType)) {
            continue;
        }
        boolean needsValidation;
        if (correspondingProperty.isPresent()) {
            needsValidation = isGetterConstrained(beanDescriptor, method, correspondingProperty.get());
        } else {
            needsValidation = isNonGetterConstrained(beanDescriptor, method);
        }
        if (needsValidation) {
            callables.add(annotatedMethod);
        }
    }
}
Also used : ExecutableType(jakarta.validation.executable.ExecutableType) Method(java.lang.reflect.Method) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod)

Example 4 with AnnotatedMethod

use of jakarta.enterprise.inject.spi.AnnotatedMethod in project helidon by oracle.

the class SchedulingCdiExtension method invoke.

void invoke(@Observes @Priority(PLATFORM_AFTER + 4000) @Initialized(ApplicationScoped.class) Object event, BeanManager beanManager) {
    ScheduledThreadPoolSupplier scheduledThreadPoolSupplier = ScheduledThreadPoolSupplier.builder().threadNamePrefix(schedulingConfig.get("thread-name-prefix").asString().orElse("scheduled-")).config(schedulingConfig).build();
    for (AnnotatedMethod<?> am : methods) {
        Class<?> aClass = am.getDeclaringType().getJavaClass();
        Bean<?> bean = beans.get(am);
        Object beanInstance = lookup(bean, beanManager);
        ScheduledExecutorService executorService = scheduledThreadPoolSupplier.get();
        executors.add(executorService);
        Method method = am.getJavaMember();
        if (!method.trySetAccessible()) {
            throw new DeploymentException(String.format("Scheduled method %s#%s is not accessible!", method.getDeclaringClass().getName(), method.getName()));
        }
        if (am.isAnnotationPresent(FixedRate.class) && am.isAnnotationPresent(Scheduled.class)) {
            throw new DeploymentException(String.format("Scheduled method %s#%s can have only one scheduling annotation.", method.getDeclaringClass().getName(), method.getName()));
        }
        Config methodConfig = config.get(aClass.getName() + "." + method.getName() + ".schedule");
        if (am.isAnnotationPresent(FixedRate.class)) {
            FixedRate annotation = am.getAnnotation(FixedRate.class);
            long initialDelay = methodConfig.get("initial-delay").asLong().orElseGet(annotation::initialDelay);
            long delay = methodConfig.get("delay").asLong().orElseGet(annotation::value);
            TimeUnit timeUnit = methodConfig.get("time-unit").asString().map(TimeUnit::valueOf).orElseGet(annotation::timeUnit);
            Task task = Scheduling.fixedRateBuilder().executor(executorService).initialDelay(initialDelay).delay(delay).timeUnit(timeUnit).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        } else if (am.isAnnotationPresent(Scheduled.class)) {
            Scheduled annotation = am.getAnnotation(Scheduled.class);
            String cron = methodConfig.get("cron").asString().orElseGet(() -> resolvePlaceholders(annotation.value(), config));
            boolean concurrent = methodConfig.get("concurrent").asBoolean().orElseGet(annotation::concurrentExecution);
            Task task = Scheduling.cronBuilder().executor(executorService).concurrentExecution(concurrent).expression(cron).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        }
    }
}
Also used : Observes(jakarta.enterprise.event.Observes) Task(io.helidon.scheduling.Task) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) Invocation(io.helidon.scheduling.Invocation) ProcessManagedBean(jakarta.enterprise.inject.spi.ProcessManagedBean) Level(java.util.logging.Level) Bean(jakarta.enterprise.inject.spi.Bean) RuntimeStart(io.helidon.microprofile.cdi.RuntimeStart) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Matcher(java.util.regex.Matcher) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) Map(java.util.Map) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) PLATFORM_AFTER(jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Priority(jakarta.annotation.Priority) LinkedList(java.util.LinkedList) Method(java.lang.reflect.Method) Initialized(jakarta.enterprise.context.Initialized) ExecutorService(java.util.concurrent.ExecutorService) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Scheduling(io.helidon.scheduling.Scheduling) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) CreationalContext(jakarta.enterprise.context.spi.CreationalContext) Logger(java.util.logging.Logger) BeforeDestroyed(jakarta.enterprise.context.BeforeDestroyed) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) WithAnnotations(jakarta.enterprise.inject.spi.WithAnnotations) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Task(io.helidon.scheduling.Task) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Method(java.lang.reflect.Method) TimeUnit(java.util.concurrent.TimeUnit) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException)

Example 5 with AnnotatedMethod

use of jakarta.enterprise.inject.spi.AnnotatedMethod in project core by weld.

the class InterceptionModelInitializer method initMethodDeclaredEjbInterceptors.

private void initMethodDeclaredEjbInterceptors(AnnotatedMethod<?> method) {
    Method javaMethod = method.getJavaMember();
    boolean excludeClassInterceptors = method.isAnnotationPresent(interceptorsApi.getExcludeClassInterceptorsAnnotationClass());
    if (excludeClassInterceptors) {
        builder.addMethodIgnoringGlobalInterceptors(javaMethod);
    }
    Class<?>[] methodDeclaredInterceptors = interceptorsApi.extractInterceptorClasses(method);
    if (methodDeclaredInterceptors != null && methodDeclaredInterceptors.length > 0) {
        if (Reflections.isFinal(method.getJavaMember())) {
            throw new DeploymentException(BeanLogger.LOG.finalInterceptedBeanMethodNotAllowed(method, methodDeclaredInterceptors[0].getName()));
        }
        InterceptionType interceptionType = isTimeoutAnnotationPresentOn(method) ? InterceptionType.AROUND_TIMEOUT : InterceptionType.AROUND_INVOKE;
        builder.interceptMethod(interceptionType, javaMethod, getMethodDeclaredInterceptorMetadatas(methodDeclaredInterceptors), null);
    }
}
Also used : DeploymentException(org.jboss.weld.exceptions.DeploymentException) EnhancedAnnotatedMethod(org.jboss.weld.annotated.enhanced.EnhancedAnnotatedMethod) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Method(java.lang.reflect.Method) InterceptionType(jakarta.enterprise.inject.spi.InterceptionType)

Aggregations

AnnotatedMethod (jakarta.enterprise.inject.spi.AnnotatedMethod)11 Method (java.lang.reflect.Method)7 AnnotatedType (jakarta.enterprise.inject.spi.AnnotatedType)4 Observes (jakarta.enterprise.event.Observes)3 AnnotatedParameter (jakarta.enterprise.inject.spi.AnnotatedParameter)3 Extension (jakarta.enterprise.inject.spi.Extension)3 Type (java.lang.reflect.Type)3 HashSet (java.util.HashSet)3 Priority (jakarta.annotation.Priority)2 BeanManager (jakarta.enterprise.inject.spi.BeanManager)2 Annotation (java.lang.annotation.Annotation)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 Set (java.util.Set)2 ScheduledThreadPoolSupplier (io.helidon.common.configurable.ScheduledThreadPoolSupplier)1 Config (io.helidon.config.Config)1 RuntimeStart (io.helidon.microprofile.cdi.RuntimeStart)1 InProcessGrpcChannel (io.helidon.microprofile.grpc.core.InProcessGrpcChannel)1 Invocation (io.helidon.scheduling.Invocation)1 Scheduling (io.helidon.scheduling.Scheduling)1 Task (io.helidon.scheduling.Task)1