Example usage for org.springframework.transaction TransactionDefinition getIsolationLevel

List of usage examples for org.springframework.transaction TransactionDefinition getIsolationLevel

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition getIsolationLevel.

Prototype

default int getIsolationLevel() 

Source Link

Document

Return the isolation level.

Usage

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

/**
 * Prepare the given Session with the given transaction semantics.
 * @param ses the Session to prepare/*from   w  ww . j a  v  a  2 s  .co m*/
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws XccException if thrown by XDBC methods
 * @see #resetSessionAfterTransaction
 */
public static Integer prepareSessionForTransaction(Session ses, TransactionDefinition definition)
        throws XccException {

    Assert.notNull(ses, "No Session specified");

    if (definition != null && definition.isReadOnly()) {
        if (logger.isDebugEnabled()) {
            logger.debug("Setting XDBC Session [" + ses + "] read-only");
        }
        ses.setTransactionMode(Session.TransactionMode.QUERY);
    } else {
        ses.setTransactionMode(Session.TransactionMode.UPDATE);
    }

    // Apply specific isolation level, if any.
    Integer previousIsolationLevel = null;
    if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        if (logger.isDebugEnabled()) {
            logger.debug("Changing isolation level of XDBC Session [" + ses + "] to "
                    + definition.getIsolationLevel());
        }
        int currentIsolation = ses.getTransactionMode().ordinal();
        if (currentIsolation != definition.getIsolationLevel()) {
            previousIsolationLevel = currentIsolation;
            ses.setTransactionMode(Session.TransactionMode.values()[definition.getIsolationLevel()]);
        }
    }

    return previousIsolationLevel;
}

From source file:org.cfr.capsicum.datasource.DataSourceUtils.java

/**
 * Prepare the given Connection with the given transaction semantics.
 * @param con the Connection to prepare/* w w  w.  ja  va 2  s .c  om*/
 * @param definition the transaction definition to apply
 * @return the previous isolation level, if any
 * @throws SQLException if thrown by JDBC methods
 * @see #resetConnectionAfterTransaction
 */
public static Integer prepareConnectionForTransaction(Connection con, TransactionDefinition definition)
        throws SQLException {

    Assert.notNull(con, "No Connection specified");

    // Set read-only flag.
    if (definition != null && definition.isReadOnly()) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Setting JDBC Connection [" + con + "] read-only");
            }
            con.setReadOnly(true);
        } catch (Throwable ex) {
            // SQLException or UnsupportedOperationException
            // -> ignore, it's just a hint anyway.
            logger.debug("Could not set JDBC Connection read-only", ex);
        }
    }

    // Apply specific isolation level, if any.
    Integer previousIsolationLevel = null;
    if (definition != null && definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        if (logger.isDebugEnabled()) {
            logger.debug("Changing isolation level of JDBC Connection [" + con + "] to "
                    + definition.getIsolationLevel());
        }
        previousIsolationLevel = new Integer(con.getTransactionIsolation());
        con.setTransactionIsolation(definition.getIsolationLevel());
    }

    return previousIsolationLevel;
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManager.java

@Override
protected void doBegin(Object transaction, TransactionDefinition transactionDefinition)
        throws TransactionException {
    if (transactionDefinition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        throw new InvalidIsolationLevelException("NeoDatis does not support an isolation level concept.");
    }//from www.  j  a va2s .  c o m

    ODB odb = null;

    try {
        NeoDatisTransactionObject transactionObject = (NeoDatisTransactionObject) transaction;
        if (transactionObject.getODBHolder() == null) {
            odb = getOdb();
            logger.debug("Using given ODB [{}] for the current thread transaction.", odb);
            transactionObject.setODBHolder(new ODBHolder(odb));
        }

        ODBHolder odbHolder = transactionObject.getODBHolder();

        odbHolder.setSynchronizedWithTransaction(true);

        // start transaction
        // no-op
        // register timeout
        if (transactionDefinition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
            transactionObject.getODBHolder().setTimeoutInSeconds(transactionDefinition.getTimeout());
        }

        //Bind session holder to the thread
        TransactionSynchronizationManager.bindResource(getOdb(), odbHolder);

    } catch (Exception e) {
        throw new CannotCreateTransactionException("Can not create an NeoDatis transaction.", e);
    }

}

From source file:org.springextensions.db4o.Db4oTransactionManager.java

protected void doBegin(Object transaction, TransactionDefinition transactionDefinition)
        throws TransactionException {
    if (transactionDefinition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
        throw new InvalidIsolationLevelException("Db4o does not support an isolation level concept");
    }//  w  w w.j a  va  2s .c  om

    ObjectContainer container = null;

    try {
        Db4oTransactionObject txObject = (Db4oTransactionObject) transaction;
        if (txObject.getObjectContainerHolder() == null) {
            // use the given container
            container = getObjectContainer();
            logger.debug("Using given objectContainer [{}] for the current thread transaction", container);
            txObject.setObjectContainerHolder(new ObjectContainerHolder(container));
        }

        ObjectContainerHolder containerHolder = txObject.getObjectContainerHolder();

        containerHolder.setSynchronizedWithTransaction(true);

        /*
        * We have no notion of flushing inside a db4o object container
        *
        if (transactionDefinition.isReadOnly() && txObject.isNewObjectContainerHolder()) {
        containerHolder.setReadOnly(true);
        }
                
        if (!transactionDefinition.isReadOnly() && !txObject.isNewObjectContainerHolder()) {
        if (containerHolder.isReadOnly()) {
        containerHolder.setReadOnly(false);
        }
        }
        */

        // start the transaction
        // no-op
        // Register transaction timeout.
        if (transactionDefinition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getObjectContainerHolder().setTimeoutInSeconds(transactionDefinition.getTimeout());
        }

        // Bind the session holder to the thread.
        TransactionSynchronizationManager.bindResource(getObjectContainer(), containerHolder);
    } catch (Exception ex) {
        throw new CannotCreateTransactionException("Could not start db4o object container transaction", ex);
    }
}

From source file:pl.com.bottega.testutils.HibernateExtendedJpaDialect.java

/**
 * This method is overridden to set custom isolation levels on the connection
 * @param entityManager/* w  ww.  j  a  v a 2s .c  o m*/
 * @param definition
 * @return
 * @throws PersistenceException
 * @throws SQLException
 * @throws TransactionException
 */
@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {
    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }

    entityManager.getTransaction().begin();
    logger.debug("Transaction started");

    session.doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            logger.debug("The connection instance is {}", connection);
            logger.debug(
                    "The isolation level of the connection is {} and the isolation level set on the transaction is {}",
                    connection.getTransactionIsolation(), definition.getIsolationLevel());
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
        }
    });

    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManager.java

@Override
protected DefaultTransactionStatus newTransactionStatus(TransactionDefinition definition, Object transaction,
        boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources) {
    // Validate isolation level and time-out settings 
    validateIsolationLevel(definition.getIsolationLevel());

    boolean actualNewSynchronization = newSynchronization
            && !TransactionSynchronizationManager.isSynchronizationActive();

    GlobalTransaction gtx = (GlobalTransaction) transaction;
    Set<GlobalTransactionState> gtxStateSet = getGlobalTransactionStates(gtx);

    GlobalTransaction newGtx;/*from w w w . ja  v  a 2 s.c om*/

    switch (definition.getPropagationBehavior()) {
    case TransactionAttribute.PROPAGATION_NESTED:
        if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            if (!isNestedTransactionAllowed()) {
                throw new TransactionSystemException(String.format(
                        "Unexpected system state: the value of nestedTransactionAllowed boolean "
                                + "member field is false. It should have been checked early as true within "
                                + "handleExistingTransaction method, in order to provide the nested "
                                + "propagation behavior over the transaction (what has already begun "
                                + "GlobalTransaction instance (ID:%1$s)) by nested begin and commit/rollback calls.",
                        (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
                                : "null")));
            }
            if (logger.isInfoEnabled()) {
                logger.info(String.format(
                        "Going to provide nested propagation behavior by nested begin and "
                                + "commit/rollback calls on new GlobalTransaction instance over the "
                                + "transaction what has already begun GlobalTransaction instance (ID:%1$s).",
                        gtx.getId()));
            }
        }
        // Enter to below logic (for TransactionAttribute.PROPAGATION_REQUIRES_NEW case)
    case TransactionAttribute.PROPAGATION_REQUIRES_NEW:
        // Sanity check on system state
        if (!newTransaction) {
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: the value of newTransaction boolean member field "
                            + "is false for %1$s propagation behavior (%2$d). Exptected it to be true.",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior()));
        }

        // Sanity check on current GlobalTransaction instances
        if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            validateCurrentActiveGlobalTransactionToParticipate(gtx, definition);
        }

        // begin new GlobalTransaction
        newGtx = beginGlogalTransaction(gtx, gtxStateSet, definition);

        return new DefaultTransactionStatus(newGtx, newTransaction, actualNewSynchronization,
                definition.isReadOnly(), debug, suspendedResources);
    case TransactionAttribute.PROPAGATION_REQUIRED:
        if (newTransaction) {
            // Sanity check on current GlobalTransaction instances
            if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
                throw new IllegalTransactionStateException(String.format(
                        "Unexpected system state: the value of newTransaction boolean member "
                                + "field is true what direct to create new transaction for %1$s "
                                + "propagation behavior (%2$d) though this transaction has already begun "
                                + "the GlobalTransaction instance (ID:%3$s). Exptected it to be false and "
                                + "participate to the existing transaction.",
                        getPropagationBehaviorStr(definition.getPropagationBehavior()),
                        definition.getPropagationBehavior(), gtx.getId()));
            }

            // begin new GlobalTransaction
            newGtx = beginGlogalTransaction(gtx, gtxStateSet, definition);

            return new DefaultTransactionStatus(newGtx, newTransaction, actualNewSynchronization,
                    definition.isReadOnly(), debug, suspendedResources);
        } else {
            // Sanity check on current GlobalTransaction instances
            validateCurrentActiveGlobalTransactionToParticipate(gtx, definition);

            return new DefaultTransactionStatus(gtx, newTransaction, actualNewSynchronization,
                    definition.isReadOnly(), debug, suspendedResources);
        }
    case TransactionAttribute.PROPAGATION_NEVER:
        if (newTransaction && !gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            return new DefaultTransactionStatus(null, newTransaction, actualNewSynchronization,
                    definition.isReadOnly(), debug, suspendedResources);
        } else {
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: for %1$s propagation behavior (%2$d), the value of "
                            + "newTransaction boolean member field is expected to be true (actual: %3$b) "
                            + "and transaction Object argument is expected to hold current active "
                            + "GlobalTransaction instance (actual: %4$s %5$s one (ID:%6$s)).",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(), newTransaction,
                    (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                            : "not-current"),
                    (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                            : "inactive"),
                    (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
                            : "null")));
        }
    case TransactionAttribute.PROPAGATION_NOT_SUPPORTED:
        if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: for %1$s propagation behavior (%2$d), the "
                            + "transaction Object argument is expected to hold null value (actual: "
                            + "%3$s %4$s GlobalTransaction instance (ID:%5$s)).",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(),
                    (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                            : "not-current"),
                    (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                            : "inactive"),
                    gtx.getId()));
        }

        // Create DeafultTransactionState with null transaction
        return new DefaultTransactionStatus(null, newTransaction, actualNewSynchronization,
                definition.isReadOnly(), debug, suspendedResources);
    case TransactionAttribute.PROPAGATION_SUPPORTS:
        if (newTransaction) {
            if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
                throw new IllegalTransactionStateException(String.format(
                        "Unexpected system state: for %1$s propagation behavior (%2$d), when the "
                                + "newTransaction is true, the transaction Object argument is expected to "
                                + "hold null value (actual: %3$s %4$s GlobalTransaction instance (ID:%5$s)).",
                        getPropagationBehaviorStr(definition.getPropagationBehavior()),
                        definition.getPropagationBehavior(),
                        (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                                : "not-current"),
                        (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                                : "inactive"),
                        gtx.getId()));
            }
            return new DefaultTransactionStatus(null, newTransaction, actualNewSynchronization,
                    definition.isReadOnly(), debug, suspendedResources);
        } else {
            if (!gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction)
                    || !gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction)) {
                throw new IllegalTransactionStateException(String.format(
                        "Unexpected system state: for %1$s propagation behavior (%2$d), when the "
                                + "newTransaction is false, the transaction Object argument is expected to "
                                + "hold current active GlobalTransaction instance (actual: %3$s %4$s "
                                + "GlobalTransaction instance (ID:%5$s)).",
                        getPropagationBehaviorStr(definition.getPropagationBehavior()),
                        definition.getPropagationBehavior(),
                        (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                                : "not-current"),
                        (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                                : "inactive"),
                        (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
                                : "null")));
            }
            return new DefaultTransactionStatus(gtx, newTransaction, actualNewSynchronization,
                    definition.isReadOnly(), debug, suspendedResources);
        }

    case TransactionAttribute.PROPAGATION_MANDATORY:
        if (newTransaction || !gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction)
                || !gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction)) {
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: for %1$s propagation behavior (%2$d), the "
                            + "newTransaction is expected to be false (actual: %3$b) and the transaction "
                            + "Object argument is expected to hold current active GlobalTransaction "
                            + "instance (actual: %3$s %4$s GlobalTransaction instance (ID:%5$s)).",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(),
                    (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                            : "not-current"),
                    (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                            : "inactive"),
                    (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
                            : "null")));
        }

        return new DefaultTransactionStatus(gtx, newTransaction, actualNewSynchronization,
                definition.isReadOnly(), debug, suspendedResources);

    default:
        throw new IllegalTransactionStateException(String.format(
                "Unknown propagation behavior (%1$d) is specified. Supported propagation "
                        + "behaviors is either PROPAGATION_MANDATORY (%2$d), PROPAGATION_NESTED (%3$d), "
                        + "PROPAGATION_NEVER (%4$d), PROPAGATION_NOT_SUPPORTED (%5$d), "
                        + "PROPAGATION_REQUIRED (%6$d), PROPAGATION_REQUIRES_NEW (%7$d), "
                        + "or PROPAGATION_SUPPORTS (%8$d).",
                definition.getPropagationBehavior(), TransactionAttribute.PROPAGATION_MANDATORY,
                TransactionAttribute.PROPAGATION_NESTED, TransactionAttribute.PROPAGATION_NEVER,
                TransactionAttribute.PROPAGATION_NOT_SUPPORTED, TransactionAttribute.PROPAGATION_REQUIRED,
                TransactionAttribute.PROPAGATION_REQUIRES_NEW, TransactionAttribute.PROPAGATION_SUPPORTS));

    } // switch
}

From source file:org.guzz.web.context.spring.GuzzTransactionManager.java

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    GuzzTransactionObject txObject = (GuzzTransactionObject) transaction;

    //TODO: checkout the outside DataSourceTransactionManager 
    //      if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
    //         throw new IllegalTransactionStateException(
    //               "Pre-bound JDBC Connection found! GuzzTransactionManager does not support " +
    //               "running within DataSourceTransactionManager if told to manage the DataSource itself. ") ;
    //      }// www.  j av a 2  s . co  m

    WriteTranSession writeTranSession = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            writeTranSession = getTransactionManager().openRWTran(false);

            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + TransactionManagerUtils.toString(writeTranSession)
                        + "] for Guzz transaction");
            }
            txObject.setWriteTranSession(writeTranSession);
        }

        writeTranSession = txObject.getSessionHolder().getWriteTranSession();

        if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
            // We should set a specific isolation level but are not allowed to...
            IsolationsSavePointer oldSavePointer = writeTranSession
                    .setTransactionIsolation(definition.getIsolationLevel());

            txObject.setIsolationsSavePointer(oldSavePointer);
        }

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getSessionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewWriteTranSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getTransactionManager(),
                    txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);

    } catch (Exception ex) {
        if (txObject.isNewWriteTranSession()) {
            try {
                if (writeTranSession != null) {
                    //TransactionIsolation?????
                    writeTranSession.rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback WriteTranSession after failed transaction begin", ex);
            } finally {
                TransactionManagerUtils.closeSession(writeTranSession);
            }
        }
        throw new CannotCreateTransactionException("Could not open Guzz WriteTranSession for transaction", ex);
    }
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

protected void verifyGetExistingTransactionProcess(int isolationLevel, int propagationBehavior, int timeOutSec,
        boolean debugEnabled) {
    // public final TransactionStatus getTransaction(TransactionDefinition definition)

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).doGetTransaction();

    ArgumentCaptor<GlobalTransaction> globalTransactionArgumentCaptor = ArgumentCaptor
            .forClass(GlobalTransaction.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(globalTransactionArgumentCaptor.capture());
    GlobalTransaction gtx = globalTransactionArgumentCaptor.getValue();
    Assert.assertTrue(gtx instanceof GlobalTransaction);

    ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .isExistingTransaction(Mockito.eq(gtx));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(Mockito.eq(gtx));

    // private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled)
    // public final boolean isValidateExistingTransaction()
    // public final int getTransactionSynchronization()
    // protected final DefaultTransactionStatus prepareTransactionStatus( TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources)

    ArgumentCaptor<TransactionDefinition> transactionDefinitionArgumentCaptor = ArgumentCaptor
            .forClass(TransactionDefinition.class);
    final boolean newSynchronization = true;
    // value true is from result of comparison operation of 
    // getTransactionSynchronization() != SYNCHRONIZATION_NEVER
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).newTransactionStatus(
            transactionDefinitionArgumentCaptor.capture(), Mockito.eq(gtx), Mockito.eq(false),
            Mockito.eq(newSynchronization), Mockito.eq(debugEnabled), Mockito.eq(null));
    TransactionDefinition transactionDefinition = transactionDefinitionArgumentCaptor.getValue();
    Assert.assertEquals(isolationLevel, transactionDefinition.getIsolationLevel());
    Assert.assertEquals(propagationBehavior, transactionDefinition.getPropagationBehavior());
    Assert.assertEquals(timeOutSec, transactionDefinition.getTimeout());

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .validateIsolationLevel(Mockito.eq(isolationLevel));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(Mockito.eq(gtx));

    // protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition)
}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

protected void verifyGetNewTransactionProcess(final int isolationLevel, final int propagationBehavior,
        final int timeOutSec, final boolean debugEnabled, final boolean isSynchronizationActive) {
    ArgumentCaptor<TransactionDefinition> transactionDefinitionArgumentCaptor = ArgumentCaptor
            .forClass(TransactionDefinition.class);
    /* Mockito cannot spy on "final" method because it cannot mock "final" method: 
     * @see http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#13      
          inOrder.verify( slim3PlatformTransactionManager, Mockito.times( 1))
          .getTransaction( transactionDefinitionArgumentCaptor.capture());
          Assert.assertNull( transactionDefinitionArgumentCaptor.getValue());
     *//*from  w w w . j  a  v  a  2  s  . c o  m*/

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).doGetTransaction();

    ArgumentCaptor<GlobalTransaction> globalTransactionArgumentCaptor = ArgumentCaptor
            .forClass(GlobalTransaction.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(globalTransactionArgumentCaptor.capture());
    Assert.assertNull(globalTransactionArgumentCaptor.getValue());

    ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .isExistingTransaction(objectArgumentCaptor.capture());
    Assert.assertNull(objectArgumentCaptor.getValue());

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(globalTransactionArgumentCaptor.capture());
    GlobalTransaction gtx = globalTransactionArgumentCaptor.getValue();
    Assert.assertNull(gtx);

    // protected final SuspendedResourcesHolder suspend(Object transaction) throws TransactionException

    /* Mockito cannot spy on "final" method because it cannot mock "final" method: 
     * @see http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#13      
    mockedSlim3TxMangerInOrder.verify( slim3PlatformTransactionManager, Mockito.times( 1))
    .getTransactionSynchronization();
     */

    final boolean newSynchronization = true;
    // value true is from result of comparison operation of 
    // getTransactionSynchronization() != SYNCHRONIZATION_NEVER
    ArgumentCaptor<Object> suspendedResourcesHolderArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).newTransactionStatus(
            transactionDefinitionArgumentCaptor.capture(), Mockito.eq(gtx), Mockito.eq(true),
            Mockito.eq(newSynchronization), Mockito.eq(debugEnabled),
            suspendedResourcesHolderArgumentCaptor.capture());
    TransactionDefinition transactionDefinition = transactionDefinitionArgumentCaptor.getValue();
    Assert.assertEquals(isolationLevel, transactionDefinition.getIsolationLevel());
    Assert.assertEquals(propagationBehavior, transactionDefinition.getPropagationBehavior());
    Assert.assertEquals(timeOutSec, transactionDefinition.getTimeout());
    if (isSynchronizationActive) {
        Assert.assertNotNull(suspendedResourcesHolderArgumentCaptor.getValue());
    } else {
        Assert.assertNull(suspendedResourcesHolderArgumentCaptor.getValue());
    }
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .validateIsolationLevel(Mockito.eq(isolationLevel));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(Mockito.eq(gtx));

    ArgumentCaptor<Set> gtxStateSetArgumentCaptor = ArgumentCaptor.forClass(Set.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).beginGlogalTransaction(
            Mockito.eq(gtx), gtxStateSetArgumentCaptor.capture(), Mockito.eq(transactionDefinition));
    Set<GlobalTransactionState> gtxStateSet = gtxStateSetArgumentCaptor.getValue();
    Assert.assertFalse(gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance));
    Assert.assertFalse(gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction));
    Assert.assertFalse(gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .setSlim3AsnyncTimeout(Mockito.eq(timeOutSec));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getPropagationBehaviorStr(Mockito.eq(propagationBehavior));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .doBegin(Mockito.eq(gtx), Mockito.eq(transactionDefinition));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(Mockito.eq(gtx));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(globalTransactionArgumentCaptor.capture());
    GlobalTransaction currentGtx = globalTransactionArgumentCaptor.getValue();
    Assert.assertTrue(currentGtx instanceof GlobalTransaction);

    // protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition)

}

From source file:com.newmainsoftech.spray.slingong.datastore.Slim3PlatformTransactionManagerTest.java

protected void verifyNotGetNewTransactionProcess(boolean existingTransactionFlag, int isolationLevel,
        int propagationBehavior, int timeOutSec, boolean debugEnabled) {
    // public final TransactionStatus getTransaction(TransactionDefinition definition)

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1)).doGetTransaction();

    ArgumentCaptor<GlobalTransaction> globalTransactionArgumentCaptor = ArgumentCaptor
            .forClass(GlobalTransaction.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(globalTransactionArgumentCaptor.capture());
    GlobalTransaction gtx = globalTransactionArgumentCaptor.getValue();
    if (existingTransactionFlag) {
        Assert.assertTrue(gtx instanceof GlobalTransaction);
    } else {/*from w  w  w . j a v a  2  s  . c o m*/
        Assert.assertNull(gtx);
    }

    ArgumentCaptor<Object> objectArgumentCaptor = ArgumentCaptor.forClass(Object.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .isExistingTransaction(Mockito.eq(gtx));

    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .getGlobalTransactionStates(Mockito.eq(gtx));

    if (existingTransactionFlag) {
        Assert.fail("Wrong usage of this test method; should be used for the case that "
                + "no GlobalTransaction is available");
        /* The below codes are for the time to extend this test method to handle (active) GlobalTransaction is available. 
                 // private TransactionStatus handleExistingTransaction( TransactionDefinition definition, Object transaction, boolean debugEnabled)
                         
                    switch( propagationBehavior) {
                    case TransactionAttribute.PROPAGATION_NEVER:
                       // Do nothing since IllegalTransactionStateException should have been thrown at
                       // AbstractPlatformTransactionManager.handleExistingTransaction method.
                       break;
                    case TransactionAttribute.PROPAGATION_NOT_SUPPORTED:
                    case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
                       // Do nothing since, in this scenario, TransactionSuspensionNotSupportedException
                       // should have been thrown at AbstractPlatformTransactionManager.doSuspend method
                       // by following logic flow:
          // protected final SuspendedResourcesHolder suspend(Object transaction)
             // - TransactionSynchronizationManager.isSynchronizationActive() should always be false
             // due to Slim3PlatformTransactionManager does not support transaction synchronization currently.
             // - transaction argument to suspend method should not be null due to
             // value of existingTransactionFlag argument to this verifyNotGetNewTransactionProcess method.
                               
             // protected Object doSuspend(Object transaction)
                // throws TransactionSuspensionNotSupportedException
                       break;
                    case TransactionDefinition.PROPAGATION_NESTED:
                       // Do nothing since, in this scenario, NestedTransactionNotSupportedException should
                       // have been thrown at AbstractPlatformTransactionManager.handleExistingTransaction
                       // by following logic below
          // public final boolean isNestedTransactionAllowed()
             // Should return false because the use case of this verifyNotGetNewTransactionProcess
             // method is for not getting new transaction.
                       break;
                    default:
                       // public final boolean isValidateExistingTransaction()
          // IllegalTransactionStateException can be thrown depends on value of isolation
                       // public final int getTransactionSynchronization()
                       // protected final DefaultTransactionStatus prepareTransactionStatus( TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources)
          ArgumentCaptor<TransactionDefinition> transactionDefinitionArgumentCaptor 
          = ArgumentCaptor.forClass( TransactionDefinition.class);
          ArgumentCaptor<Boolean> booleanArgumentCaptor 
          = ArgumentCaptor.forClass( Boolean.class);
          mockedSlim3TxMangerInOrder.verify( slim3PlatformTransactionManager, Mockito.times( 1))
          .newTransactionStatus( 
                transactionDefinitionArgumentCaptor.capture(), // TransactionDefinition definition
                Mockito.eq( gtx), // Object transaction
                Mockito.eq( false), Mockito.eq( false), // boolean newTransaction, boolean newSynchronization
                Mockito.eq( debugEnabled), Mockito.eq( null) //boolean debug, Object suspendedResources
                );
             TransactionDefinition transactionDefinition 
             = transactionDefinitionArgumentCaptor.getValue();
             Assert.assertEquals( isolationLevel, transactionDefinition.getIsolationLevel());
             Assert.assertEquals( propagationBehavior, transactionDefinition.getPropagationBehavior());
             Assert.assertEquals( timeOutSec, transactionDefinition.getTimeout());
                     
          // protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition)
                       break;
                    } // switch
        */
    } else {
        switch (propagationBehavior) {
        case TransactionDefinition.PROPAGATION_REQUIRED:
        case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
        case TransactionDefinition.PROPAGATION_NESTED:
            Assert.fail("Wrong usage of this test method; value of propagationBehavior argument should be "
                    + "one among the nexts: PROPAGATION_SUPPORTS, PROPAGATION_NOT_SUPPORTED, "
                    + "and PROPAGATION_NEVER");
            /* The below codes are for the time to extend this test method to handle (active) GlobalTransaction is available. 
                        // protected final SuspendedResourcesHolder suspend(Object transaction)
                           // suspend method should return null due to the following logic flow:
                           // - TransactionSynchronizationManager.isSynchronizationActive() should always be false
                           // due to Slim3PlatformTransactionManager does not support transaction synchronization currently.
                           // - transaction argument to suspend method should be null due to
                           // value of existingTransactionFlag argument to this verifyNotGetNewTransactionProcess method.
                        // public final int getTransactionSynchronization()
                        ArgumentCaptor<TransactionDefinition> transactionDefinitionArgumentCaptor 
                        = ArgumentCaptor.forClass( TransactionDefinition.class);
                        ArgumentCaptor<Boolean> booleanArgumentCaptor = ArgumentCaptor.forClass( Boolean.class);
                        mockedSlim3TxMangerInOrder.verify( slim3PlatformTransactionManager, Mockito.times( 1))
                        .newTransactionStatus( 
                              transactionDefinitionArgumentCaptor.capture(), // TransactionDefinition definition
                              Mockito.eq( null), // Object transaction
                              Mockito.eq( true), Mockito.eq( false), // boolean newTransaction, boolean newSynchronization
                              Mockito.eq( debugEnabled), Mockito.eq( null) //boolean debug, Object suspendedResources
                              );
                           TransactionDefinition transactionDefinition 
                           = transactionDefinitionArgumentCaptor.getValue();
                           Assert.assertEquals( isolationLevel, transactionDefinition.getIsolationLevel());
                           Assert.assertEquals( propagationBehavior, transactionDefinition.getPropagationBehavior());
                           Assert.assertEquals( timeOutSec, transactionDefinition.getTimeout());
                        // protected void doBegin( Object transaction, TransactionDefinition definition)
                        // protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition)
            */
            break;
        default: // Case of creating "empty" transaction: no actual transaction, but potentially synchronization.
            // public final int getTransactionSynchronization()
            // protected final DefaultTransactionStatus prepareTransactionStatus( TransactionDefinition definition, Object transaction, boolean newTransaction, boolean newSynchronization, boolean debug, Object suspendedResources)
            ArgumentCaptor<TransactionDefinition> transactionDefinitionArgumentCaptor = ArgumentCaptor
                    .forClass(TransactionDefinition.class);
            final boolean newSynchronization = true;
            // value true is from result of comparison operation of 
            // getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS
            mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
                    .newTransactionStatus(transactionDefinitionArgumentCaptor.capture(), Mockito.eq(null),
                            Mockito.eq(true), Mockito.eq(newSynchronization), Mockito.eq(debugEnabled),
                            Mockito.eq(null));
            TransactionDefinition transactionDefinition = transactionDefinitionArgumentCaptor.getValue();
            Assert.assertEquals(isolationLevel, transactionDefinition.getIsolationLevel());
            Assert.assertEquals(propagationBehavior, transactionDefinition.getPropagationBehavior());
            Assert.assertEquals(timeOutSec, transactionDefinition.getTimeout());

            mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
                    .validateIsolationLevel(Mockito.eq(isolationLevel));

            mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
                    .getGlobalTransactionStates(null);

            // protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition)
            break;
        } // switch
    }

}