Search in sources :

Example 16 with AnnotatedType

use of javax.enterprise.inject.spi.AnnotatedType in project ovirt-engine by oVirt.

the class Injector method injectMembers.

/**
 * This method will take an instance and will fulfill all its dependencies, which are members
 * annotated with <code>@Inject</code>.
 * @param instance unmanaged CDI bean, essentially a regular object which is not managed by
 *                  the CDI container.
 * @param <T> an unmanaged CDI instance with some members containing <code>@Inject</code> annotated
 *           members
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T injectMembers(T instance) {
    AnnotatedType type = CDI.current().getBeanManager().createAnnotatedType(instance.getClass());
    InjectionTarget injectionTarget = CDI.current().getBeanManager().createInjectionTarget(type);
    injectionTarget.inject(instance, CDI.current().getBeanManager().createCreationalContext(null));
    injectionTarget.postConstruct(instance);
    return instance;
}
Also used : AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) InjectionTarget(javax.enterprise.inject.spi.InjectionTarget)

Example 17 with AnnotatedType

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

the class BeanContext method mergeOWBAndOpenEJBInfo.

public void mergeOWBAndOpenEJBInfo() {
    final CdiEjbBean cdiEjbBean = get(CdiEjbBean.class);
    if (cdiEjbBean == null) {
        return;
    }
    final InjectionTargetImpl<?> injectionTarget = InjectionTargetImpl.class.cast(get(CdiEjbBean.class).getInjectionTarget());
    final InterceptorResolutionService.BeanInterceptorInfo info = injectionTarget.getInterceptorInfo();
    if (info == null) {
        return;
    }
    final Collection<Interceptor<?>> postConstructInterceptors = Collection.class.cast(Reflections.get(injectionTarget, "postConstructInterceptors"));
    final Collection<Interceptor<?>> preDestroyInterceptors = Collection.class.cast(Reflections.get(injectionTarget, "preDestroyInterceptors"));
    if (postConstructInterceptors != null) {
        for (final Interceptor<?> pc : postConstructInterceptors) {
            if (isEjbInterceptor(pc)) {
                continue;
            }
            final InterceptorData interceptorData = createInterceptorData(pc);
            instanceScopedInterceptors.add(interceptorData);
            cdiInterceptors.add(interceptorData);
        }
    }
    if (preDestroyInterceptors != null) {
        for (final Interceptor<?> pd : preDestroyInterceptors) {
            if (isEjbInterceptor(pd)) {
                continue;
            }
            if (postConstructInterceptors.contains(pd)) {
                continue;
            }
            final InterceptorData interceptorData = createInterceptorData(pd);
            instanceScopedInterceptors.add(interceptorData);
            cdiInterceptors.add(interceptorData);
        }
    }
    for (final Map.Entry<Method, InterceptorResolutionService.BusinessMethodInterceptorInfo> entry : info.getBusinessMethodsInfo().entrySet()) {
        final Interceptor<?>[] interceptors = entry.getValue().getCdiInterceptors();
        if (interceptors == null) {
            continue;
        }
        for (final Interceptor<?> i : interceptors) {
            // already at class level, since we merge "hooks" in InterceptorData no need to add it again
            if (postConstructInterceptors.contains(i) || preDestroyInterceptors.contains(i)) {
                continue;
            }
            final InterceptorData data = createInterceptorData(i);
            addCdiMethodInterceptor(entry.getKey(), data);
        }
        entry.getValue().setEjbInterceptors(new ArrayList<>());
        entry.getValue().setCdiInterceptors(new ArrayList<>());
    }
    // handled by OpenEJB now so clean up all duplication from OWB
    if (info.getSelfInterceptorBean() != null) {
        try {
            final Field field = InterceptorResolutionService.BeanInterceptorInfo.class.getDeclaredField("selfInterceptorBean");
            field.setAccessible(true);
            field.set(info, null);
        } catch (final Exception e) {
        // no-op
        }
    }
    Map.class.cast(Reflections.get(injectionTarget, "methodInterceptors")).clear();
    clear(Collection.class.cast(postConstructInterceptors));
    clear(Collection.class.cast(preDestroyInterceptors));
    clear(Collection.class.cast(Reflections.get(injectionTarget, "postConstructMethods")));
    clear(Collection.class.cast(Reflections.get(injectionTarget, "preDestroyMethods")));
    clear(Collection.class.cast(Reflections.get(info, "ejbInterceptors")));
    clear(Collection.class.cast(Reflections.get(info, "cdiInterceptors")));
    // OWB doesn't compute AROUND_INVOKE so let's do it
    final Method timeout = getEjbTimeout();
    if (timeout != null) {
        final AnnotatedType annotatedType = cdiEjbBean.getAnnotatedType();
        final AnnotationManager annotationManager = getWebBeansContext().getAnnotationManager();
        final Collection<Annotation> annotations = new HashSet<>(annotationManager.getInterceptorAnnotations(annotatedType.getAnnotations()));
        final Set<AnnotatedMethod<?>> methods = annotatedType.getMethods();
        for (final AnnotatedMethod<?> m : methods) {
            if (timeout.equals(m.getJavaMember())) {
                annotations.addAll(annotationManager.getInterceptorAnnotations(m.getAnnotations()));
                break;
            }
        }
        if (!annotations.isEmpty()) {
            for (final Interceptor<?> timeoutInterceptor : getWebBeansContext().getBeanManagerImpl().resolveInterceptors(InterceptionType.AROUND_TIMEOUT, AnnotationUtil.asArray(annotations))) {
                if (isEjbInterceptor(timeoutInterceptor)) {
                    continue;
                }
                final InterceptorData data = createInterceptorData(timeoutInterceptor);
                addCdiMethodInterceptor(timeout, data);
            }
        }
    }
}
Also used : AnnotationManager(org.apache.webbeans.annotation.AnnotationManager) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) CdiEjbBean(org.apache.openejb.cdi.CdiEjbBean) Field(java.lang.reflect.Field) Interceptor(javax.enterprise.inject.spi.Interceptor) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) InterceptorResolutionService(org.apache.webbeans.intercept.InterceptorResolutionService) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) ApplicationException(javax.ejb.ApplicationException) ConstructionException(org.apache.xbean.recipe.ConstructionException) Annotation(java.lang.annotation.Annotation) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) InterceptorData(org.apache.openejb.core.interceptor.InterceptorData) Collection(java.util.Collection) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 18 with AnnotatedType

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

the class InterceptorBase method intercept.

protected Object intercept(final InvocationContext ic) throws Exception {
    TransactionPolicy policy = null;
    final boolean forbidsUt = doesForbidUtUsage();
    final RuntimeException oldEx;
    final IllegalStateException illegalStateException;
    if (forbidsUt) {
        illegalStateException = ILLEGAL_STATE_EXCEPTION;
        oldEx = CoreUserTransaction.error(illegalStateException);
    } else {
        illegalStateException = null;
        oldEx = null;
    }
    try {
        policy = getPolicy();
        final Object proceed = ic.proceed();
        // force commit there to ensure we can catch synchro exceptions
        policy.commit();
        return proceed;
    } catch (final Exception e) {
        if (illegalStateException == e) {
            throw e;
        }
        Exception error = unwrap(e);
        if (error != null && (!HANDLE_EXCEPTION_ONLY_FOR_CLIENT || policy.isNewTransaction())) {
            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 && policy != null && policy.isTransactionActive()) {
                    policy.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 && policy != null && policy.isTransactionActive()) {
                        policy.setRollbackOnly();
                    }
                }
            }
        }
        if (policy != null) {
            try {
                policy.commit();
            } 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());
                }
            }
        }
        if (error == null || TransactionRequiredException.class.isInstance(error)) {
            throw new TransactionalException(e.getMessage(), error);
        }
        throw error;
    } finally {
        if (forbidsUt) {
            CoreUserTransaction.resetError(oldEx);
        }
    }
}
Also used : AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) TransactionalException(javax.transaction.TransactionalException) TransactionPolicy(org.apache.openejb.core.transaction.TransactionPolicy) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) Logger(java.util.logging.Logger) TransactionRequiredException(javax.transaction.TransactionRequiredException) TransactionalException(javax.transaction.TransactionalException) SystemException(org.apache.openejb.SystemException) RollbackException(javax.transaction.RollbackException) TransactionRolledbackException(org.apache.openejb.core.transaction.TransactionRolledbackException) ApplicationException(org.apache.openejb.ApplicationException) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Transactional(javax.transaction.Transactional)

Example 19 with AnnotatedType

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

the class InterDynExtension method processAnnotatedType.

public void processAnnotatedType(@Observes ProcessAnnotatedType pat) {
    if (enabled) {
        AnnotatedType at = pat.getAnnotatedType();
        String beanClassName = at.getJavaClass().getName();
        AnnotatedTypeBuilder atb = null;
        for (AnnotationRule rule : interceptorRules) {
            if (beanClassName.matches(rule.getRule())) {
                if (rule.requiresProxy() && !ClassUtils.isProxyableClass(at.getJavaClass())) {
                    logger.info("Skipping unproxyable class " + beanClassName + " even if matches rule=" + rule.getRule());
                    return;
                }
                if (atb == null) {
                    atb = new AnnotatedTypeBuilder();
                    atb.readFromType(at);
                }
                atb.addToClass(rule.getAdditionalAnnotation());
                logger.info("Adding Dynamic Interceptor " + rule.getAdditionalAnnotation() + " to class " + beanClassName);
            }
        }
        if (atb != null) {
            pat.setAnnotatedType(atb.create());
        }
    }
}
Also used : ProcessAnnotatedType(javax.enterprise.inject.spi.ProcessAnnotatedType) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) AnnotatedTypeBuilder(org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder)

Example 20 with AnnotatedType

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

the class AnnotatedTypeBuilderTest method testTypeLevelAnnotationRedefinition.

@Test
public void testTypeLevelAnnotationRedefinition() {
    AnnotatedTypeBuilder<Cat> builder = new AnnotatedTypeBuilder<Cat>();
    builder.readFromType(Cat.class);
    AnnotatedType<Cat> cat = builder.create();
    assertNotNull(cat);
    assertNotNull(cat.getAnnotation(Named.class));
    assertEquals("cat", cat.getAnnotation(Named.class).value());
    builder.addToClass(new AlternativeLiteral()).addToClass(new ApplicationScopedLiteral()).removeFromClass(Named.class).addToClass(new NamedLiteral("tomcat"));
    cat = builder.create();
    assertNotNull(cat);
    assertEquals(3, cat.getAnnotations().size());
    assertTrue(cat.isAnnotationPresent(Named.class));
    assertTrue(cat.isAnnotationPresent(Alternative.class));
    assertTrue(cat.isAnnotationPresent(ApplicationScoped.class));
    assertEquals("tomcat", cat.getAnnotation(Named.class).value());
    AnnotatedMethod observerMethod = null;
    for (AnnotatedMethod m : cat.getMethods()) {
        if ("doSomeObservation".equals(m.getJavaMember().getName())) {
            observerMethod = m;
            break;
        }
    }
    assertNotNull(observerMethod);
    observerMethod.isAnnotationPresent(Observes.class);
    {
        // test reading from an AnnotatedType
        AnnotatedTypeBuilder<Cat> builder2 = new AnnotatedTypeBuilder<Cat>();
        builder2.readFromType(cat);
        builder2.removeFromAll(Named.class);
        final AnnotatedType<Cat> noNameCat = builder2.create();
        assertFalse(noNameCat.isAnnotationPresent(Named.class));
        assertEquals(2, noNameCat.getAnnotations().size());
    }
    {
        // test reading from an AnnotatedType in non-overwrite mode
        AnnotatedTypeBuilder<Cat> builder3 = new AnnotatedTypeBuilder<Cat>();
        builder3.readFromType(cat, true);
        builder3.removeFromAll(Named.class);
        builder3.readFromType(cat, false);
        final AnnotatedType<Cat> namedCat = builder3.create();
        assertTrue(namedCat.isAnnotationPresent(Named.class));
        assertEquals(3, namedCat.getAnnotations().size());
    }
}
Also used : Named(javax.inject.Named) AnnotatedType(javax.enterprise.inject.spi.AnnotatedType) AnnotatedTypeBuilder(org.apache.deltaspike.core.util.metadata.builder.AnnotatedTypeBuilder) Alternative(javax.enterprise.inject.Alternative) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) AlternativeLiteral(org.apache.deltaspike.core.api.literal.AlternativeLiteral) ApplicationScoped(javax.enterprise.context.ApplicationScoped) NamedLiteral(org.apache.deltaspike.core.api.literal.NamedLiteral) ApplicationScopedLiteral(org.apache.deltaspike.core.api.literal.ApplicationScopedLiteral) Test(org.junit.Test)

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