Search in sources :

Example 6 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project deltaspike by apache.

the class BeanBuilder method readFromType.

/**
 * <p>
 * Read the {@link AnnotatedType}, creating a bean from the class and it's
 * annotations.
 * </p>
 * <p/>
 * <p>
 * By default the bean lifecycle will wrap the result of calling
 * {@link BeanManager#createInjectionTarget(AnnotatedType)}.
 * </p>
 * <p/>
 * <p>
 * {@link BeanBuilder} does <em>not</em> support reading members of the class
 * to create producers or observer methods.
 * </p>
 *
 * @param type the type to read
 */
public BeanBuilder<T> readFromType(AnnotatedType<T> type) {
    this.beanClass = type.getJavaClass();
    if (beanLifecycle == null) {
        setDefaultBeanLifecycle(type);
    }
    this.qualifiers = new HashSet<Annotation>();
    this.stereotypes = new HashSet<Class<? extends Annotation>>();
    this.types = new HashSet<Type>();
    for (Annotation annotation : type.getAnnotations()) {
        if (beanManager.isQualifier(annotation.annotationType())) {
            this.qualifiers.add(annotation);
        } else if (beanManager.isScope(annotation.annotationType())) {
            this.scope = annotation.annotationType();
        } else if (beanManager.isStereotype(annotation.annotationType())) {
            this.stereotypes.add(annotation.annotationType());
        }
        if (annotation instanceof Named) {
            this.name = ((Named) annotation).value();
            if (name == null || name.length() == 0) {
                name = createDefaultBeanName(type);
            }
        }
        if (annotation instanceof Alternative) {
            this.alternative = true;
        }
    }
    if (type.isAnnotationPresent(Typed.class)) {
        Typed typed = type.getAnnotation(Typed.class);
        this.types.addAll(Arrays.asList(typed.value()));
    } else {
        for (Class<?> c = type.getJavaClass(); c != Object.class && c != null; c = c.getSuperclass()) {
            this.types.add(c);
        }
        Collections.addAll(this.types, type.getJavaClass().getInterfaces());
        this.types.add(Object.class);
    }
    if (qualifiers.isEmpty()) {
        qualifiers.add(new DefaultLiteral());
    }
    qualifiers.add(new AnyLiteral());
    this.id = ImmutableBeanWrapper.class.getName() + ":" + Annotateds.createTypeId(type);
    return this;
}
Also used : Named(javax.inject.Named) Alternative(javax.enterprise.inject.Alternative) Annotation(java.lang.annotation.Annotation) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) Type(java.lang.reflect.Type) Typed(javax.enterprise.inject.Typed) DefaultLiteral(org.apache.deltaspike.core.api.literal.DefaultLiteral) AnyLiteral(org.apache.deltaspike.core.api.literal.AnyLiteral)

Example 7 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project tomee by apache.

the class WebContext method getConstructorInjectionBean.

private ConstructorInjectionBean<Object> getConstructorInjectionBean(final Class beanClass, final WebBeansContext webBeansContext) {
    if (webBeansContext == null) {
        return null;
    }
    ConstructorInjectionBean<Object> beanDefinition = constructorInjectionBeanCache.get(beanClass);
    if (beanDefinition == null) {
        synchronized (this) {
            beanDefinition = constructorInjectionBeanCache.get(beanClass);
            if (beanDefinition == null) {
                final AnnotatedType annotatedType = webBeansContext.getAnnotatedElementFactory().newAnnotatedType(beanClass);
                if (isWeb(beanClass)) {
                    beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType, false);
                } else {
                    beanDefinition = new ConstructorInjectionBean<>(webBeansContext, beanClass, annotatedType);
                }
                constructorInjectionBeanCache.put(beanClass, beanDefinition);
            }
        }
    }
    return beanDefinition;
}
Also used : AnnotatedType(javax.enterprise.inject.spi.AnnotatedType)

Example 8 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project tomee by apache.

the class BValInterceptor method computeIsConstructorValidated.

private <T> boolean computeIsConstructorValidated(Class<T> targetClass, Constructor<T> ctor) {
    final AnnotatedType<T> annotatedType = CDI.current().getBeanManager().createAnnotatedType(ctor.getDeclaringClass());
    final ValidateOnExecution annotation = annotatedType.getConstructors().stream().filter(ac -> ctor.equals(ac.getJavaMember())).findFirst().map(ac -> ac.getAnnotation(ValidateOnExecution.class)).orElseGet(() -> ctor.getAnnotation(ValidateOnExecution.class));
    final Set<ExecutableType> validatedExecutableTypes = annotation == null ? classConfiguration : ExecutableTypes.interpret(annotation.type());
    return validatedExecutableTypes.contains(ExecutableType.CONSTRUCTORS);
}
Also used : Reflection(org.apache.bval.util.reflection.Reflection) Arrays(java.util.Arrays) InvocationContext(javax.interceptor.InvocationContext) ObjectUtils(org.apache.bval.util.ObjectUtils) Proxies(org.apache.bval.jsr.util.Proxies) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) ExecutableValidator(javax.validation.executable.ExecutableValidator) Constructor(java.lang.reflect.Constructor) ConcurrentMap(java.util.concurrent.ConcurrentMap) Inject(javax.inject.Inject) Interceptor(javax.interceptor.Interceptor) MethodDescriptor(javax.validation.metadata.MethodDescriptor) BiPredicate(java.util.function.BiPredicate) Map(java.util.Map) Executable(java.lang.reflect.Executable) BValBinding(org.apache.bval.cdi.BValBinding) ConstraintViolation(javax.validation.ConstraintViolation) Method(java.lang.reflect.Method) ExecutableTypes(org.apache.bval.jsr.util.ExecutableTypes) EnumSet(java.util.EnumSet) BValExtension(org.apache.bval.cdi.BValExtension) Validate(org.apache.bval.util.Validate) Interfaces(org.apache.bval.util.reflection.Reflection.Interfaces) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CDI(javax.enterprise.inject.spi.CDI) Validator(javax.validation.Validator) Set(java.util.Set) ConstructorDescriptor(javax.validation.metadata.ConstructorDescriptor) InterceptorBinding(javax.interceptor.InterceptorBinding) Serializable(java.io.Serializable) Methods(org.apache.bval.jsr.util.Methods) Priority(javax.annotation.Priority) AroundConstruct(javax.interceptor.AroundConstruct) List(java.util.List) ConstraintViolationException(javax.validation.ConstraintViolationException) ExecutableType(javax.validation.executable.ExecutableType) AroundInvoke(javax.interceptor.AroundInvoke) Optional(java.util.Optional) DescriptorManager(org.apache.bval.jsr.descriptor.DescriptorManager) Signature(org.apache.bval.jsr.metadata.Signature) Collections(java.util.Collections) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) ValidateOnExecution(javax.validation.executable.ValidateOnExecution) ExecutableType(javax.validation.executable.ExecutableType) ValidateOnExecution(javax.validation.executable.ValidateOnExecution)

Example 9 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project Payara by payara.

the class ConfigPropertiesProducer method getGenericObject.

@ConfigProperties
public static final Object getGenericObject(InjectionPoint injectionPoint, BeanManager bm) throws InstantiationException, IllegalAccessException {
    Type type = injectionPoint.getType();
    if (!(type instanceof Class)) {
        throw new IllegalArgumentException("Unable to process injection point with @ConfigProperties of type " + type);
    }
    // Initialise the object. This may throw exceptions
    final Object object = ((Class) type).newInstance();
    // Model the class
    final AnnotatedType<?> annotatedType = bm.createAnnotatedType((Class) type);
    // Find the @ConfigProperties annotations, and calculate the property prefix
    final ConfigProperties injectionAnnotation = getQualifier(injectionPoint);
    final ConfigProperties classAnnotation = annotatedType.getAnnotation(ConfigProperties.class);
    final String prefix = parsePrefixes(injectionAnnotation, classAnnotation);
    for (AnnotatedField<?> field : annotatedType.getFields()) {
        // Find the java field and field name
        final Field javaField = field.getJavaMember();
        // Make sure the field is accessible
        javaField.setAccessible(true);
        // Model the field
        final InjectionPoint fieldInjectionPoint = bm.createInjectionPoint(field);
        final ConfigPropertyModel model = new ConfigPropertyModel(fieldInjectionPoint, prefix);
        try {
            final Object value = ConfigPropertyProducer.getGenericPropertyFromModel(model);
            if (value != null) {
                javaField.set(object, value);
            }
        } catch (Exception ex) {
            if (javaField.get(object) == null) {
                LOGGER.log(Level.WARNING, String.format("Unable to inject property with name %s into type %s.", model.getName(), type.getTypeName()), ex);
                throw ex;
            }
        }
    }
    return object;
}
Also used : Field(java.lang.reflect.Field) AnnotatedField(javax.enterprise.inject.spi.AnnotatedField) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) Type(java.lang.reflect.Type) ConfigProperties(org.eclipse.microprofile.config.inject.ConfigProperties) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) ConfigPropertyModel(fish.payara.microprofile.config.cdi.model.ConfigPropertyModel) ConfigProperties(org.eclipse.microprofile.config.inject.ConfigProperties)

Example 10 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project meecrowave by apache.

the class InterceptorBase method intercept.

protected Object intercept(final InvocationContext ic) throws Exception {
    final boolean forbidsUt = doesForbidUtUsage();
    final RuntimeException oldEx;
    final IllegalStateException illegalStateException;
    if (forbidsUt) {
        illegalStateException = ILLEGAL_STATE_EXCEPTION;
        oldEx = error(illegalStateException);
    } else {
        illegalStateException = null;
        oldEx = null;
    }
    State state = null;
    try {
        state = start();
        final Object proceed = ic.proceed();
        // force commit there to ensure we can catch synchro exceptions
        commit(state);
        return proceed;
    } catch (final Exception e) {
        if (illegalStateException == e) {
            throw e;
        }
        Exception error = unwrap(e);
        if (error != null && (!config.isHandleExceptionOnlyForClient() || isNewTransaction(state))) {
            final Method method = ic.getMethod();
            if (rollback == null) {
                synchronized (this) {
                    if (rollback == null) {
                        rollback = new ConcurrentHashMap<>();
                    }
                }
            }
            Boolean doRollback = rollback.get(method);
            if (doRollback != null) {
                if (doRollback && isTransactionActive(state.current)) {
                    setRollbackOnly();
                }
            } else {
                // computed lazily but we could cache it later for sure if that's really a normal case
                final AnnotatedType<?> annotatedType = CDI.current().getBeanManager().createAnnotatedType(method.getDeclaringClass());
                Transactional tx = null;
                for (final AnnotatedMethod<?> m : annotatedType.getMethods()) {
                    if (method.equals(m.getJavaMember())) {
                        tx = m.getAnnotation(Transactional.class);
                        break;
                    }
                }
                if (tx == null) {
                    tx = annotatedType.getAnnotation(Transactional.class);
                }
                if (tx != null) {
                    doRollback = new ExceptionPriotiryRules(tx.rollbackOn(), tx.dontRollbackOn()).accept(error, method.getExceptionTypes());
                    rollback.putIfAbsent(method, doRollback);
                    if (doRollback && isTransactionActive(state.current)) {
                        setRollbackOnly();
                    }
                }
            }
        }
        try {
            commit(state);
        } catch (final Exception ex) {
            // no-op: swallow to keep the right exception
            final Logger logger = Logger.getLogger(getClass().getName());
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Swallowing: " + ex.getMessage());
            }
        }
        throw new TransactionalException(e.getMessage(), error);
    } finally {
        if (forbidsUt) {
            resetError(oldEx);
        }
    }
}
Also used : AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) TransactionalException(javax.transaction.TransactionalException) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) Logger(java.util.logging.Logger) TransactionalException(javax.transaction.TransactionalException) SystemException(javax.transaction.SystemException) RollbackException(javax.transaction.RollbackException) TransactionRolledbackException(javax.transaction.TransactionRolledbackException) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Transactional(javax.transaction.Transactional)

Aggregations

AnnotatedType (javax.enterprise.inject.spi.AnnotatedType)24 AnnotatedMethod (javax.enterprise.inject.spi.AnnotatedMethod)7 Annotation (java.lang.annotation.Annotation)5 Method (java.lang.reflect.Method)5 Type (java.lang.reflect.Type)5 HashSet (java.util.HashSet)4 Set (java.util.Set)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 ProcessAnnotatedType (javax.enterprise.inject.spi.ProcessAnnotatedType)4 Test (org.junit.Test)4 InjectionTarget (javax.enterprise.inject.spi.InjectionTarget)3 EnhancedAnnotatedType (org.jboss.weld.annotated.enhanced.EnhancedAnnotatedType)3 ForwardingAnnotatedType (org.jboss.weld.util.annotated.ForwardingAnnotatedType)3 Field (java.lang.reflect.Field)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Logger (java.util.logging.Logger)2 CreationalContext (javax.enterprise.context.spi.CreationalContext)2 Alternative (javax.enterprise.inject.Alternative)2