Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED

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

Introduction

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

Prototype

int PROPAGATION_REQUIRED

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRED.

Click Source Link

Document

Support a current transaction; create a new one if none exists.

Usage

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Tests the use of nested transactions.
 *//*w w w  .  ja  v a2  s  . c o  m*/
@Test
public void testNestedTransactions() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    final TransactionTemplate tt = hbc.getTransactionTemplate();

    Serializable empId = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp.setFirstName("Committed");
                    return emp.getId();
                }
            });
            // asserts that UOW is still active after the end of the nested transaction.
            assertTrue("UOW should still be active since outer TX is ongoing.", hbc.isUnitOfWorkActive());
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria empById = DetachedCriteria.forClass(Employee.class);
    empById.add(Restrictions.eq(IEntity.ID, empId));
    Employee emp = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertTrue("Inner transaction should have been committed", "Committed".equals(emp.getFirstName()));

    Serializable emp2Id = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp2 = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp2.setFirstName("Rollbacked");
                    return emp2.getId();
                }
            });
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria emp2ById = DetachedCriteria.forClass(Employee.class);
    emp2ById.add(Restrictions.eq(IEntity.ID, emp2Id));
    Employee emp2 = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertFalse("Inner transaction should have been rollbacked", "Rollbacked".equals(emp2.getFirstName()));

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            City newCity = hbc.getEntityFactory().createEntityInstance(City.class);
            newCity.setName("Test City");

            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            String testZip = nestedTT.execute(new TransactionCallback<String>() {

                @Override
                public String doInTransaction(TransactionStatus nestedStatus) {
                    return "12345";
                }
            });
            newCity.setZip(testZip);
            hbc.registerForUpdate(newCity);
        }
    });

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            final City randomCity = hbc.findFirstByCriteria(DetachedCriteria.forClass(City.class),
                    EMergeMode.MERGE_KEEP, City.class);
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            nestedTT.execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus nestedStatus) {
                    DetachedCriteria cityById = DetachedCriteria.forClass(City.class);
                    cityById.add(Restrictions.eq(IEntity.ID, randomCity.getId()));
                    City innerRandomCity = (City) cityById.getExecutableCriteria(hbc.getHibernateSession())
                            .uniqueResult();
                    // If we reach this point without exception, there is no mix between the inner TX and the outer UOW.
                    // See bug #1118
                }
            });
        }
    });
}

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);//from   ww  w.ja v  a2s  .  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(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:ru.apertum.qsystem.common.model.QCustomer.java

private void saveToSelfDB() {
    // ? ?  //w ww .  j a v a  2s. c om
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("SomeTxName");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
    try {
        if (input_data == null) { //     ? ?       ,   ?   
            input_data = "";
        }
        Spring.getInstance().getHt().saveOrUpdate(this);
    } catch (Exception ex) {
        Spring.getInstance().getTxManager().rollback(status);
        throw new ServerException("  ? \n" + ex.toString() + "\n"
                + Arrays.toString(ex.getStackTrace()));
    }
    Spring.getInstance().getTxManager().commit(status);
    QLog.l().logger().debug(".");
}

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);/*  w w w.j  a v  a 2  s  .  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(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:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

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

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

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

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

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

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

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

From source file: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//  w w w.j a  va 2  s .  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: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 ww  .  j  a va 2  s  .co 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.krawler.esp.handlers.zohoRequestHandler.java

public String saveUpdateZohoContact(String username, String password, String authToken, String userid,
        String companyid, String ipAddress, String tzdiff) {

    //        Session s = zohoRequestDAO.getCurrentSession();
    String result = "{success:false,recCount:0,totalRecords:0}";
    int recCount = 0;
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {//from   w  w  w  . jav  a  2 s .  co  m
        String Hql = "from CrmContact c where  c.contactid= ?";
        JSONObject jobj = getRecordJson("Contacts", username, password, authToken); //Potential , Leads, Accounts
        if (jobj.get("success").equals(true)) {
            JSONArray dataArray = jobj.getJSONArray("data");
            for (int cnt = 0; cnt < dataArray.length(); cnt++) {
                //                    Transaction tx = (Transaction) s.beginTransaction();
                JSONObject recObj = dataArray.getJSONObject(cnt);
                List existingContact = zohoRequestDAO.executeQuery(Hql,
                        new Object[] { recObj.get("CONTACTID") });

                JSONObject conJObj = new JSONObject();
                String conid = recObj.get("CONTACTID").toString();
                conJObj.put("contactid", conid);
                conJObj.put("companyid", companyid);
                conJObj.put("userid", userid);
                conJObj.put("contactownerid", userid);
                conJObj.put("updatedon", new Date());
                conJObj.put("description", "");
                conJObj.put("phone", recObj.getString("Phone").equals("null") ? "" : recObj.getString("Phone"));
                conJObj.put("isarchive", false);
                conJObj.put("deleteflag", 0);
                CrmAccount ca = null;
                try {
                    ca = (CrmAccount) zohoRequestDAO.get(CrmAccount.class, recObj.get("ACCOUNTID").toString());
                } catch (Exception e) {
                    logger.warn(e.getMessage(), e);
                }
                if (ca != null) {
                    conJObj.put("accountid", recObj.get("ACCOUNTID"));
                }
                conJObj.put("email", recObj.getString("Email").equals("null") ? "" : recObj.getString("Email"));
                conJObj.put("firstname",
                        recObj.getString("First Name").equals("null") ? "" : recObj.getString("First Name"));
                conJObj.put("lastname",
                        recObj.getString("Last Name").equals("null") ? "" : recObj.getString("Last Name"));
                conJObj.put("validflag", 1);

                if (existingContact.size() == 0) {
                    conJObj.put("contactid", "0");
                }
                contactManagementService.saveContact(companyid, userid, tzdiff, ipAddress, conJObj);
                //                    tx.commit();
                recCount++;
            }
            txnManager.commit(status);
            result = "{success:true,recCount:" + recCount + ",totalRecords:" + jobj.get("recordCount") + "}";
        }
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    } finally {
        //            s.close();
        return result;
    }
}

From source file:com.krawler.esp.handlers.zohoRequestHandler.java

public String saveUpdateZohoLeads(String username, String password, String authToken, String userid,
        String companyid) {/*from www .  ja v  a 2 s  .c om*/

    //        Session s = zohoRequestDAO.getCurrentSession();
    String result = "{success:false,recCount:0,totalRecords:0}";
    int recCount = 0;
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {

        String Hql = "from CrmLead c where  c.leadid= ?";
        JSONObject jobj = getRecordJson("Leads", username, password, authToken); //Potential , Leads, Accounts
        if (jobj.get("success").equals(true)) {

            JSONArray dataArray = jobj.getJSONArray("data");
            for (int cnt = 0; cnt < dataArray.length(); cnt++) {
                //                    Transaction tx = (Transaction) hibernateTemplate.beginTransaction();
                JSONObject recObj = dataArray.getJSONObject(cnt);
                List existingContact = zohoRequestDAO.executeQuery(Hql, new Object[] { recObj.get("LEADID") });

                JSONObject jobjret = new JSONObject();
                String fname = recObj.getString("First Name");
                String lname = recObj.getString("Last Name");
                lname = fname.equalsIgnoreCase("null") ? lname : fname + " " + lname;
                lname = lname.trim();
                jobjret.put("lastname", recObj.getString("Last Name").equals("null") ? "" : lname);
                jobjret.put("email", recObj.getString("Email").equals("null") ? "" : recObj.getString("Email"));
                jobjret.put("phone", recObj.getString("Phone").equals("null") ? "" : recObj.getString("Phone"));
                jobjret.put("validflag", 1);
                jobjret.put("userid", userid);
                jobjret.put("companyid", companyid);
                jobjret.put("isconverted", "0");
                jobjret.put("istransfered", "0");
                jobjret.put("type", "0");
                jobjret.put("updatedon", new Date());
                jobjret.put("leadid", recObj.getString("LEADID"));
                jobjret.put("leadownerid", userid);
                jobjret.put("isarchive", false);
                jobjret.put("deleteflag", 0);

                if (existingContact.size() > 0) {
                    KwlReturnObject kmsg = crmLeadDAOObj.editLeads(jobjret);
                } else {
                    KwlReturnObject kmsg = crmLeadDAOObj.addLeads(jobjret);
                }
                recCount++;
            }
            txnManager.commit(status);
            result = "{success:true,recCount:" + recCount + ",totalRecords:" + jobj.get("recordCount") + "}";
        }
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } finally {
        //            s.close();
        return result;
    }
}

From source file:com.krawler.esp.handlers.zohoRequestHandler.java

public String saveUpdateZohoAccounts(String username, String password, String authToken, String userid,
        String companyid) {//from ww  w.j a  v  a  2s. co m

    //        Session s = zohoRequestDAO.getCurrentSession();
    String result = "{success:false,recCount:0,totalRecords:0}";
    int recCount = 0;
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        String Hql = "from CrmAccount c where  c.accountid= ?";
        JSONObject jobj = getRecordJson("Accounts", username, password, authToken); //Potential , Leads, Accounts
        if (jobj.get("success").equals(true)) {
            JSONArray dataArray = jobj.getJSONArray("data");
            for (int cnt = 0; cnt < dataArray.length(); cnt++) {
                //                    Transaction tx = (Transaction) s.beginTransaction();
                JSONObject recObj = dataArray.getJSONObject(cnt);
                List existingContact = zohoRequestDAO.executeQuery(Hql,
                        new Object[] { recObj.get("ACCOUNTID") });

                JSONObject accJObj = new JSONObject();
                accJObj.put("accountid", recObj.get("ACCOUNTID"));
                accJObj.put("companyid", companyid);
                accJObj.put("userid", userid);
                accJObj.put("updatedon", new Date());
                accJObj.put("accountname", recObj.getString("Account Name").equals("null") ? ""
                        : recObj.getString("Account Name"));
                accJObj.put("description", "");
                accJObj.put("email",
                        recObj.getString("Website").equals("null") ? "" : recObj.getString("Website"));
                accJObj.put("phone", recObj.getString("Phone").equals("null") ? "" : recObj.getString("Phone"));
                accJObj.put("revenue", recObj.getString("Annual Revenue").equals("null") ? ""
                        : recObj.getString("Annual Revenue"));
                accJObj.put("validflag", 1);
                accJObj.put("accountownerid", userid);
                accJObj.put("isarchive", false);
                accJObj.put("deleteflag", 0);

                if (existingContact.size() > 0) {
                    KwlReturnObject kmsg = crmAccountDAOObj.editAccounts(accJObj);
                } else {
                    //                        accJObj.put("createdon", new Date());
                    KwlReturnObject kmsg = crmAccountDAOObj.addAccounts(accJObj);
                }
                recCount++;
            }
            txnManager.commit(status);
            result = "{success:true,recCount:" + recCount + ",totalRecords:" + jobj.get("recordCount") + "}";
        }
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    } finally {
        //            s.close();
        return result;
    }

}