Search in sources :

Example 6 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class LifecycleMethodTransactionManagementTestCase method testStatefulRequiresNew.

@Test
public void testStatefulRequiresNew() throws SystemException, NotSupportedException, NamingException {
    UserTransaction userTransaction = (UserTransaction) new InitialContext().lookup("java:jboss/UserTransaction");
    TransactionSynchronizationRegistry tsr = (TransactionSynchronizationRegistry) new InitialContext().lookup("java:jboss/TransactionSynchronizationRegistry");
    userTransaction.begin();
    StatefulRequiresNewLifecycleBean required = (StatefulRequiresNewLifecycleBean) new InitialContext().lookup("java:module/StatefulRequiresNewLifecycleBean");
    try {
        Object key = tsr.getTransactionKey();
        Assert.assertNotSame(key, required.getKey());
        Assert.assertEquals(Status.STATUS_ACTIVE, required.getState());
    } finally {
        userTransaction.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 7 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class TransactionManagerTest method testTransactionSynchronizationRegistryBoundToJndi.

@Test
public void testTransactionSynchronizationRegistryBoundToJndi() throws NamingException {
    TransactionSynchronizationRegistry tm = (TransactionSynchronizationRegistry) new InitialContext().lookup("java:jboss/TransactionSynchronizationRegistry");
    Assert.assertNotNull(tm);
}
Also used : TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 8 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class TestWildFlyTSR method test.

@Test
public void test() throws NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
    jtaPropertyManager.getJTAEnvironmentBean().setTransactionManagerClassName("com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple");
    final TransactionSynchronizationRegistry tsr = new TransactionSynchronizationRegistryWrapper(new com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple());
    TransactionManager transactionManager = com.arjuna.ats.jta.TransactionManager.transactionManager();
    transactionManager.begin();
    tsr.registerInterposedSynchronization(new Synchronization() {

        @Override
        public void beforeCompletion() {
            tsr.registerInterposedSynchronization(new Synchronization() {

                @Override
                public void beforeCompletion() {
                    innerSyncCalled = true;
                }

                @Override
                public void afterCompletion(int status) {
                }
            });
        }

        @Override
        public void afterCompletion(int status) {
        }
    });
    transactionManager.commit();
    assertTrue(innerSyncCalled);
}
Also used : TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) TransactionManager(javax.transaction.TransactionManager) Synchronization(javax.transaction.Synchronization) TransactionSynchronizationRegistryWrapper(org.jboss.as.txn.service.internal.tsr.TransactionSynchronizationRegistryWrapper) Test(org.junit.Test)

Example 9 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class StatefulSessionSynchronizationInterceptor method processInvocation.

@Override
public Object processInvocation(final InterceptorContext context) throws Exception {
    final StatefulSessionComponent component = getComponent(context, StatefulSessionComponent.class);
    final StatefulSessionComponentInstance instance = getComponentInstance(context);
    final OwnableReentrantLock lock = instance.getLock();
    final Object threadLock = instance.getThreadLock();
    final AtomicInteger invocationSyncState = instance.getInvocationSynchState();
    final TransactionSynchronizationRegistry transactionSynchronizationRegistry = component.getTransactionSynchronizationRegistry();
    final Object lockOwner = getLockOwner(transactionSynchronizationRegistry);
    final AccessTimeoutDetails timeout = component.getAccessTimeout(context.getMethod());
    boolean toDiscard = false;
    if (ROOT_LOGGER.isTraceEnabled()) {
        ROOT_LOGGER.trace("Trying to acquire lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
    }
    // we obtain a lock in this synchronization interceptor because the lock needs to be tied to the synchronization
    // so that it can released on the tx synchronization callbacks
    boolean acquired = lock.tryLock(timeout.getValue(), timeout.getTimeUnit(), lockOwner);
    if (!acquired) {
        throw EjbLogger.ROOT_LOGGER.failToObtainLock(component.getComponentName(), timeout.getValue(), timeout.getTimeUnit());
    }
    synchronized (threadLock) {
        //invocation in progress
        invocationSyncState.set(SYNC_STATE_INVOCATION_IN_PROGRESS);
        if (ROOT_LOGGER.isTraceEnabled()) {
            ROOT_LOGGER.trace("Acquired lock: " + lock + " for stateful component instance: " + instance + " during invocation: " + context);
        }
        Object currentTransactionKey = null;
        boolean wasTxSyncRegistered = false;
        try {
            //so enrolling in an existing transaction is not correct
            if (containerManagedTransactions) {
                if (!instance.isSynchronizationRegistered()) {
                    // get the key to current transaction associated with this thread
                    currentTransactionKey = transactionSynchronizationRegistry.getTransactionKey();
                    final int status = transactionSynchronizationRegistry.getTransactionStatus();
                    // if the thread is currently associated with a tx, then register a tx synchronization
                    if (currentTransactionKey != null && status != Status.STATUS_COMMITTED && status != Status.STATUS_ROLLEDBACK) {
                        // register a tx synchronization for this SFSB instance
                        final Synchronization statefulSessionSync = new StatefulSessionSynchronization(instance);
                        transactionSynchronizationRegistry.registerInterposedSynchronization(statefulSessionSync);
                        wasTxSyncRegistered = true;
                        if (ROOT_LOGGER.isTraceEnabled()) {
                            ROOT_LOGGER.trace("Registered tx synchronization: " + statefulSessionSync + " for tx: " + currentTransactionKey + " associated with stateful component instance: " + instance);
                        }
                        // invoke the afterBegin callback on the SFSB
                        instance.afterBegin();
                        instance.setSynchronizationRegistered(true);
                        context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(true));
                    }
                } else {
                    context.putPrivateData(StatefulTransactionMarker.class, StatefulTransactionMarker.of(false));
                }
            }
            // proceed with the invocation
            try {
                return context.proceed();
            } catch (Exception e) {
                if (component.shouldDiscard(e, context.getMethod())) {
                    toDiscard = true;
                }
                throw e;
            }
        } finally {
            // taken care off by a tx synchronization callbacks.
            if (!wasTxSyncRegistered && !instance.isSynchronizationRegistered()) {
                releaseInstance(instance);
            } else if (!wasTxSyncRegistered) {
                //if we don't release the lock here then it will be acquired multiple times
                //and only released once
                releaseLock(instance);
                //we also call the cache release to decrease the usage count
                if (!instance.isDiscarded()) {
                    instance.getComponent().getCache().release(instance);
                }
            }
            for (; ; ) {
                int state = invocationSyncState.get();
                if (state == SYNC_STATE_INVOCATION_IN_PROGRESS && invocationSyncState.compareAndSet(SYNC_STATE_INVOCATION_IN_PROGRESS, SYNC_STATE_NO_INVOCATION)) {
                    break;
                } else if (state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED || state == SYNC_STATE_AFTER_COMPLETE_DELAYED_NO_COMMIT) {
                    try {
                        //invoke the after completion method, other after completion syncs may have already run
                        handleAfterCompletion(state == SYNC_STATE_AFTER_COMPLETE_DELAYED_COMMITTED, instance, toDiscard);
                    } finally {
                        invocationSyncState.set(SYNC_STATE_NO_INVOCATION);
                    }
                } else {
                    EjbLogger.ROOT_LOGGER.unexpectedInvocationState(state);
                    break;
                }
            }
        }
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) OwnableReentrantLock(org.jboss.as.ejb3.tx.OwnableReentrantLock) AccessTimeoutDetails(org.jboss.as.ejb3.concurrency.AccessTimeoutDetails) Synchronization(javax.transaction.Synchronization) EJBException(javax.ejb.EJBException)

Example 10 with TransactionSynchronizationRegistry

use of javax.transaction.TransactionSynchronizationRegistry in project wildfly by wildfly.

the class StatefulSessionSynchronizationInterceptorTestCase method testDifferentTx.

/**
     * After the bean is accessed within a tx and the tx has committed, the
     * association should be gone (and thus it is ready for another tx).
     */
@Test
public void testDifferentTx() throws Exception {
    final Interceptor interceptor = new StatefulSessionSynchronizationInterceptor(true);
    final InterceptorContext context = new InterceptorContext();
    context.setInterceptors(Arrays.asList(noop()));
    final StatefulSessionComponent component = mock(StatefulSessionComponent.class);
    context.putPrivateData(Component.class, component);
    when(component.getAccessTimeout(null)).thenReturn(defaultAccessTimeout());
    Cache<SessionID, StatefulSessionComponentInstance> cache = mock(Cache.class);
    when(component.getCache()).thenReturn(cache);
    final TransactionSynchronizationRegistry transactionSynchronizationRegistry = mock(TransactionSynchronizationRegistry.class);
    when(component.getTransactionSynchronizationRegistry()).thenReturn(transactionSynchronizationRegistry);
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX1");
    final List<Synchronization> synchronizations = new LinkedList<Synchronization>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Synchronization synchronization = (Synchronization) invocation.getArguments()[0];
            synchronizations.add(synchronization);
            return null;
        }
    }).when(transactionSynchronizationRegistry).registerInterposedSynchronization((Synchronization) any());
    final StatefulSessionComponentInstance instance = new StatefulSessionComponentInstance(component, org.jboss.invocation.Interceptors.getTerminalInterceptor(), Collections.EMPTY_MAP, Collections.emptyMap());
    context.putPrivateData(ComponentInstance.class, instance);
    interceptor.processInvocation(context);
    // commit
    for (Synchronization synchronization : synchronizations) {
        synchronization.beforeCompletion();
    }
    for (Synchronization synchronization : synchronizations) {
        synchronization.afterCompletion(Status.STATUS_COMMITTED);
    }
    synchronizations.clear();
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX2");
    interceptor.processInvocation(context);
}
Also used : Synchronization(javax.transaction.Synchronization) LinkedList(java.util.LinkedList) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InterceptorContext(org.jboss.invocation.InterceptorContext) Interceptor(org.jboss.invocation.Interceptor) SessionID(org.jboss.ejb.client.SessionID) Test(org.junit.Test)

Aggregations

TransactionSynchronizationRegistry (javax.transaction.TransactionSynchronizationRegistry)23 TransactionManager (javax.transaction.TransactionManager)14 InitialContext (javax.naming.InitialContext)6 Synchronization (javax.transaction.Synchronization)4 UserTransaction (javax.transaction.UserTransaction)4 ServiceName (org.jboss.msc.service.ServiceName)4 Test (org.junit.Test)4 HashMap (java.util.HashMap)3 BeanManager (javax.enterprise.inject.spi.BeanManager)3 Context (javax.naming.Context)3 ValidatorFactory (javax.validation.ValidatorFactory)3 XATerminator (com.arjuna.ats.internal.jbossatx.jta.jca.XATerminator)2 TransactionManagerImple (com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple)2 TransactionSynchronizationRegistryImple (com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple)2 JTAEnvironmentBean (com.arjuna.ats.jta.common.JTAEnvironmentBean)2 LinkedList (java.util.LinkedList)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 NamingException (javax.naming.NamingException)2 BeanContext (org.apache.openejb.BeanContext)2 OpenEJBException (org.apache.openejb.OpenEJBException)2