Example usage for org.springframework.transaction TransactionDefinition getPropagationBehavior

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

Introduction

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

Prototype

default int getPropagationBehavior() 

Source Link

Document

Return the propagation behavior.

Usage

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

/**
 * This implementation sets the isolation level but ignores the timeout.
 *//* ww  w . ja  va  2  s .  c  om*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) transaction;
    Connection con = null;

    try {
        if (txObject.getConnectionHolder() == null
                || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            Connection newCon = this.dataSource.getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            ObjectContext context = null;
            if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
                Injector injector = this.cayenneRuntime.getInjector();
                context = injector.getInstance(ObjectContextFactory.class).createContext();
            } else {
                context = BaseContext.getThreadObjectContext();
            }
            txObject.setConnectionHolder(new CayenneConnectionHolder(newCon, context), true);
            BaseContext.bindThreadObjectContext(context);
        }

        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();

        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);

        // Switch to manual commit if necessary. This is very expensive in
        // some
        // JDBC drivers,
        // so we don't want to do it unnecessarily (for example if we've
        // explicitly
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolderEx().setTransactionActive(true);

        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        }
    }

    catch (SQLException ex) {
        DataSourceUtils.releaseConnection(con, this.dataSource);
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    }
}

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

protected boolean validateCurrentActiveGlobalTransactionToParticipate(final GlobalTransaction gtx,
        final TransactionDefinition definition) throws IllegalTransactionStateException {
    Set<GlobalTransactionState> gtxStateSet = getGlobalTransactionStates(gtx);
    if ((!gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction))
            || (!gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction))) {
        throw new IllegalTransactionStateException(String.format(
                "Though %1$s propergation behavior (%2$d) was specified, "
                        + "the GlobalTransaction instance (ID:%3$s) (what has been begun this "
                        + "transaction before) is %4$s %5$s one. Expected it to be current active " + "one.",
                getPropagationBehaviorStr(definition.getPropagationBehavior()),
                definition.getPropagationBehavior(), gtx.getId(),
                (gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction) ? "current"
                        : "not-current"),
                (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction) ? "active"
                        : "inactive")));
    }//from   ww  w  . ja v  a  2  s .  com

    return true;
}

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

protected GlobalTransaction beginGlogalTransaction(GlobalTransaction gtx,
        Set<GlobalTransactionState> gtxStateSet, TransactionDefinition definition)
        throws CannotCreateTransactionException {
    setSlim3AsnyncTimeout(definition.getTimeout());

    GlobalTransaction newGtx;//w w w . jav a  2 s  .co m
    try {
        newGtx = Datastore.beginGlobalTransaction();
    } catch (Throwable throwable) {
        String message;
        if (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            message = String.format(
                    "Failure to begin new Slim3 GlobalTransaction instance under %1$s propagation "
                            + "behavior (%2$d) over the transaction what has already begun GlobalTransaction "
                            + "instance (ID:%3$s)",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(), gtx.getId());
        } else {
            message = String.format(
                    "Failure to begin new Slim3 GlobalTransaction instance under "
                            + "%1$s propergation behavior (%2$d)",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior());
        }
        throw new CannotCreateTransactionException(message, throwable);
    }

    String newGtxIdStr = newGtx.getId();

    synchronized (slim3GtxObjMapThreadLocal) {
        Slim3GlobalTransactionObject gtxObj = new Slim3GlobalTransactionObject(newGtxIdStr);
        slim3GtxObjMapThreadLocal.get().put(newGtxIdStr, gtxObj);
    } // synchronized

    if (logger.isInfoEnabled()) {
        logger.info(String.format(
                "Slim3 GlobalTransaction (ID:%1$s) began successfully under "
                        + "%2$s propergation behavior (%3$d).",
                newGtx.getId(), getPropagationBehaviorStr(definition.getPropagationBehavior()),
                definition.getPropagationBehavior()));
    }

    return newGtx;
}

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;// www  . jav a 2  s  .c  o m

    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: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.  co  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 {/*  w  w  w .j a va2  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
    }

}

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

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException {
    // Validation on transaction argument -----------------------------------------------------
    /* transaction Object should be either 
     *       null//from w ww. j  a  v a  2s . c om
     *          either TransactionDefinition.PROPAGATION_REQUIRED, 
     *          TransactionDefinition.PROPAGATION_REQUIRES_NEW or TransactionDefinition.PROPAGATION_NESTED
     *       active GlobalTransactoin object (one before current one)
     *          either TransactionDefinition.PROPAGATION_REQUIRES_NEW or 
     *          TransactionDefinition.PROPAGATION_NESTED
     *             if TransactionDefinition.PROPAGATION_NESTED case, then 
     *             useSavepointForNestedTransaction method returns false
     */
    GlobalTransaction gtx = (GlobalTransaction) transaction;
    Set<GlobalTransactionState> gtxStateSet = getGlobalTransactionStates(gtx);
    GlobalTransaction currentGtx = Datastore.getCurrentGlobalTransaction();
    Set<GlobalTransactionState> currentGtxStateSet = getGlobalTransactionStates(currentGtx);
    if (!currentGtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction)) {
        throw new IllegalTransactionStateException(String.format(
                "Unexpected system state: getCurrentGlobalTransaction method of Slim3 Datastore "
                        + "returned inactive GlobalTransaction instance (ID:%3$s). Expected it to return "
                        + "active GlobalTransaction instance as new GlobalTransaction instance has begun "
                        + "by newTransactionStatus method.",
                (currentGtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)
                        ? currentGtx.getId()
                        : "null")));
    }
    String gtxIdStr = (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
            : "null");
    if (gtxIdStr.equals(currentGtx.getId())) {
        throw new IllegalTransactionStateException(String.format(
                "Unexpected system state: the transaction Object argument refers to current "
                        + "active GlobalTransaction instance (ID:%1$s). Expected it not to refer to "
                        + "current active GlobalTransaction instance rather refer to the GlobalTransaction "
                        + "instance available before newTransaction method execution or hold null value.",
                gtxIdStr));
    }

    if (!gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
        switch (definition.getPropagationBehavior()) {
        case TransactionDefinition.PROPAGATION_REQUIRED:
        case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
        case TransactionDefinition.PROPAGATION_NESTED:
            break;
        default:
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: found that the %1$s propagation behavior (%2$d) was "
                            + "specified when the transaction Object argument holds null value. Expected "
                            + "propagation behavior to be either PROPAGATION_REQUIRED (%3$d), "
                            + "PROPAGATION_REQUIRES_NEW (%4$d) or PROPAGATION_NESTED (%5$d) when the "
                            + "transaction Object argument holds null value.",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(), TransactionDefinition.PROPAGATION_REQUIRED,
                    TransactionDefinition.PROPAGATION_REQUIRES_NEW, TransactionDefinition.PROPAGATION_NESTED));
        } // switch
    } else if (gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction)) {
        switch (definition.getPropagationBehavior()) {
        case TransactionDefinition.PROPAGATION_REQUIRES_NEW:
        case TransactionDefinition.PROPAGATION_NESTED:
            break;
        default:
            throw new IllegalTransactionStateException(String.format(
                    "Unexpected system state: found that the %1$s propagation behavior (%2$d) was "
                            + "specified when the transaction Object argument holds active "
                            + "GlobalTransaction instance (ID:%3$s). Expected propagation behavior to be "
                            + "either PROPAGATION_REQUIRES_NEW (%4$d) or PROPAGATION_NESTED (%5$d) when "
                            + "the transaction Object argument holds active GlobalTransaction instance.",
                    getPropagationBehaviorStr(definition.getPropagationBehavior()),
                    definition.getPropagationBehavior(), gtx.getId(),
                    TransactionDefinition.PROPAGATION_REQUIRES_NEW, TransactionDefinition.PROPAGATION_NESTED));
        } // switch
    } else {
        throw new IllegalTransactionStateException(
                String.format("Unexpected system state: the transaction Object argument holds inactive "
                        + "GlobalTransaction instance (ID:%1$s). Expected it to hold either null or "
                        + "active GlobalTransaction instance.", gtx.getId()));
    }
    // ----------------------------------------------------------------------------------------
}

From source file:jp.terasoluna.fw.batch.util.BatchUtil.java

/**
 * ??/*from   w w w.  jav a 2s .c  om*/
 * @param tran PlatformTransactionManager
 * @param def TransactionDefinition
 * @param log Log
 * @return TransactionStatus
 */
public static TransactionStatus startTransaction(PlatformTransactionManager tran, TransactionDefinition def,
        Log log) {
    if (log != null && log.isDebugEnabled()) {
        logDebug(log, LogId.DAL025033, tran);
        if (def != null) {
            logDebug(log, LogId.DAL025034, def.getPropagationBehavior(), def.getIsolationLevel(),
                    def.getTimeout(), def.isReadOnly(), def.getName());
        }
    }

    TransactionStatus stat = null;
    if (tran != null) {
        stat = tran.getTransaction(def);
    }

    if (log != null && log.isDebugEnabled()) {
        logDebug(log, LogId.DAL025035, stat);
    }
    return stat;
}

From source file:jp.terasoluna.fw.batch.util.BatchUtil.java

/**
 * ??//from  ww  w .  j av a2s . co m
 * @param tranDef TransactionDefinition
 * @param tranMap PlatformTransactionManager
 * @param log Log
 * @return TransactionStatus
 */
public static Map<String, TransactionStatus> startTransactions(TransactionDefinition tranDef, Map<?, ?> tranMap,
        Log log) {
    Map<String, TransactionStatus> statMap = new LinkedHashMap<String, TransactionStatus>();

    if (!tranMap.isEmpty()) {
        for (Map.Entry<?, ?> ent : tranMap.entrySet()) {
            String key = null;
            PlatformTransactionManager ptm = null;

            // ??
            if (ent.getKey() instanceof String) {
                key = (String) ent.getKey();
            }
            // ???
            if (ent.getValue() instanceof PlatformTransactionManager) {
                ptm = (PlatformTransactionManager) ent.getValue();
            }

            if (ptm != null) {

                if (log != null && log.isDebugEnabled()) {
                    logDebug(log, LogId.DAL025033, key);
                    if (tranDef != null) {
                        logDebug(log, LogId.DAL025034, tranDef.getPropagationBehavior(),
                                tranDef.getIsolationLevel(), tranDef.getTimeout(), tranDef.isReadOnly(),
                                tranDef.getName());
                    }
                }

                // 
                TransactionStatus trnStat = null;
                try {
                    trnStat = ptm.getTransaction(tranDef);
                } catch (TransactionException e) {
                    if (log != null && log.isErrorEnabled()) {
                        logError(log, LogId.EAL025048, e, key);
                    }
                    endTransactions(tranMap, statMap, log);
                    throw e;
                }

                // ?
                if (statMap != null) {
                    statMap.put(key, trnStat);
                }

                if (log != null && log.isDebugEnabled()) {
                    logDebug(log, LogId.DAL025035, key, trnStat);
                }
            }
        }
    }

    return statMap;
}