Example usage for javax.transaction Status STATUS_ACTIVE

List of usage examples for javax.transaction Status STATUS_ACTIVE

Introduction

In this page you can find the example usage for javax.transaction Status STATUS_ACTIVE.

Prototype

int STATUS_ACTIVE

To view the source code for javax.transaction Status STATUS_ACTIVE.

Click Source Link

Document

A transaction is associated with the target object and it is in the active state.

Usage

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

public synchronized void setRollbackOnly() throws IllegalStateException, SystemException {
    // just a check
    TransactionInfo txnInfo = getTransactionInfo();

    int status = getStatus();
    // check the status
    if (status == Status.STATUS_MARKED_ROLLBACK) {
        // this is acceptable
    } else if (status == Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("The transaction has not been started yet");
    } else if (status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK) {
        throw new IllegalStateException("The transaction has already been rolled back");
    } else if (status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED) {
        throw new IllegalStateException("The transaction has already been committed");
    } else if (status != Status.STATUS_ACTIVE) {
        throw new IllegalStateException("The transaction is not active: " + status);
    }/*from  w  ww  . ja v  a2 s .  c  o  m*/

    // mark for rollback
    txnInfo.getTransactionStatus().setRollbackOnly();
    // make sure that we record the fact that we have been marked for rollback
    internalStatus = Status.STATUS_MARKED_ROLLBACK;
    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Set transaction status to rollback only: " + this);
    }
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * @throws NotSupportedException if an attempt is made to reuse this instance
 *///from  www. j  ava 2  s. c  om
public synchronized void begin() throws NotSupportedException, SystemException {
    // make sure that the status and info align - the result may or may not be null
    @SuppressWarnings("unused")
    TransactionInfo txnInfo = getTransactionInfo();
    if (internalStatus != Status.STATUS_NO_TRANSACTION) {
        throw new NotSupportedException("The UserTransaction may not be reused");
    }

    // check 

    if ((propagationBehaviour != TransactionDefinition.PROPAGATION_REQUIRES_NEW)) {
        if (!readOnly && TransactionSynchronizationManager.isSynchronizationActive()
                && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            throw new IllegalStateException("Nested writable transaction in a read only transaction");
        }
    }

    // begin a transaction
    try {
        internalTxnInfo = createTransactionIfNecessary((Method) null, (Class<?>) null); // super class will just pass nulls back to us
    } catch (CannotCreateTransactionException e) {
        throw new ConnectionPoolException("The DB connection pool is depleted.", e);
    }

    internalStatus = Status.STATUS_ACTIVE;
    threadId = Thread.currentThread().getId();

    // Record that transaction details now that begin was successful
    isBeginMatched = false;
    if (isCallStackTraced) {
        // get the stack trace
        Exception e = new Exception();
        e.fillInStackTrace();
        beginCallStack = e.getStackTrace();
    }

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Began user transaction: " + this);
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew,
        boolean notSupported) throws Exception {

    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION,
                Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {//from   w ww. j a v  a2 s.  c  o  m
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
                Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }

    final ContentSource contentSource = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    final Session session2 = mock(Session.class);
    given(contentSource.newSession()).willReturn(session1, session2);

    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED
            : TransactionDefinition.PROPAGATION_SUPPORTS);

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
            assertSame(session1, ContentSourceUtils.getSession(contentSource));

            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                    : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                }
            });

            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(session2).close();
    verify(session1).close();
}

From source file:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * @throws IllegalStateException if a transaction was not started
 *//*w w w .  ja  v a2s .co m*/
public synchronized void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException,
        SecurityException, IllegalStateException, SystemException {
    // perform checks
    TransactionInfo txnInfo = getTransactionInfo();

    int status = getStatus();
    // check the status
    if (status == Status.STATUS_NO_TRANSACTION) {
        throw new IllegalStateException("The transaction has not yet begun");
    } else if (status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK) {
        throw new RollbackException("The transaction has already been rolled back");
    } else if (status == Status.STATUS_MARKED_ROLLBACK) {
        throw new RollbackException("The transaction has already been marked for rollback");
    } else if (status == Status.STATUS_COMMITTING || status == Status.STATUS_COMMITTED) {
        throw new IllegalStateException("The transaction has already been committed");
    } else if (status != Status.STATUS_ACTIVE || txnInfo == null) {
        throw new IllegalStateException("No user transaction is active");
    }

    if (!finalized) {
        try {
            // the status seems correct - we can try a commit
            commitTransactionAfterReturning(txnInfo);
        } catch (Throwable e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Transaction didn't commit", e);
            }
            // commit failed
            internalStatus = Status.STATUS_ROLLEDBACK;
            RollbackException re = new RollbackException("Transaction didn't commit: " + e.getMessage());
            // Stick the originating reason for failure into the exception.
            re.initCause(e);
            throw re;
        } finally {
            // make sure that we clean up the stack
            cleanupTransactionInfo(txnInfo);
            finalized = true;
            // clean up leaked transaction logging
            isBeginMatched = true;
            beginCallStack = null;
        }
    }

    // regardless of whether the transaction was finally committed or not, the status
    // as far as UserTransaction is concerned should be 'committed'

    // keep track that this UserTransaction was explicitly committed
    internalStatus = Status.STATUS_COMMITTED;

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Committed user transaction: " + this);
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionWithPropagationRequiresNewAndBeginException(boolean suspendException,
        final boolean openOuterConnection, final boolean useTransactionAwareContentSource) throws Exception {

    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE);
    if (suspendException) {
        given(transactionManager.suspend()).willThrow(new SystemException());
    } else {/*from   ww  w  .j  a  v a  2s  .  com*/
        given(transactionManager.suspend()).willReturn(transaction);
        willThrow(new SystemException()).given(userTransaction).begin();
    }

    given(session.getTransactionMode()).willReturn(Session.TransactionMode.QUERY);

    final ContentSource dsToUse = useTransactionAwareContentSource
            ? new TransactionAwareContentSourceProxy(contentSource)
            : contentSource;
    if (dsToUse instanceof TransactionAwareContentSourceProxy) {
        ((TransactionAwareContentSourceProxy) dsToUse).setReobtainTransactionalSessions(true);
    }

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    final TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
                assertTrue("JTA synchronizations active",
                        TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is new transaction", status.isNewTransaction());

                Session c = ContentSourceUtils.getSession(dsToUse);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                c.getTransactionMode();
                ContentSourceUtils.releaseSession(c, dsToUse);

                c = ContentSourceUtils.getSession(dsToUse);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
                if (!openOuterConnection) {
                    ContentSourceUtils.releaseSession(c, dsToUse);
                }

                try {
                    tt.execute(new TransactionCallbackWithoutResult() {
                        @Override
                        protected void doInTransactionWithoutResult(TransactionStatus status)
                                throws RuntimeException {
                            assertTrue("Hasn't thread session",
                                    !TransactionSynchronizationManager.hasResource(dsToUse));
                            assertTrue("JTA synchronizations active",
                                    TransactionSynchronizationManager.isSynchronizationActive());
                            assertTrue("Is new transaction", status.isNewTransaction());

                            Session c = ContentSourceUtils.getSession(dsToUse);
                            assertTrue("Has thread session",
                                    TransactionSynchronizationManager.hasResource(dsToUse));
                            ContentSourceUtils.releaseSession(c, dsToUse);

                            c = ContentSourceUtils.getSession(dsToUse);
                            assertTrue("Has thread session",
                                    TransactionSynchronizationManager.hasResource(dsToUse));
                            ContentSourceUtils.releaseSession(c, dsToUse);
                        }
                    });
                } finally {
                    if (openOuterConnection) {
                        c.getTransactionMode();
                        ContentSourceUtils.releaseSession(c, dsToUse);

                    }
                }
            }
        });

        fail("Should have thrown TransactionException");
    } catch (TransactionException ex) {
        // expected
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(dsToUse));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    verify(userTransaction).begin();
    if (suspendException) {
        verify(userTransaction).rollback();
    }

    if (suspendException) {
        verify(session, atLeastOnce()).close();
    } else {
        verify(session, never()).close();
    }
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithConnectionHolderStillBound() throws Exception {
    @SuppressWarnings("serial")
    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction) {

        @Override//from   ww  w.j av a2s.co m
        protected void doRegisterAfterCompletionWithJtaTransaction(JtaTransactionObject txObject,
                final List<TransactionSynchronization> synchronizations)
                throws RollbackException, SystemException {
            Thread async = new Thread() {
                @Override
                public void run() {
                    invokeAfterCompletion(synchronizations, TransactionSynchronization.STATUS_COMMITTED);
                }
            };
            async.start();
            try {
                async.join();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    };
    TransactionTemplate tt = new TransactionTemplate(ptm);
    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
    assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

    given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE);
    for (int i = 0; i < 3; i++) {
        final boolean releaseCon = (i != 1);

        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
                assertTrue("JTA synchronizations active",
                        TransactionSynchronizationManager.isSynchronizationActive());
                assertTrue("Is existing transaction", !status.isNewTransaction());

                Session c = ContentSourceUtils.getSession(contentSource);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
                ContentSourceUtils.releaseSession(c, contentSource);

                c = ContentSourceUtils.getSession(contentSource);
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(contentSource));
                if (releaseCon) {
                    ContentSourceUtils.releaseSession(c, contentSource);
                }
            }
        });

        if (!releaseCon) {
            assertTrue("Still has session holder",
                    TransactionSynchronizationManager.hasResource(contentSource));
        } else {
            assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(contentSource));
        }
        assertTrue("JTA synchronizations not active",
                !TransactionSynchronizationManager.isSynchronizationActive());
    }
    verify(session, times(3)).close();
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

@Test
public void testJtaTransactionWithIsolationLevelContentSourceAdapter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final IsolationLevelContentSourceAdapter dsToUse = new IsolationLevelContentSourceAdapter();
    dsToUse.setTargetContentSource(contentSource);
    dsToUse.afterPropertiesSet();//w  w w .ja  va2 s.  com

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.setReadOnly(true);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session).setTransactionMode(Session.TransactionMode.QUERY);
    verify(session, times(2)).close();
}

From source file:se.alingsas.alfresco.repo.utils.byggreda.ByggRedaUtil.java

/**
 * Import a document/*from w  w  w  .j a v  a2  s.c om*/
 * 
 * @param site
 * @param sourcePath
 * @param document
 * @return
 */
private ByggRedaDocument importDocument(SiteInfo site, String sourcePath, ByggRedaDocument document) {
    final String currentDestinationPath = destinationPath + "/" + document.getPath();
    UserTransaction trx = getTransactionService().getNonPropagatingUserTransaction();

    try {
        trx.begin();
        // Check if file exists already
        FileInfo repoFileFolder = getRepoFileFolder(site,
                currentDestinationPath + "/" + document.getFileName());
        if (repoFileFolder != null) {
            if (this.updateExisting) {
                try {
                    String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                            sourcePath + "/" + document.getFileName());
                    if (fullFilenamePath == null) {
                        throw new java.io.FileNotFoundException();
                    }
                    File f = new File(fullFilenamePath);
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    if (!f.exists()) {
                        throw new java.io.FileNotFoundException();
                    }
                    LOG.debug("File " + document.getFileName()
                            + " already exists, attempting to creating a new version at "
                            + currentDestinationPath);
                    final NodeRef workingCopy = checkOutCheckInService.checkout(repoFileFolder.getNodeRef());

                    addProperties(workingCopy, document, true);

                    createFile(workingCopy, site, sourcePath, document);

                    final Map<String, Serializable> properties = new HashMap<String, Serializable>();
                    properties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);
                    NodeRef checkin = checkOutCheckInService.checkin(workingCopy, properties);
                    document.setNodeRef(checkin);
                    if (checkin != null && nodeService.exists(checkin)) {
                        document.setReadSuccessfully(true);
                        document.setStatusMsg("Filen " + sourcePath + "/" + document.getFileName()
                                + " uppdaterades till ny version");
                        trx.commit();
                    } else {
                        document.setReadSuccessfully(false);
                        document.setStatusMsg("Uppdatering av fil " + currentDestinationPath + "/"
                                + document.getFileName() + " misslyckades.");
                        LOG.error(document.getStatusMsg());
                        throw new Exception(document.getStatusMsg());
                    }
                } catch (java.io.FileNotFoundException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                            + document.getFileName() + " kunde inte hittas.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (FileExistsException e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                            + " finns redan.");
                    LOG.error(document.getStatusMsg());
                    throw new Exception(document.getStatusMsg(), e);
                } catch (Exception e) {
                    document.setReadSuccessfully(false);
                    document.setStatusMsg(e.getMessage());
                    LOG.error("Error importing document " + document.getRecordNumber(), e);
                    throw new Exception(document.getStatusMsg(), e);
                }
            } else {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Filen existerar redan, hoppar ver.");
                LOG.debug("File already exists");
                trx.commit();
            }
        } else {
            try {
                String fullFilenamePath = checkFileExistsIgnoreExtensionCase(
                        sourcePath + "/" + document.getFileName());
                if (fullFilenamePath == null) {
                    throw new java.io.FileNotFoundException();
                }
                File f = new File(fullFilenamePath);
                if (!f.exists()) {
                    throw new java.io.FileNotFoundException();
                }
                NodeRef folderNodeRef = createFolder(destinationPath, document.getPath(),
                        document.getOriginalPath(), site);
                final FileInfo fileInfo = fileFolderService.create(folderNodeRef, document.getFileName(),
                        AkDmModel.TYPE_AKDM_BYGGREDA_DOC);
                document.setNodeRef(fileInfo.getNodeRef());
                addProperties(document.getNodeRef(), document, false);
                createFile(document.getNodeRef(), site, sourcePath, document);
                createVersionHistory(document.getNodeRef());
                document.setReadSuccessfully(true);
                LOG.debug("Imported document " + document.getRecordDisplay());
                trx.commit();
            } catch (java.io.FileNotFoundException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, filen " + sourcePath + "/"
                        + document.getFileName() + " kunde inte hittas.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (FileExistsException e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Inlsning av fil misslyckades, mlfilen " + currentDestinationPath
                        + " finns redan.");
                LOG.error(document.getStatusMsg());
                throw new Exception(document.getStatusMsg(), e);
            } catch (Exception e) {
                document.setReadSuccessfully(false);
                document.setStatusMsg("Fel vid inlsning av fil, systemmeddelande: " + e.getMessage());
                LOG.error("Error importing document " + document.getRecordNumber(), e);
                throw new Exception(document.getStatusMsg(), e);
            }
        }
    } catch (Exception e) {
        try {
            if (trx.getStatus() == Status.STATUS_ACTIVE) {
                trx.rollback();
            } else {
                LOG.error("The transaction was not active", e);
            }
            return document;
        } catch (Exception e2) {
            LOG.error("Exception: ", e);
            LOG.error("Exception while rolling back transaction", e2);
            throw new RuntimeException(e2);
        }

    }
    return document;

}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionWithIsolationLevelContentSourceRouter() throws Exception {
    given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
            Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

    final ContentSource contentSource1 = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    given(contentSource1.newSession()).willReturn(session1);

    final ContentSource contentSource2 = mock(ContentSource.class);
    final Session session2 = mock(Session.class);
    given(contentSource2.newSession()).willReturn(session2);

    final IsolationLevelContentSourceRouter dsToUse = new IsolationLevelContentSourceRouter();
    Map<Object, Object> targetContentSources = new HashMap<Object, Object>();

    targetContentSources.put("ISOLATION_REPEATABLE_READ", contentSource2);
    dsToUse.setDefaultTargetContentSource(contentSource1);

    dsToUse.setTargetContentSources(targetContentSources);
    dsToUse.afterPropertiesSet();/*w  w  w .j  av  a2  s  .  co  m*/

    JtaTransactionManager ptm = new JtaTransactionManager(userTransaction);
    ptm.setAllowCustomIsolationLevels(true);

    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session1, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
            Session c = ContentSourceUtils.getSession(dsToUse);
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(dsToUse));
            assertSame(session2, c);
            ContentSourceUtils.releaseSession(c, dsToUse);
        }
    });

    verify(userTransaction, times(2)).begin();
    verify(userTransaction, times(2)).commit();
    verify(session1).close();
    verify(session2).close();
}

From source file:org.alfresco.repo.cache.CacheTest.java

public void testTransactionalCacheWithSingleTxn() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_ONE, NEW_GLOBAL_ONE, null);
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_TWO, NEW_GLOBAL_TWO, null);
    TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_THREE, NEW_GLOBAL_THREE, null);

    TransactionService transactionService = serviceRegistry.getTransactionService();
    UserTransaction txn = transactionService.getUserTransaction();

    try {/*from  ww  w  .ja  v  a  2  s . c o m*/
        // begin a transaction
        txn.begin();

        // remove 1 from the cache
        transactionalCache.remove(NEW_GLOBAL_ONE);
        assertFalse("Item was not removed from txn cache", transactionalCache.contains(NEW_GLOBAL_ONE));
        assertNull("Get didn't return null", transactionalCache.get(NEW_GLOBAL_ONE));
        assertTrue("Item was removed from backing cache", backingCache.contains(NEW_GLOBAL_ONE));

        // read 2 from the cache
        assertEquals("Item not read from backing cache", NEW_GLOBAL_TWO,
                transactionalCache.get(NEW_GLOBAL_TWO));
        // Change the backing cache
        TransactionalCache.putSharedCacheValue(backingCache, NEW_GLOBAL_TWO, NEW_GLOBAL_TWO + "-updated", null);
        // Ensure read-committed
        assertEquals("Read-committed not preserved", NEW_GLOBAL_TWO, transactionalCache.get(NEW_GLOBAL_TWO));

        // update 3 in the cache
        transactionalCache.put(UPDATE_TXN_THREE, "XXX");
        assertEquals("Item not updated in txn cache", "XXX", transactionalCache.get(UPDATE_TXN_THREE));
        assertFalse("Item was put into backing cache", backingCache.contains(UPDATE_TXN_THREE));

        // check that the keys collection is correct
        Collection<String> transactionalKeys = transactionalCache.getKeys();
        assertFalse("Transactionally removed item found in keys", transactionalKeys.contains(NEW_GLOBAL_ONE));
        assertTrue("Transactionally added item not found in keys",
                transactionalKeys.contains(UPDATE_TXN_THREE));

        // Register a post-commit cache reader to make sure that nothing blows up if the cache is hit in post-commit
        PostCommitCacheReader listenerReader = new PostCommitCacheReader(transactionalCache, UPDATE_TXN_THREE);
        AlfrescoTransactionSupport.bindListener(listenerReader);

        // Register a post-commit cache reader to make sure that nothing blows up if the cache is hit in post-commit
        PostCommitCacheWriter listenerWriter = new PostCommitCacheWriter(transactionalCache, UPDATE_TXN_FOUR,
                "FOUR");
        AlfrescoTransactionSupport.bindListener(listenerWriter);

        // commit the transaction
        txn.commit();

        // Check the post-commit stressers
        if (listenerReader.e != null) {
            throw listenerReader.e;
        }
        if (listenerWriter.e != null) {
            throw listenerWriter.e;
        }

        // check that backing cache was updated with the in-transaction changes
        assertFalse("Item was not removed from backing cache", backingCache.contains(NEW_GLOBAL_ONE));
        assertNull("Item could still be fetched from backing cache",
                TransactionalCache.getSharedCacheValue(backingCache, NEW_GLOBAL_ONE, null));
        assertEquals("Item not updated in backing cache", "XXX",
                TransactionalCache.getSharedCacheValue(backingCache, UPDATE_TXN_THREE, null));

        // Check that the transactional cache serves get requests
        assertEquals("Transactional cache must serve post-commit get requests", "XXX",
                transactionalCache.get(UPDATE_TXN_THREE));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}