Search in sources :

Example 6 with AnnotatedMethod

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

the class LockSupplierStorage method getLockSupplier.

protected LockSupplier getLockSupplier(final InvocationContext ic) {
    final Method key = ic.getMethod();
    LockSupplier operation = lockSuppliers.get(key);
    if (operation == null) {
        final Class declaringClass = key.getDeclaringClass();
        final AnnotatedType<Object> annotatedType = beanManager.createAnnotatedType(declaringClass);
        final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, key);
        Locked config = annotatedMethod.getAnnotation(Locked.class);
        if (config == null) {
            config = annotatedType.getAnnotation(Locked.class);
        }
        final Locked.LockFactory factory = config.factory() != Locked.LockFactory.class ? Locked.LockFactory.class.cast(beanManager.getReference(beanManager.resolve(beanManager.getBeans(config.factory())), Locked.LockFactory.class, null)) : this;
        final ReadWriteLock writeLock = factory.newLock(annotatedMethod, config.fair());
        final long timeout = config.timeoutUnit().toMillis(config.timeout());
        final Lock lock = config.operation() == READ ? writeLock.readLock() : writeLock.writeLock();
        if (timeout > 0) {
            operation = new LockSupplier() {

                @Override
                public Lock get() {
                    try {
                        if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
                            throw new IllegalStateException("Can't lock for " + key + " in " + timeout + "ms");
                        }
                    } catch (final InterruptedException e) {
                        Thread.interrupted();
                        throw new IllegalStateException("Locking interrupted", e);
                    }
                    return lock;
                }
            };
        } else {
            operation = new LockSupplier() {

                @Override
                public Lock get() {
                    lock.lock();
                    return lock;
                }
            };
        }
        final LockSupplier existing = lockSuppliers.putIfAbsent(key, operation);
        if (existing != null) {
            operation = existing;
        }
    }
    return operation;
}
Also used : Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Lock(java.util.concurrent.locks.Lock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Locked(org.apache.deltaspike.core.api.lock.Locked) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock)

Example 7 with AnnotatedMethod

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

the class InvokerStorage method getOrCreateInvoker.

Invoker getOrCreateInvoker(final InvocationContext ic) {
    final Method method = ic.getMethod();
    Invoker i = providers.get(method);
    if (i == null) {
        final Class declaringClass = method.getDeclaringClass();
        final AnnotatedType<Object> annotatedType = beanManager.createAnnotatedType(declaringClass);
        final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, method);
        Throttled config = annotatedMethod.getAnnotation(Throttled.class);
        if (config == null) {
            config = annotatedType.getAnnotation(Throttled.class);
        }
        Throttling sharedConfig = annotatedMethod.getAnnotation(Throttling.class);
        if (sharedConfig == null) {
            sharedConfig = annotatedType.getAnnotation(Throttling.class);
        }
        final Throttling.SemaphoreFactory factory = sharedConfig != null && sharedConfig.factory() != Throttling.SemaphoreFactory.class ? Throttling.SemaphoreFactory.class.cast(beanManager.getReference(beanManager.resolve(beanManager.getBeans(sharedConfig.factory())), Throttling.SemaphoreFactory.class, null)) : this;
        final Semaphore semaphore = factory.newSemaphore(annotatedMethod, sharedConfig != null && !sharedConfig.name().isEmpty() ? sharedConfig.name() : declaringClass.getName(), sharedConfig != null && sharedConfig.fair(), sharedConfig != null ? sharedConfig.permits() : 1);
        final long timeout = config.timeoutUnit().toMillis(config.timeout());
        final int weigth = config.weight();
        i = new Invoker(semaphore, weigth, timeout);
        final Invoker existing = providers.putIfAbsent(ic.getMethod(), i);
        if (existing != null) {
            i = existing;
        }
    }
    return i;
}
Also used : Throttling(org.apache.deltaspike.core.api.throttling.Throttling) Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) Semaphore(java.util.concurrent.Semaphore) Throttled(org.apache.deltaspike.core.api.throttling.Throttled)

Example 8 with AnnotatedMethod

use of javax.enterprise.inject.spi.AnnotatedMethod 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 9 with AnnotatedMethod

use of javax.enterprise.inject.spi.AnnotatedMethod 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<Interceptor<?>>());
        entry.getValue().setCdiInterceptors(new ArrayList<Interceptor<?>>());
    }
    // 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<>();
        annotations.addAll(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)

Aggregations

AnnotatedMethod (javax.enterprise.inject.spi.AnnotatedMethod)9 Method (java.lang.reflect.Method)6 AnnotatedType (javax.enterprise.inject.spi.AnnotatedType)4 Annotation (java.lang.annotation.Annotation)3 HashSet (java.util.HashSet)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 HashMap (java.util.HashMap)2 Field (java.lang.reflect.Field)1 Member (java.lang.reflect.Member)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 WeakHashMap (java.util.WeakHashMap)1 ExecutorService (java.util.concurrent.ExecutorService)1 Semaphore (java.util.concurrent.Semaphore)1 Lock (java.util.concurrent.locks.Lock)1