Example usage for org.springframework.transaction.support DefaultTransactionStatus getTransaction

List of usage examples for org.springframework.transaction.support DefaultTransactionStatus getTransaction

Introduction

In this page you can find the example usage for org.springframework.transaction.support DefaultTransactionStatus getTransaction.

Prototype

public Object getTransaction() 

Source Link

Document

Return the underlying transaction object.

Usage

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test
public void testTransactionCommit() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI commitUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.COMMIT);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*w w  w  . j  ava  2s.  c o  m*/
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(commitUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform()).thenReturn(new FcrepoResponse(commitUri, 201, emptyMap(), null));

    DefaultTransactionStatus status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);
    FcrepoTransactionObject txObj = (FcrepoTransactionObject) status.getTransaction();

    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

    status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);

    txMgr.commit(status);

    txObj = (FcrepoTransactionObject) status.getTransaction();

    assertNull(txObj.getSessionId());
    assertTrue(status.isCompleted());
}

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test
public void testTransactionRollback() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI commitUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.COMMIT);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*w ww. j  a v  a  2  s.  c om*/
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(commitUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform()).thenReturn(new FcrepoResponse(commitUri, 201, emptyMap(), null));

    DefaultTransactionStatus status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);
    FcrepoTransactionObject txObj = (FcrepoTransactionObject) status.getTransaction();

    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

    status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);

    txMgr.rollback(status);

    txObj = (FcrepoTransactionObject) status.getTransaction();

    assertNull(txObj.getSessionId());
    assertTrue(status.isCompleted());
}

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test(expected = TransactionSystemException.class)
public void testTransactionCommitError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI commitUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.COMMIT);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);//  w ww  .j  a  v a  2s .c  om
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(commitUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform())
            .thenThrow(new FcrepoOperationFailedException(commitUri, 400, "Bad Request"));

    DefaultTransactionStatus status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);

    final FcrepoTransactionObject txObj = (FcrepoTransactionObject) status.getTransaction();
    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

    status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);
    txMgr.commit(status);
}

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test(expected = TransactionSystemException.class)
public void testTransactionRollbackError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI rollbackUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.ROLLBACK);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);//from  ww w  . ja va2  s  .  co m
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(rollbackUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform())
            .thenThrow(new FcrepoOperationFailedException(rollbackUri, 400, "Bad Request"));

    DefaultTransactionStatus status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);

    final FcrepoTransactionObject txObj = (FcrepoTransactionObject) status.getTransaction();
    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

    status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);
    txMgr.rollback(status);
}

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

@Override
protected void doSetRollbackOnly(DefaultTransactionStatus status) {
    GuzzTransactionObject txObject = (GuzzTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Setting Guzz transaction on WriteTranSession ["
                + TransactionManagerUtils.toString(txObject.getSessionHolder().getWriteTranSession())
                + "] rollback-only");
    }//from w w w.  jav a 2  s.  c  om
    txObject.setRollbackOnly();
}

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

@Override
protected void doRollback(DefaultTransactionStatus status) {
    GuzzTransactionObject txObject = (GuzzTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Rolling back Guzz transaction on WriteTranSession ["
                + TransactionManagerUtils.toString(txObject.getSessionHolder().getWriteTranSession()) + "]");
    }//w  w w.ja va 2s  . c o  m

    try {
        txObject.getSessionHolder().getWriteTranSession().rollback();
    } catch (Throwable ex) {
        throw new TransactionSystemException("Could not roll back Hibernate transaction", ex);
    }
}

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

@Override
protected void doCommit(DefaultTransactionStatus status) {
    GuzzTransactionObject txObject = (GuzzTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Committing Guzz transaction on WriteTranSession ["
                + TransactionManagerUtils.toString(txObject.getSessionHolder().getWriteTranSession()) + "]");
    }//from   w w w  . j  av a  2s . co m
    try {
        txObject.getSessionHolder().getWriteTranSession().commit();
    } catch (DaoException ex) {
        throw convertGuzzAccessException(ex);
    } catch (Throwable ex) {
        throw new TransactionSystemException("Could not commit Hibernate transaction", ex);
    }
}

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

@Override
protected void doCommit(DefaultTransactionStatus defaultTransactionStatus) throws TransactionException {
    GlobalTransaction gtx = (GlobalTransaction) defaultTransactionStatus.getTransaction();
    Set<GlobalTransactionState> gtxStateSet = getGlobalTransactionStates(gtx);

    // Sanity check on precondition -----------------------------------------------------------
    /*/*from   w w  w . ja  v a 2s . c  om*/
     * This will be called at outermost transaction boundary (defaultTransactionStatus.isNewTransaction() 
     * will return true). 
     * When defaultTransactionStatus has been set for roll back, roll back doesn't need to be handled 
     * within doCommit method. 
     *    When either defaultTransactionStatus's isGlobalRollbackOnly and shouldCommitOnGlobalRollbackOnly 
     *    returns true or its isLocalRollbackOnly returns true, then logic flow won't reach here and 
     *    roll back should have been performed by doRollback.
     */
    if (defaultTransactionStatus.isRollbackOnly()) {
        throw new TransactionSystemException(String.format(
                "Unexpected system state: the transaction for the GlobalTransaction "
                        + "instance (ID:%1$s) has been marked as roll-back only "
                        + "(LocalRollbackOnly:%2$b, GlobalRollbackOnly:%3$b).",
                (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId() : "null"),
                defaultTransactionStatus.isLocalRollbackOnly(),
                defaultTransactionStatus.isGlobalRollbackOnly()));
    }
    if (!defaultTransactionStatus.isNewTransaction()) {
        throw new TransactionSystemException(String.format(
                "Unexpected system state: attempted to commit from participation of an existing "
                        + "transaction (of which GlobalTransacion Id is %1$s).",
                (gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance) ? gtx.getId()
                        : "null")));
    }
    // ----------------------------------------------------------------------------------------

    // Sanity check on gtx GlobalTransaction instance -----------------------------------------
    if (!gtxStateSet.contains(GlobalTransactionState.ActiveGlobalTransaction)) {
        String message;

        if (!gtxStateSet.contains(GlobalTransactionState.GlobalTransactionInstance)) {
            message = "Unexpected system state: The GlobalTransaction object passed as the transaction "
                    + "Object argument is null.";
        } else {
            message = String
                    .format("Unexpected system state: The GlobalTransaction instance (ID:%1$s) passed as the "
                            + "transaction Object argument is inactive.", gtx.getId());
        }

        throw new IllegalTransactionStateException(message);
    }
    if (!gtxStateSet.contains(GlobalTransactionState.CurrentGlobalTransaction)) {
        /* The one possible case of the control flow reaching here is that GlobalTransaction object 
         * is manually instantiated at the outside of Spring transaction framework, and it is left active.
         * 
         * In nesting global transaction, easy to yield ConcurrentModificationException without care.
         * Nesting global transaction should be less necessary, since Slim3 isolate between (Global) 
         * transactions and cannot change that isolation setting, and this uses Slim3 GlobalTransaction, 
         * as GAE/J datastore API is not provide suspend feature as well.
         */

        GlobalTransaction currentGtx = Datastore.getCurrentGlobalTransaction();
        if (logger.isWarnEnabled()) {
            logger.warn(String.format(
                    "Though active GlobalTransaction instance (ID:%1$s) is passed as transaction "
                            + "Object argument, it's not current GlobalTransaction instance (ID:%2$s).",
                    gtx.getId(), ((currentGtx instanceof GlobalTransaction) ? currentGtx.getId() : "null")));
        }
    }
    // ----------------------------------------------------------------------------------------
    boolean exceptionUp = false;
    try {
        gtx.commit();
        slim3GtxObjMapThreadLocal.get().remove(gtx.getId());
        if (logger.isInfoEnabled()) {
            logger.info(String.format("Slim3 GlobalTransaction (ID:%1$s) committed.", gtx.getId()));
        }
    } catch (Throwable throwable) {
        /* Set rollback only flag so calling processRollback method to roll back will occur at 
         * commit method by AnnotationTransactionAspect, even for other exceptions than ones specified 
         * for rollbackFor or rollbackForClassname attributes of @Transactional annotation.
         */
        defaultTransactionStatus.setRollbackOnly();

        exceptionUp = true;

        String message = String.format("Slim3 GlobalTransaction (ID:%1$s) failed on commit.", gtx.getId());
        if ((throwable instanceof ConcurrentModificationException)
                || (throwable instanceof DeadlineExceededException)) {
            /* Slim3 should have already rolled back automatically on either
             * ConcurrentModificationException or DeadlineExceededException.
             * 
             * About DeadlineExceededException case: It seems like no harm
             * will be made even active global transaction at
             * DeadlineExceededException case left behind. As looking
             * briefly through the Slim3 source codes, the locks by that
             * global transaction seems to be released while it rolls back
             * by DatastoreFilter, and itself seem to be removed from
             * TheadLocal stack of the global transactions. So, it won't be
             * returned by such Datastore.getCurrentGlobalTransaction()
             * method. See at
             * http://groups.google.com/group/slim3-user/browse_frm
             * /thread/e3d47d8f28c8e8d3
             * /9e43553f3b56d1f2?tvc=1#9e43553f3b56d1f2 If it turns out
             * opposite, then that active global transaction can be cleared
             * some how at here for DeadlineExceededException case.
             */

            message = String.format("Slim3 GlobalTransaction (ID:%1$s) failed on commit. %n"
                    + "Slim3 must have already rolled back automatically behind "
                    + "Spring transaction framework.", gtx.getId());
        }

        throw new TransactionSystemException(message, throwable);
    } finally {
        if (gtx.isActive()) {
            if (exceptionUp) {
                if (logger.isInfoEnabled()) {
                    logger.info(String.format(
                            "GlobalTransaction instance (ID:%1$s) remains active after exception "
                                    + "durring commit attempt. That GlobalTransaction instance has not "
                                    + "been removed yet from slim3GtxObjMapThreadLocal member field.",
                            gtx.getId(), this.getClass().getName()));
                }
            } else {
                if (logger.isWarnEnabled()) {
                    logger.warn(String.format(
                            "Unexpected system state: GlobalTransaction instance (ID:%1$s) "
                                    + "remains active even after commit attempt. That GlobalTransaction "
                                    + "instance was removed from slim3GtxObjMapThreadLocal member field.",
                            gtx.getId(), this.getClass().getName()));
                }
            }
        }
    }
}

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

protected void verifyRollbackProcess(boolean readOnlyEnabled, boolean roolBackOnlyEnabled,
        boolean debugEnabled) {
    // public final void rollback(TransactionStatus status)
    // private void processRollback(DefaultTransactionStatus status)
    // protected final void triggerBeforeCompletion(DefaultTransactionStatus status)

    ArgumentCaptor<DefaultTransactionStatus> defaultTransactionStatusArgumentCaptor = ArgumentCaptor
            .forClass(DefaultTransactionStatus.class);
    mockedSlim3TxMangerInOrder.verify(slim3PlatformTransactionManager, Mockito.times(1))
            .doRollback(defaultTransactionStatusArgumentCaptor.capture());
    DefaultTransactionStatus defaultTransactionStatus = defaultTransactionStatusArgumentCaptor.getValue();
    Assert.assertTrue(defaultTransactionStatus.getTransaction() instanceof GlobalTransaction);
    GlobalTransaction gtx = (GlobalTransaction) defaultTransactionStatus.getTransaction();
    Assert.assertTrue(defaultTransactionStatus.isNewTransaction());
    Assert.assertTrue(defaultTransactionStatus.isCompleted()); // Should be true since actually transaction has already been finished
    Assert.assertEquals(readOnlyEnabled, defaultTransactionStatus.isReadOnly());
    Assert.assertEquals(roolBackOnlyEnabled, defaultTransactionStatus.isRollbackOnly());
    /* If defaultTransactionStatus.isRollbackOnly() returns true, then either 
     * its isGlobalRollbackOnly() or its isLocalRollbackOnly() returns true.
     *//*from   ww w.j  ava  2 s.co m*/
    if (defaultTransactionStatus.isRollbackOnly() && logger.isDebugEnabled()) {
        logger.debug("defaultTransactionStatus.isGlobalRollbackOnly() = "
                + defaultTransactionStatus.isGlobalRollbackOnly());
        logger.debug("defaultTransactionStatus.isLocalRollbackOnly() = "
                + defaultTransactionStatus.isLocalRollbackOnly());
    }
    Assert.assertEquals(debugEnabled, defaultTransactionStatus.isDebug());
    Assert.assertFalse(defaultTransactionStatus.isTransactionSavepointManager());
    Assert.assertTrue(defaultTransactionStatus.isNewSynchronization());

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

    // private void triggerAfterCompletion(DefaultTransactionStatus status, int completionStatus)
    // private void cleanupAfterCompletion(DefaultTransactionStatus status)
    // protected void doCleanupAfterCompletion(Object transaction)

}