javax.enterprise.inject.spi.AnnotatedMethod Java Examples

The following examples show how to use javax.enterprise.inject.spi.AnnotatedMethod. 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: CdiPlugin.java    From tomee with Apache License 2.0 6 votes vote down vote up
private static void validateObserverMethods(final CdiEjbBean<?> bean, final Map<ObserverMethod<?>, AnnotatedMethod<?>> methods) {
    final BeanContext beanContext = bean.getBeanContext();
    if (beanContext.isLocalbean()) {
        return;
    }

    for (final Map.Entry<ObserverMethod<?>, AnnotatedMethod<?>> m : methods.entrySet()) {
        final Method method = m.getValue().getJavaMember();
        if (!Modifier.isStatic(method.getModifiers())) {
            final Method viewMethod = doResolveViewMethod(bean, method);
            if (viewMethod == null) {
                throw new WebBeansConfigurationException(
                        "@Observes " + method + " neither in the ejb view of ejb " + bean.getBeanContext().getEjbName() + " nor static");
            } else if (beanContext.getBusinessRemoteInterfaces().contains(viewMethod.getDeclaringClass())) {
                throw new WebBeansConfigurationException(viewMethod + " observer is defined in a @Remote interface");
            }
        }
        if (m.getValue().getParameters().stream().anyMatch(p -> p.isAnnotationPresent(ObservesAsync.class))) {
            throw new WebBeansConfigurationException("@ObservesAsync " + method + " not supported on EJB in CDI 2");
        }
    }
}
 
Example #2
Source File: HandlerMethodImpl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Determines if the given method is a handler by looking for the {@link Handles} annotation on a parameter.
 *
 * @param method method to search
 * @return true if {@link Handles} is found, false otherwise
 */
public static boolean isHandler(final AnnotatedMethod<?> method)
{
    if (method == null)
    {
        throw new IllegalArgumentException("Method must not be null");
    }

    for (AnnotatedParameter<?> param : method.getParameters())
    {
        if (param.isAnnotationPresent(Handles.class) || param.isAnnotationPresent(BeforeHandles.class))
        {
            return true;
        }
    }

    return false;
}
 
Example #3
Source File: HandlerMethodImpl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static AnnotatedParameter<?> findHandlerParameter(final AnnotatedMethod<?> method)
{
    if (!isHandler(method))
    {
        throw new IllegalArgumentException("Method is not a valid handler");
    }

    AnnotatedParameter<?> returnParam = null;

    for (AnnotatedParameter<?> param : method.getParameters())
    {
        if (param.isAnnotationPresent(Handles.class) || param.isAnnotationPresent(BeforeHandles.class))
        {
            returnParam = param;
            break;
        }
    }

    return returnParam;
}
 
Example #4
Source File: AnnotatedMethods.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static AnnotatedMethod<?> findMethod(final AnnotatedType<?> type, final Method method)
{
    AnnotatedMethod<?> annotatedMethod = null;
    for (final AnnotatedMethod<?> am : type.getMethods())
    {
        if (am.getJavaMember().equals(method))
        {
            annotatedMethod = am;
            break;
        }
    }
    if (annotatedMethod == null)
    {
        throw new IllegalStateException("No annotated method for " + method);
    }
    return annotatedMethod;
}
 
Example #5
Source File: Annotateds.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public int compare(AnnotatedMethod<? super T> arg0, AnnotatedMethod<? super T> arg1)
{
    int result = callableComparator.compare(arg0, arg1);
    if (result != 0)
    {
        return result;
    }
    for (int i = 0; i < arg0.getJavaMember().getParameterTypes().length; ++i)
    {
        Class<?> p0 = arg0.getJavaMember().getParameterTypes()[i];
        Class<?> p1 = arg1.getJavaMember().getParameterTypes()[i];
        result = p0.getName().compareTo(p1.getName());
        if (result != 0)
        {
            return result;
        }
    }
    return 0;
}
 
Example #6
Source File: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 6 votes vote down vote up
private <X> void findAnnotatedMethods(@Observes ProcessManagedBean<X> bean) {
    Package pack = bean.getBean().getBeanClass().getPackage();
    if (pack != null && pack.equals(GaugeRegistrationInterceptor.class.getPackage())) {
        return;
    }
    ArrayList<AnnotatedMember<?>> list = new ArrayList<>();
    for (AnnotatedMethod<? super X> aMethod : bean.getAnnotatedBeanClass().getMethods()) {
        Method method = aMethod.getJavaMember();
        if (!method.isSynthetic() && !Modifier.isPrivate(method.getModifiers())) {
            list.add(aMethod);
        }
    }
    list.addAll(bean.getAnnotatedBeanClass().getConstructors());
    if (!list.isEmpty()) {
        metricsFromAnnotatedMethods.put(bean.getBean(), list);
    }
}
 
Example #7
Source File: AnnotatedMethodWrapper.java    From krazo with Apache License 2.0 6 votes vote down vote up
public AnnotatedMethodWrapper(AnnotatedMethod<T> wrapped,
                              Set<Annotation> additionalAnnotations,
                              Predicate<Class> annotationBlacklist) {

    this.wrapped = wrapped;

    // add annotations which are not blacklisted
    this.annotations.addAll(
            wrapped.getAnnotations().stream()
                    .filter(a -> !annotationBlacklist.test(a.annotationType()))
                    .collect(Collectors.toList())
    );

    // add additional annotations
    this.annotations.addAll(additionalAnnotations);

}
 
Example #8
Source File: AnnotatedTypeProcessor.java    From krazo with Apache License 2.0 6 votes vote down vote up
public <T> AnnotatedType<T> getReplacement(AnnotatedType<T> originalType) {

        boolean modified = false;
        Set<AnnotatedMethod<? super T>> methods = new LinkedHashSet<>();

        for (AnnotatedMethod<? super T> originalMethod : originalType.getMethods()) {
            AnnotatedMethod<? super T> replacement = getReplacement(originalType, originalMethod);
            if (replacement != null) {
                methods.add(replacement);
                modified = true;
            } else {
                methods.add(originalMethod);
            }
        }

        if (modified) {
            return new AnnotatedTypeWrapper<T>(originalType, methods);
        }
        return null;

    }
 
Example #9
Source File: AnnotatedTypeProcessor.java    From krazo with Apache License 2.0 6 votes vote down vote up
private <T> AnnotatedMethod<? super T> getReplacement(AnnotatedType<T> type,
                                                      AnnotatedMethod<? super T> method) {

    // added to methods to intercept calls with our interceptors
    Set<Annotation> markerAnnotations = new LinkedHashSet<>(Arrays.asList(
            () -> ValidationInterceptorBinding.class,
            () -> AroundController.class
    ));

    // drop Hibernate Validator's marker annotations to skip the native validation
    Predicate<Class> annotationBlacklist = clazz -> isHibernateValidatorMarkerAnnotation(clazz);

    if (ControllerUtils.isControllerMethod(method.getJavaMember())) {

        log.log(Level.FINE, "Found controller method: {0}#{1}", new Object[]{
            type.getJavaClass().getName(),
            method.getJavaMember().getName()
        });

        return new AnnotatedMethodWrapper<>(method, markerAnnotations, annotationBlacklist);

    }

    return null;

}
 
Example #10
Source File: AnnotatedMethodWrapper.java    From ozark with Apache License 2.0 6 votes vote down vote up
public AnnotatedMethodWrapper(AnnotatedMethod<T> wrapped,
                              Set<Annotation> additionalAnnotations,
                              Predicate<Class> annotationBlacklist) {

    this.wrapped = wrapped;

    // add annotations which are not blacklisted
    this.annotations.addAll(
            wrapped.getAnnotations().stream()
                    .filter(a -> !annotationBlacklist.test(a.annotationType()))
                    .collect(Collectors.toList())
    );

    // add additional annotations
    this.annotations.addAll(additionalAnnotations);

}
 
Example #11
Source File: AnnotatedTypeProcessor.java    From ozark with Apache License 2.0 6 votes vote down vote up
public <T> AnnotatedType<T> getReplacement(AnnotatedType<T> originalType) {

        boolean modified = false;
        Set<AnnotatedMethod<? super T>> methods = new LinkedHashSet<>();

        for (AnnotatedMethod<? super T> originalMethod : originalType.getMethods()) {
            AnnotatedMethod<? super T> replacement = getReplacement(originalType, originalMethod);
            if (replacement != null) {
                methods.add(replacement);
                modified = true;
            } else {
                methods.add(originalMethod);
            }
        }

        if (modified) {
            return new AnnotatedTypeWrapper<T>(originalType, methods);
        }
        return null;

    }
 
Example #12
Source File: MetricCdiInjectionExtension.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private static boolean hasInjectionPointMetadata(AnnotatedMember<?> member) {
    if (!(member instanceof AnnotatedMethod)) {
        return false;
    }
    AnnotatedMethod<?> method = (AnnotatedMethod<?>) member;
    for (AnnotatedParameter<?> parameter : method.getParameters()) {
        if (parameter.getBaseType().equals(InjectionPoint.class)) {
            return true;
        }
    }
    return false;
}
 
Example #13
Source File: MediatorManager.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public <T> void analyze(AnnotatedType<T> annotatedType, Bean<T> bean) {
    log.scanningType(annotatedType.getJavaClass());
    Set<AnnotatedMethod<? super T>> methods = annotatedType.getMethods();

    methods.stream()
            .filter(this::hasMediatorAnnotations)
            .forEach(method -> collected.add(method.getJavaMember(), bean));
}
 
Example #14
Source File: BeanUtils.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Given a method, and the bean on which the method is declared, create a
 * collection of injection points representing the parameters of the method.
 *
 * @param <X>           the type declaring the method
 * @param method        the method
 * @param declaringBean the bean on which the method is declared
 * @param beanManager   the bean manager to use to create the injection points
 * @return the injection points
 */
public static <X> List<InjectionPoint> createInjectionPoints(AnnotatedMethod<X> method, Bean<?> declaringBean,
                                                             BeanManager beanManager)
{
    List<InjectionPoint> injectionPoints = new ArrayList<InjectionPoint>();
    for (AnnotatedParameter<X> parameter : method.getParameters())
    {
        InjectionPoint injectionPoint =
                new ImmutableInjectionPoint(parameter, beanManager, declaringBean, false, false);

        injectionPoints.add(injectionPoint);
    }
    return injectionPoints;
}
 
Example #15
Source File: WorkerPoolRegistry.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public <T> void analyzeWorker(AnnotatedType<T> annotatedType) {
    Objects.requireNonNull(annotatedType, msg.annotatedTypeWasEmpty());

    Set<AnnotatedMethod<? super T>> methods = annotatedType.getMethods();

    methods.stream()
            .filter(m -> m.isAnnotationPresent(Blocking.class))
            .forEach(m -> defineWorker(m.getJavaMember()));
}
 
Example #16
Source File: SecurityMetaDataStorage.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
void registerSecuredMethods()
{
    for (AnnotatedMethod<?> method : securedMethods)
    {
        registerSecuredMethod(method.getDeclaringType().getJavaClass(), method.getJavaMember());
    }
}
 
Example #17
Source File: AnnotatedTypeDecorator.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
@Override
public Set<AnnotatedMethod<? super X>> getMethods() {
    Set<AnnotatedMethod<? super X>> methods = new HashSet<>(decoratedType.getMethods());
    for (AnnotatedMethod<? super X> method : decoratedMethods) {
        methods.remove(method);
        methods.add(method);
    }

    return Collections.unmodifiableSet(methods);
}
 
Example #18
Source File: SecurityMetaDataStorage.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
void addSecuredType(AnnotatedType<?> annotatedType)
{
    for (AnnotatedMethod<?> securedMethod : annotatedType.getMethods())
    {
        addSecuredMethod(securedMethod);
    }
}
 
Example #19
Source File: ExceptionControlExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Listener to ProcessBean event to locate handlers.
 *
 * @param processBean current {@link AnnotatedType}
 * @param beanManager  Activated Bean Manager
 * @throws TypeNotPresentException if any of the actual type arguments refers to a non-existent type declaration
 *                                 when trying to obtain the actual type arguments from a
 *                                 {@link java.lang.reflect.ParameterizedType}
 * @throws java.lang.reflect.MalformedParameterizedTypeException
 *                                 if any of the actual type parameters refer to a parameterized type that cannot
 *                                 be instantiated for any reason when trying to obtain the actual type arguments
 *                                 from a {@link java.lang.reflect.ParameterizedType}
 */
@SuppressWarnings("UnusedDeclaration")
public <T> void findHandlers(@Observes final ProcessBean<?> processBean, final BeanManager beanManager)
{
    if (!isActivated)
    {
        return;
    }

    if (processBean.getBean() instanceof Interceptor || processBean.getBean() instanceof Decorator ||
            !(processBean.getAnnotated() instanceof AnnotatedType))
    {
        return;
    }

    AnnotatedType annotatedType = (AnnotatedType)processBean.getAnnotated();

    if (annotatedType.getJavaClass().isAnnotationPresent(ExceptionHandler.class))
    {
        final Set<AnnotatedMethod<? super T>> methods = annotatedType.getMethods();

        for (AnnotatedMethod<? super T> method : methods)
        {
            if (HandlerMethodImpl.isHandler(method))
            {
                if (method.getJavaMember().getExceptionTypes().length != 0)
                {
                    processBean.addDefinitionError(new IllegalArgumentException(
                        String.format("Handler method %s must not throw exceptions", method.getJavaMember())));
                }

                //beanManager won't be stored in the instance -> no issue with wls12c
                registerHandlerMethod(new HandlerMethodImpl(processBean.getBean(), method, beanManager));
            }
        }
    }
}
 
Example #20
Source File: FaultToleranceOperation.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
private static <A extends Annotation, C extends GenericConfig<A>> C getConfig(Class<A> annotationType,
        AnnotatedMethod<?> annotatedMethod, Function<AnnotatedMethod<?>, C> function) {
    if (getConfigStatus(annotationType, annotatedMethod.getJavaMember()) && isAnnotated(annotationType, annotatedMethod)) {
        return function.apply(annotatedMethod);
    }
    return null;
}
 
Example #21
Source File: FaultToleranceOperation.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
public static FaultToleranceOperation of(AnnotatedMethod<?> annotatedMethod) {
    return new FaultToleranceOperation(annotatedMethod.getDeclaringType().getJavaClass(), annotatedMethod.getJavaMember(),
            isAsync(annotatedMethod),
            returnsCompletionStage(annotatedMethod),
            getConfig(Bulkhead.class, annotatedMethod, BulkheadConfig::new),
            getConfig(CircuitBreaker.class, annotatedMethod, CircuitBreakerConfig::new),
            getConfig(Fallback.class, annotatedMethod, FallbackConfig::new),
            getConfig(Retry.class, annotatedMethod, RetryConfig::new),
            getConfig(Timeout.class, annotatedMethod, TimeoutConfig::new));
}
 
Example #22
Source File: SecurityExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the specified authorizer method (i.e. a method annotated with
 * the @Secures annotation)
 *
 * @throws SecurityDefinitionException
 */
private void registerAuthorizer(AnnotatedMethod<?> annotatedMethod)
{
    if (!annotatedMethod.getJavaMember().getReturnType().equals(Boolean.class) &&
            !annotatedMethod.getJavaMember().getReturnType().equals(Boolean.TYPE))
    {
        throw new SecurityDefinitionException("Invalid authorizer method [" +
                annotatedMethod.getJavaMember().getDeclaringClass().getName() + "." +
                annotatedMethod.getJavaMember().getName() + "] - does not return a boolean.");
    }

    // Locate the binding type
    Annotation binding = null;

    for (Annotation annotation : annotatedMethod.getAnnotations())
    {
        if (SecurityUtils.isMetaAnnotatedWithSecurityBindingType(annotation))
        {
            if (binding != null)
            {
                throw new SecurityDefinitionException("Invalid authorizer method [" +
                        annotatedMethod.getJavaMember().getDeclaringClass().getName() + "." +
                        annotatedMethod.getJavaMember().getName() + "] - declares multiple security binding types");
            }
            binding = annotation;
        }
    }

    Authorizer authorizer = new Authorizer(binding, annotatedMethod);
    getMetaDataStorage().addAuthorizer(authorizer);
}
 
Example #23
Source File: DefaultMockFilter.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected boolean isMockSupportEnabled(Annotated annotated)
{
    if ((annotated instanceof AnnotatedMethod || annotated instanceof AnnotatedField) &&
            annotated.getAnnotation(Produces.class) != null)
    {
        return TestBaseConfig.MockIntegration.ALLOW_MOCKED_PRODUCERS;
    }
    else
    {
        return TestBaseConfig.MockIntegration.ALLOW_MOCKED_BEANS;
    }
}
 
Example #24
Source File: CdiHelper.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
static boolean hasInjectionPoints(AnnotatedMember<?> member) {
    if (!(member instanceof AnnotatedMethod))
        return false;
    AnnotatedMethod<?> method = (AnnotatedMethod<?>) member;
    for (AnnotatedParameter<?> parameter : method.getParameters()) {
        if (parameter.getBaseType().equals(InjectionPoint.class))
            return true;
    }
    return false;
}
 
Example #25
Source File: CdiHelper.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
static <T extends Annotation> void declareAsInterceptorBinding(Class<T> annotation, BeanManager manager, BeforeBeanDiscovery bbd) {
    AnnotatedType<T> annotated = manager.createAnnotatedType(annotation);
    Set<AnnotatedMethod<? super T>> methods = new HashSet<>();
    for (AnnotatedMethod<? super T> method : annotated.getMethods())
        methods.add(new AnnotatedMethodDecorator<>(method, NON_BINDING));

    bbd.addInterceptorBinding(new AnnotatedTypeDecorator<>(annotated, INTERCEPTOR_BINDING, methods));
}
 
Example #26
Source File: RouteExtension.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
private boolean hasEventParameter(AnnotatedMethod<?> annotatedMethod) {
    for (AnnotatedParameter<?> param : annotatedMethod.getParameters()) {
        if (param.isAnnotationPresent(Observes.class)) {
            return true;
        }
    }
    return false;
}
 
Example #27
Source File: AnnotatedTypeDecorator.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Override
public Set<AnnotatedMethod<? super X>> getMethods() {
    Set<AnnotatedMethod<? super X>> methods = new HashSet<>(decoratedType.getMethods());
    for (AnnotatedMethod<? super X> method : decoratedMethods) {
        methods.remove(method);
        methods.add(method);
    }

    return Collections.unmodifiableSet(methods);
}
 
Example #28
Source File: InjectionHelper.java    From BeanTest with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the {@link Inject} annotation to the fields and setters of the annotated type if required.
 *
 * @param <X>
 *            the type of the annotated type
 * @param annotatedType
 *            the annotated type whose fields and setters the inject annotation should be added to
 * @param builder
 *            the builder that should be used to add the annotation.
 * @see #shouldInjectionAnnotationBeAddedToMember(AnnotatedMember)
 */
public static <X> void addInjectAnnotation(final AnnotatedType<X> annotatedType, AnnotatedTypeBuilder<X> builder) {
    for (AnnotatedField<? super X> field : annotatedType.getFields()) {
        if (shouldInjectionAnnotationBeAddedToMember(field)) {
            builder.addToField(field, AnnotationInstances.INJECT);
        }
    }
    for (AnnotatedMethod<? super X> method : annotatedType.getMethods()) {
        if (shouldInjectionAnnotationBeAddedToMember(method)) {
            builder.addToMethod(method,  AnnotationInstances.INJECT);
        }
    }
}
 
Example #29
Source File: FaultToleranceExtension.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
/**
 * Observe all enabled managed beans and identify/validate FT operations. This allows us to:
 * <ul>
 * <li>Skip validation of types which are not recognized as beans (e.g. are vetoed)</li>
 * <li>Take the final values of AnnotatedTypes</li>
 * <li>Support annotations added via portable extensions</li>
 * </ul>
 *
 * @param event
 */
void collectFaultToleranceOperations(@Observes ProcessManagedBean<?> event) {
    AnnotatedType<?> annotatedType = event.getAnnotatedBeanClass();
    for (AnnotatedMethod<?> annotatedMethod : annotatedType.getMethods()) {
        FaultToleranceOperation operation = FaultToleranceOperation.of(annotatedMethod);
        if (operation.isLegitimate()) {
            operation.validate();
            LOGGER.debugf("Found %s", operation);
            faultToleranceOperations.put(getCacheKey(annotatedType.getJavaClass(), annotatedMethod.getJavaMember()),
                    operation);
        }
    }
}
 
Example #30
Source File: GenericConfig.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
GenericConfig(Class<X> annotationType, AnnotatedMethod<?> annotatedMethod) {
    this(annotatedMethod.getDeclaringType()
            .getJavaClass(), annotatedMethod.getJavaMember(), annotatedMethod, annotationType,
            annotatedMethod.isAnnotationPresent(annotationType) ? annotatedMethod.getAnnotation(annotationType)
                    : annotatedMethod.getDeclaringType()
                            .getAnnotation(annotationType),
            annotatedMethod.isAnnotationPresent(annotationType) ? ElementType.METHOD : ElementType.TYPE);
}