Example usage for javax.transaction UserTransaction getStatus

List of usage examples for javax.transaction UserTransaction getStatus

Introduction

In this page you can find the example usage for javax.transaction UserTransaction getStatus.

Prototype

int getStatus() throws SystemException;

Source Link

Document

Obtain the status of the transaction associated with the current thread.

Usage

From source file:com.gybas.evaluation.quartz.jobs.UserTransactionLookup.java

@Override
public void run() {
    try {//from  w ww . j a  v  a  2 s.  co  m
        final UserTransaction userTransaction = jndiTemplate.lookup(USER_TRANSACTION_JNDI_NAME,
                UserTransaction.class);
        LOGGER.info("Status of user transaction is [{}]", userTransaction.getStatus());
    } catch (NamingException e) {
        LOGGER.error("Could not lookup user transaction", e);
    } catch (SystemException e) {
        LOGGER.error("Could not determine user transaction status", e);
    }
}

From source file:edu.harvard.i2b2.crc.ejb.QueryExecutorMDB.java

/**
 * Take the XML based message and delegate to the system coordinator to
 * handle the actual processing/*w w  w  . jav a2  s  . co m*/
 * 
 * @param msg
 *            th JMS TextMessage object containing XML data
 */
public void onMessage(Message msg) {
    MapMessage message = null;
    QueueConnection conn = null;
    QueueSession session = null;
    QueueSender sender = null;
    QueryProcessorUtil qpUtil = QueryProcessorUtil.getInstance();
    Queue replyToQueue = null;
    UserTransaction transaction = sessionContext.getUserTransaction();
    // default timeout three minutes
    int transactionTimeout = 0;

    try {

        transactionTimeout = this.readTimeoutPropertyValue(SMALL_QUEUE);
        if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.MEDIUM_QUEUE)) {
            // four hours
            // transactionTimeout = 14400;
            transactionTimeout = this.readTimeoutPropertyValue(MEDIUM_QUEUE);
        } else if (callingMDBName.equalsIgnoreCase(QueryExecutorMDB.LARGE_QUEUE)) {
            // twelve hours
            // transactionTimeout = 43200;
            transactionTimeout = this.readTimeoutPropertyValue(LARGE_QUEUE);
        }

        transaction.setTransactionTimeout(transactionTimeout);

        transaction.begin();
        message = (MapMessage) msg;
        String sessionId = msg.getJMSCorrelationID();
        replyToQueue = (Queue) msg.getJMSReplyTo();
        log.debug("Extracting the message [" + msg.getJMSMessageID() + " ] on " + callingMDBName);
        transaction.commit();
        ExecRunnable er = new ExecRunnable(transaction, transactionTimeout, callingMDBName, message, sessionId);
        er.execute();

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            if (transaction.getStatus() != 4) {

                transaction.rollback();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.error("Error extracting message", ex);
    } finally {

        QueryManagerBeanUtil qmBeanUtil = new QueryManagerBeanUtil();
        qmBeanUtil.closeAll(sender, null, conn, session);
    }
}

From source file:com.surevine.alfresco.repo.delete.PerishabilityLogicImpl.java

private synchronized void loadPerishReasons()
        throws JSONException, SecurityException, IllegalStateException, RollbackException,
        HeuristicMixedException, HeuristicRollbackException, SystemException, NotSupportedException {
    UserTransaction transaction = null;
    ResultSet rs = null;/*from  w  w  w .ja  va 2 s  . co m*/

    try {
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        rs = _searchService.query(storeRef, SearchService.LANGUAGE_LUCENE,
                "PATH:\"/app:company_home/app:dictionary/cm:perishableReasons.json\"");
        NodeRef nodeRef = null;
        transaction = _transactionService.getUserTransaction(true);

        transaction.begin();

        if (rs.length() == 0) {
            _logger.error(
                    "Unable to load perishable reasons: Didn't find perishableReasons.json in the Data Dictionary.");
            perishReasons = Collections.emptyList();
            perishReasonsByCode = Collections.emptyMap();
            perishReasonsBySite = Collections.emptyMap();
            return;
        }
        nodeRef = rs.getNodeRef(0);

        ContentReader reader = _contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);

        JSONObject obj = new JSONObject(reader.getContentString());

        JSONArray perishableReasons = obj.getJSONArray("perishableReasons");

        perishReasons = new ArrayList<PerishReason>(perishableReasons.length());
        perishReasonsByCode = new HashMap<String, PerishReason>();
        perishReasonsBySite = new HashMap<String, List<PerishReason>>();

        for (int i = 0; i < perishableReasons.length(); ++i) {
            PerishReason reason = PerishReason.fromJSON(perishableReasons.getJSONObject(i));
            perishReasons.add(reason);
            perishReasonsByCode.put(reason.getCode(), reason);
            addPerishReasonBySite(reason);
        }

        transaction.commit();
    } finally {
        if (rs != null) {
            rs.close();
        }

        if ((transaction != null) && (transaction.getStatus() == Status.STATUS_ACTIVE)) {
            transaction.rollback();
        }
    }
}

From source file:de.fme.topx.component.TopXUpdateComponent.java

/**
 * increase the hitcount for the given noderef by using the aspect
 * <code>topx:countable</code>. Does not fire events for other behaviours.
 * Using admin use to increment because not everybody has
 * //w  w  w.  j a va2s  .co m
 * @param nodeRef
 * @param userName
 *            current user who reads or updates the document.
 * @param counterUserProperty
 * @throws SystemException
 * @throws NotSupportedException
 * @throws HeuristicRollbackException
 * @throws HeuristicMixedException
 * @throws RollbackException
 * @throws IllegalStateException
 * @throws SecurityException
 */
@SuppressWarnings("unchecked")
public Integer increaseHitcount(final NodeRef nodeRef, final String userName, final QName counterProperty,
        final QName counterDateProperty, final QName counterUserProperty)
        throws NotSupportedException, SystemException, SecurityException, IllegalStateException,
        RollbackException, HeuristicMixedException, HeuristicRollbackException {
    UserTransaction transaction = transactionService.getNonPropagatingUserTransaction(false);
    transaction.begin();

    try {
        Preconditions.checkNotNull(nodeRef, "Passed noderef should not be null");
        Preconditions.checkArgument(nodeService.exists(nodeRef),
                "Node[" + nodeRef + "] must exist in the repository");
        filter.disableAllBehaviours();
        Map<QName, Serializable> newProperties = Maps.newHashMap();
        Integer counter = (Integer) nodeService.getProperty(nodeRef, counterProperty);
        if (counter == null) {
            counter = setHitCountProperties(nodeRef, counterProperty, counterDateProperty, counterUserProperty,
                    newProperties, 1, userName);
        } else {
            boolean shouldCount = true;
            Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
            Serializable usersValue = properties.get(counterUserProperty);

            List<String> users;
            if (!(usersValue instanceof List)) {
                users = Lists.newArrayList((String) usersValue);
            } else {
                users = (List<String>) usersValue;
            }

            if (users != null) {
                int userIndex = users.indexOf(userName);
                if (userIndex != -1) {
                    List<Date> counterDates = (List<Date>) properties.get(counterDateProperty);
                    Date lastUserReadDate = counterDates.get(userIndex);
                    // only count one download for a
                    // document of
                    // a user per day
                    if (DateUtils.isSameDay(lastUserReadDate, new Date())) {
                        shouldCount = false;
                        LOG.info("User " + userName + " already downloads/updates document " + nodeRef
                                + " today. Skip counting.");
                    }
                }
            }
            if (shouldCount) {
                counter = setHitCountProperties(nodeRef, counterProperty, counterDateProperty,
                        counterUserProperty, newProperties, counter, userName);
            }

        }
        transaction.commit();
        LOG.info("Commiting transaction for Node " + nodeRef);
        return counter;
    } finally {
        filter.enableAllBehaviours();
        if (transaction.getStatus() == javax.transaction.Status.STATUS_ACTIVE) {
            transaction.rollback();
            LOG.warn("Had to rollback the transaction for Node " + nodeRef);
        }

    }
}

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

/**
 * Import a document/* ww w  .  jav  a  2 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:org.alfresco.filesys.alfresco.AlfrescoTxDiskDriver.java

/**
 * End an active transaction/*  w w w .j a  v  a 2 s .com*/
 * 
 * @param sess SrvSession
 * @param tx Object
 */
public void endTransaction(SrvSession sess, Object tx) {

    // Check that the transaction object is valid

    if (tx == null)
        return;

    // Get the filesystem transaction

    FilesysTransaction filesysTx = (FilesysTransaction) tx;

    // Check if there is an active transaction

    if (filesysTx != null && filesysTx.hasTransaction()) {
        // Get the active transaction

        UserTransaction ftx = filesysTx.getTransaction();

        try {
            // Commit or rollback the transaction

            if (ftx.getStatus() == Status.STATUS_MARKED_ROLLBACK || ftx.getStatus() == Status.STATUS_ROLLEDBACK
                    || ftx.getStatus() == Status.STATUS_ROLLING_BACK) {
                // Transaction is marked for rollback

                ftx.rollback();

                // DEBUG

                if (logger.isDebugEnabled())
                    logger.debug("End transaction (rollback)");
            } else {
                // Commit the transaction

                ftx.commit();

                // DEBUG

                if (logger.isDebugEnabled())
                    logger.debug("End transaction (commit)");
            }
        } catch (Exception ex) {
            if (logger.isDebugEnabled())
                logger.debug("Failed to end transaction, " + ex.getMessage());
            //              throw new AlfrescoRuntimeException("Failed to end transaction", ex);
        } finally {
            // Clear the current transaction

            sess.clearTransaction();
        }
    }
}

From source file:org.alfresco.filesys.alfresco.AlfrescoTxDiskDriver.java

/**
 * Create and start a transaction, if not already active
 * /*from  w w  w  . ja  v  a  2 s. com*/
 * @param sess SrvSession
 * @param readOnly boolean
 * @exception AlfrescoRuntimeException
 */
private final void beginTransaction(SrvSession sess, boolean readOnly) throws AlfrescoRuntimeException {
    // Do nothing if we are already in a retrying transaction
    Boolean inRetryingTransaction = m_inRetryingTransaction.get();

    if (inRetryingTransaction != null && inRetryingTransaction) {
        return;
    }

    // Initialize the per session thread local that holds the transaction

    sess.initializeTransactionObject();

    // Get the filesystem transaction

    FilesysTransaction filesysTx = (FilesysTransaction) sess.getTransactionObject().get();
    if (filesysTx == null) {
        filesysTx = new FilesysTransaction();
        sess.getTransactionObject().set(filesysTx);
    }

    // If there is an active transaction check that it is the required type

    if (filesysTx.hasTransaction()) {
        // Get the active transaction

        UserTransaction tx = filesysTx.getTransaction();

        // Check if the current transaction is marked for rollback

        try {
            if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK || tx.getStatus() == Status.STATUS_ROLLEDBACK
                    || tx.getStatus() == Status.STATUS_ROLLING_BACK) {
                //  Rollback the current transaction

                tx.rollback();
            }
        } catch (Exception ex) {
        }

        // Check if the transaction is a write transaction, if write has been requested

        if (readOnly == false && filesysTx.isReadOnly() == true) {
            // Commit the read-only transaction

            try {
                tx.commit();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(
                        "Failed to commit read-only transaction, " + ex.getMessage());
            } finally {
                // Clear the active transaction

                filesysTx.clearTransaction();
            }
        }
    }

    // Create the transaction

    if (filesysTx.hasTransaction() == false) {
        try {
            // Create a new transaction

            UserTransaction userTrans = m_transactionService.getUserTransaction(readOnly);
            userTrans.begin();

            // Store the transaction

            filesysTx.setTransaction(userTrans, readOnly);

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("Created transaction readOnly=" + readOnly);
        } catch (Exception ex) {
            throw new AlfrescoRuntimeException("Failed to create transaction, " + ex.getMessage());
        }
    }

    //  Store the transaction callback

    sess.setTransaction(this);
}

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 {//  w w  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;
    }
}

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

public void testTransactionalCacheDisableSharedCaches() 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 w w w . j  a  va  2 s .co  m*/
        // begin a transaction
        txn.begin();

        // Go directly past ALL shared caches
        transactionalCache.setDisableSharedCacheReadForTransaction(true);

        // Try to get results in shared caches
        assertNull("Read of mutable shared cache MUST NOT use backing cache",
                transactionalCache.get(NEW_GLOBAL_ONE));
        assertNull("Value should not be in any cache", transactionalCache.get(UPDATE_TXN_THREE));

        // Update the transactional caches
        transactionalCache.put(NEW_GLOBAL_TWO, "An update");
        transactionalCache.put(UPDATE_TXN_THREE, UPDATE_TXN_THREE);

        // Try to get results in shared caches
        assertNull("Read of mutable shared cache MUST NOT use backing cache",
                transactionalCache.get(NEW_GLOBAL_ONE));
        assertEquals("Value should be in transactional cache", "An update",
                transactionalCache.get(NEW_GLOBAL_TWO));
        assertEquals("Value should be in transactional cache", UPDATE_TXN_THREE,
                transactionalCache.get(UPDATE_TXN_THREE));

        txn.commit();

        // Now check that values were not written through for any caches
        assertEquals("Out-of-txn read must return shared value", NEW_GLOBAL_ONE,
                transactionalCache.get(NEW_GLOBAL_ONE));
        assertNull("Value should be removed from shared cache", transactionalCache.get(NEW_GLOBAL_TWO));
        assertEquals("New values must be written to shared cache", UPDATE_TXN_THREE,
                transactionalCache.get(UPDATE_TXN_THREE));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}

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

public void testTransactionalCacheStatsOnCommit() throws Throwable {
    // add item to global cache
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test1", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test2", "v", null);
    TransactionalCache.putSharedCacheValue(backingCache, "stats-test3", "v", null);

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

    final long hitsAtStart = cacheStats.count("transactionalCache", OpType.GET_HIT);
    final long missesAtStart = cacheStats.count("transactionalCache", OpType.GET_MISS);
    final long putsAtStart = cacheStats.count("transactionalCache", OpType.PUT);
    final long removesAtStart = cacheStats.count("transactionalCache", OpType.REMOVE);
    final long clearsAtStart = cacheStats.count("transactionalCache", OpType.CLEAR);

    try {/*from   w  w  w  .j  ava  2s. c om*/
        // begin a transaction
        txn.begin();

        // Perform some puts
        transactionalCache.put("stats-test4", "v");
        transactionalCache.put("stats-test5", "v");
        transactionalCache.put("stats-test6", "v");
        transactionalCache.put("stats-test7", "v");
        transactionalCache.put("stats-test8", "v");

        // Perform some gets...
        // hits
        transactionalCache.get("stats-test3");
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // repeated hits won't touch the shared cache
        transactionalCache.get("stats-test2");
        transactionalCache.get("stats-test1");
        // misses - not yet committed
        transactionalCache.get("stats-miss1");
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");
        transactionalCache.get("stats-miss4");
        // repeated misses won't touch the shared cache
        transactionalCache.get("stats-miss2");
        transactionalCache.get("stats-miss3");

        // Perform some removals
        transactionalCache.remove("stats-test1");
        transactionalCache.remove("stats-test2");
        transactionalCache.remove("stats-test3");
        transactionalCache.remove("stats-test9");
        transactionalCache.remove("stats-test10");
        transactionalCache.remove("stats-test11");
        transactionalCache.remove("stats-test12");
        transactionalCache.remove("stats-test13");

        // Check nothing has changed yet - changes not written through until commit or rollback
        assertEquals(hitsAtStart, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart, cacheStats.count("transactionalCache", OpType.PUT));
        assertEquals(removesAtStart, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(clearsAtStart, cacheStats.count("transactionalCache", OpType.CLEAR));

        // commit the transaction
        txn.commit();

        // TODO: remove is called twice for each remove (in beforeCommit and afterCommit) - check this is correct.
        assertEquals(removesAtStart + 16, cacheStats.count("transactionalCache", OpType.REMOVE));
        assertEquals(hitsAtStart + 3, cacheStats.count("transactionalCache", OpType.GET_HIT));
        assertEquals(missesAtStart + 4, cacheStats.count("transactionalCache", OpType.GET_MISS));
        assertEquals(putsAtStart + 5, cacheStats.count("transactionalCache", OpType.PUT));
        // Performing a clear would affect the other stats, so a separate test is required.
        assertEquals(clearsAtStart + 0, cacheStats.count("transactionalCache", OpType.CLEAR));
    } catch (Throwable e) {
        if (txn.getStatus() == Status.STATUS_ACTIVE) {
            txn.rollback();
        }
        throw e;
    }
}