org.springframework.transaction.TransactionStatus Java Examples

The following examples show how to use org.springframework.transaction.TransactionStatus. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TransactionalTestExecutionListener.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * If a transaction is currently active for the supplied
 * {@linkplain TestContext test context}, this method will end the transaction
 * and run {@link AfterTransaction @AfterTransaction} methods.
 * <p>{@code @AfterTransaction} methods are guaranteed to be invoked even if
 * an error occurs while ending the transaction.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	Method testMethod = testContext.getTestMethod();
	Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

	TransactionContext txContext = TransactionContextHolder.removeCurrentTransactionContext();
	// If there was (or perhaps still is) a transaction...
	if (txContext != null) {
		TransactionStatus transactionStatus = txContext.getTransactionStatus();
		try {
			// If the transaction is still active...
			if (transactionStatus != null && !transactionStatus.isCompleted()) {
				txContext.endTransaction();
			}
		}
		finally {
			runAfterTransactionMethods(testContext);
		}
	}
}
 
Example #2
Source File: UserSqlMapDao.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void changeEnabledStatus(final List<String> usernames, final boolean enabled) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    clearEnabledUserCountFromCache();
                }
            });
            String queryString = String.format("update %s set enabled = :enabled where name in (:userNames)", User.class.getName());
            Query query = sessionFactory.getCurrentSession().createQuery(queryString);
            query.setParameter("enabled", enabled);
            query.setParameterList("userNames", usernames);
            query.executeUpdate();
        }
    });
}
 
Example #3
Source File: DataSourceTransactionManagerTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNever() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
			assertTrue("Is not new transaction", !status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example #4
Source File: AbstractTransactionAspectTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Check that two transactions are created and committed.
 */
@Test
public void twoTransactionsShouldSucceed() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	MapTransactionAttributeSource tas1 = new MapTransactionAttributeSource();
	tas1.register(getNameMethod, txatt);
	MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource();
	tas2.register(setNameMethod, txatt);

	TransactionStatus status = mock(TransactionStatus.class);
	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// expect a transaction
	given(ptm.getTransaction(txatt)).willReturn(status);

	TestBean tb = new TestBean();
	ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] {tas1, tas2});

	checkTransactionStatus(false);
	itb.getName();
	checkTransactionStatus(false);
	itb.setName("myName");
	checkTransactionStatus(false);

	verify(ptm, times(2)).commit(status);
}
 
Example #5
Source File: TransactionSynchronizationManagerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterSynchronization_andNotCallItOnTransactionFailure() {
    final TransactionSynchronizationManager synchronizationManager = new TransactionSynchronizationManager();

    final TransactionSynchronization synchronization = mock(TransactionSynchronization.class);
    try {
        transactionTemplate.execute(new org.springframework.transaction.support.TransactionCallbackWithoutResult() {
            @Override protected void doInTransactionWithoutResult(TransactionStatus status) {
                synchronizationManager.registerSynchronization(synchronization);
                throw new RuntimeException();
            }
        });
    } catch (Exception e) {
        //ignore
    }
    verify(synchronization, never()).afterCommit();
}
 
Example #6
Source File: HeatmapDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void saveOrUpdate(final HeatmapConfig config) {
	if (log.isDebugEnabled()) {
		log.debug("Saving " + config.getClass().getName());
	}
	txTemplate.execute(new TransactionCallback() {
		public Object doInTransaction(TransactionStatus ts) {
			try {
				getSession().saveOrUpdate(config);
			} catch (Exception ex) {
				ts.setRollbackOnly();
			}
			return null;
		}
	});

}
 
Example #7
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Test behavior if the first operation on a connection (getAutoCommit) throws SQLException.
 */
@Test
public void testTransactionWithExceptionOnBegin() throws Exception {
	willThrow(new SQLException("Cannot begin")).given(con).getAutoCommit();

	TransactionTemplate tt = new TransactionTemplate(tm);
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown CannotCreateTransactionException");
	}
	catch (CannotCreateTransactionException ex) {
		// expected
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).close();
}
 
Example #8
Source File: DataSourceTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationNested() throws Exception {
	final TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
			assertTrue("Is new transaction", status.isNewTransaction());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).commit();
	verify(con).close();
}
 
Example #9
Source File: TransactionalTestExecutionListener.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * If a transaction is currently active for the supplied
 * {@linkplain TestContext test context}, this method will end the transaction
 * and run {@link AfterTransaction @AfterTransaction} methods.
 * <p>{@code @AfterTransaction} methods are guaranteed to be invoked even if
 * an error occurs while ending the transaction.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	Method testMethod = testContext.getTestMethod();
	Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null");

	TransactionContext txContext = TransactionContextHolder.removeCurrentTransactionContext();
	// If there was (or perhaps still is) a transaction...
	if (txContext != null) {
		TransactionStatus transactionStatus = txContext.getTransactionStatus();
		try {
			// If the transaction is still active...
			if ((transactionStatus != null) && !transactionStatus.isCompleted()) {
				txContext.endTransaction();
			}
		}
		finally {
			runAfterTransactionMethods(testContext);
		}
	}
}
 
Example #10
Source File: TransactionTemplateTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldUnderstand_InTransaction() {
    TransactionTemplate template = new TransactionTemplate(transactionTemplate);

    final boolean[] inTransactionInBody = new boolean[] {false};
    final boolean[] inTransactionInAfterCommit = new boolean[] {true};
    final boolean[] inTransactionInAfterComplete = new boolean[] {true};

    String returnVal = (String) template.execute(new org.springframework.transaction.support.TransactionCallback() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            setTxnBodyActiveFlag(inTransactionInBody, inTransactionInAfterCommit, inTransactionInAfterComplete, 0);
            return "foo";
        }
    });

    assertThat(inTransactionInBody[0], is(true));
    assertThat(inTransactionInAfterCommit[0], is(false));
    assertThat(inTransactionInAfterComplete[0], is(false));
    assertThat(returnVal, is("foo"));
}
 
Example #11
Source File: SampleDataLoader.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public void init() {
	log.info("Initializing " + getClass().getName());
	if(cmAdmin == null) {
		return;
	}
	if(loadSampleData) {
		loginToSakai();
		PlatformTransactionManager tm = (PlatformTransactionManager)beanFactory.getBean("org.sakaiproject.springframework.orm.hibernate.GlobalTransactionManager");
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = tm.getTransaction(def);
		try {
			load();
		} catch (Exception e) {
			log.error("Unable to load CM data: " + e);
			tm.rollback(status);
		} finally {
			if(!status.isCompleted()) {
				tm.commit(status);
			}
		}
		logoutFromSakai();
	} else {
		if(log.isInfoEnabled()) log.info("Skipped CM data load");
	}
}
 
Example #12
Source File: MultithreadedDaoTestNgITCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            daoIdentity.setType(IdentityImpl.class);
            daoSubscriber.setType(Subscriber.class);
            daoPublisher.setType(Publisher.class);
            daoSubscription.setType(Subscription.class);

            createSubscription(createPublisher(), createSubscriber(createIdentity(IDENTITY_NAME)));

        }
    });

}
 
Example #13
Source File: JmsTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionCommit() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	given(cf.createConnection()).willReturn(con);
	given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());
	JmsTemplate jt = new JmsTemplate(cf);
	jt.execute((SessionCallback<Void>) sess -> {
		assertSame(sess, session);
		return null;
	});
	tm.commit(ts);

	verify(session).commit();
	verify(session).close();
	verify(con).close();
}
 
Example #14
Source File: PublishEventPerformance.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void publishEventManySubscriptionsForOnePublisher() {
    long startTime = System.currentTimeMillis();
    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            int numEvents = notificationServiceImpl.publishEvent(getPublishEventTO());
            log.info("publishEventManySubscriptionsForOnePublisher - numEvents: " + numEvents);
            assertEquals(NUMBER_OF_SUBSCRIBERS * NUMBER_OF_PUBLISHERS, numEvents);
        }
    });
    long endTime = System.currentTimeMillis();
    long duration = (endTime - startTime) / 1000;
    log.info("DURATION in seconds: " + duration);
    assertTrue("maximal execution time for " + NUMBER_OF_SUBSCRIBERS + " subscriptions exceeded: maximal time in seconds: " + MAX_EXECUTION_TIME_IN_SECONDS
            + ", actual duration in seconds: " + duration, duration <= MAX_EXECUTION_TIME_IN_SECONDS);

}
 
Example #15
Source File: MaterialRepositoryIntegrationTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void assertCanLoadAndSaveMaterialRevisionsFor(MaterialConfig materialConfig) {
    final PipelineConfig pipelineConfig = PipelineMother.createPipelineConfig("mingle", new MaterialConfigs(materialConfig), "dev");

    final MaterialRevisions materialRevisions = ModificationsMother.modifyOneFile(pipelineConfig);
    MaterialRevision materialRevision = materialRevisions.getMaterialRevision(0);

    final Pipeline[] pipeline = new Pipeline[1];

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            //assume that we have saved the materials
            repo.save(materialRevisions);

            PipelineConfig config = PipelineMother.withTwoStagesOneBuildEach("pipeline-name", "stage-1", "stage-2");
            config.setMaterialConfigs(materialRevisions.getMaterials().convertToConfigs());
            pipeline[0] = instanceFactory.createPipelineInstance(pipelineConfig, BuildCause.createManualForced(materialRevisions, Username.ANONYMOUS), new DefaultSchedulingContext(DEFAULT_APPROVED_BY), md5,
                    new TimeProvider());

            //this should persist the materials
            pipelineSqlMapDao.save(pipeline[0]);
        }
    });

    assertMaterialRevisions(materialRevision, pipeline[0]);
}
 
Example #16
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsolationLevel() {
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);

	PlatformTransactionManager tm = new JdoTransactionManager(pmf);
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
		}
	});
	verify(tx).setIsolationLevel(Constants.TX_SERIALIZABLE);
	verify(pm).close();
}
 
Example #17
Source File: MultithreadedDaoTestNgITCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public void setup() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            daoIdentity.setType(IdentityImpl.class);
            daoSubscriber.setType(Subscriber.class);
            daoPublisher.setType(Publisher.class);
            daoSubscription.setType(Subscription.class);

            createSubscription(createPublisher(), createSubscriber(createIdentity(IDENTITY_NAME)));

        }
    });

}
 
Example #18
Source File: AssignmentContentProducer.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String getUrl(String ref) {

        return transactionTemplate.execute(new TransactionCallback<String>() {

            @Override
            public String doInTransaction(TransactionStatus status) {

                AssignmentReferenceReckoner.AssignmentReference r = AssignmentReferenceReckoner.reckoner().reference(ref).reckon();

                try {
                    Site site = siteService.getSite(r.getContext());
                    ToolConfiguration fromTool = site.getToolForCommonId("sakai.assignment.grades");
                    return serverConfigurationService.getPortalUrl()
                            + "/directtool/"
                            + fromTool.getId()
                            + "?assignmentId="
                            + ref
                            + "&panel=Main&sakai_action=doView_assignment";
                } catch (Exception e) {
                    log.error("Failed to get deep link for context {} and assignment {}. Returning empty string.", r.getContext(), r.getId(), e);
                }
                return "";
            }
        });
    }
 
Example #19
Source File: AbstractTransactionAspectTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Check that a transaction is created and committed.
 */
@Test
public void transactionShouldSucceed() throws Exception {
	TransactionAttribute txatt = new DefaultTransactionAttribute();

	MapTransactionAttributeSource tas = new MapTransactionAttributeSource();
	tas.register(getNameMethod, txatt);

	TransactionStatus status = mock(TransactionStatus.class);
	PlatformTransactionManager ptm = mock(PlatformTransactionManager.class);
	// expect a transaction
	given(ptm.getTransaction(txatt)).willReturn(status);

	TestBean tb = new TestBean();
	ITestBean itb = (ITestBean) advised(tb, ptm, tas);

	checkTransactionStatus(false);
	itb.getName();
	checkTransactionStatus(false);

	verify(ptm).commit(status);
}
 
Example #20
Source File: HibernateCriteriaTest.java    From vladmihalcea.wordpress.com with Apache License 2.0 6 votes vote down vote up
private List<Product> getProducts_Mercifully() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Image> imageRoot = query.from(Image.class);
            Join<Image, Product> productJoin = imageRoot.join(Image_.product);
            query.select(productJoin);
            query.distinct(true);
            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(productJoin.get(Product_.name)), "%tv%"));
            criteria.add(cb.gt(imageRoot.get(Image_.index), 0));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}
 
Example #21
Source File: TargetDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void save(final Schedule aSchedule) {
	txTemplate.execute(
			new TransactionCallback() {
				public Object doInTransaction(TransactionStatus ts) {
					try { 
						log.debug("Before Saving of Schedule");
						getSession().saveOrUpdate(aSchedule);
						log.debug("After Saving Schedule");
					}
					catch(Exception ex) {
						log.debug("Setting Rollback Only", ex);
						ts.setRollbackOnly();
						throw new WCTRuntimeException("Failed to save schedule", ex);
					}
					return null;
				}
			}
	);	
}
 
Example #22
Source File: JpaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidIsolation() {
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);

	given(manager.isOpen()).willReturn(true);

	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}

	verify(manager).close();
}
 
Example #23
Source File: ReleaseAfterStatementForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public PostDTO savePostTitle(Long id, String title) {
    Post post = postDAO.findById(id);

    post.setTitle(title);
    entityManager.flush();

    executorService.submit(() -> {
        transactionTemplate.execute(new TransactionCallback<Void>() {
            @Nullable
            @Override
            public Void doInTransaction(TransactionStatus status) {
                awaitOnLatch(latch1);
                try {
                    PostDTO _postDTO =  postDAO.getPostDTOById(id);
                    assertNotEquals(title, _postDTO.getTitle());
                } catch (Throwable e) {
                    LOGGER.error("Failure", e);
                }

                entityManager.unwrap(Session.class).doWork(connection -> {
                    latch2.countDown();
                    awaitOnLatch(latch3);
                });

                return null;
            }
        });
    });

    latch1.countDown();
    awaitOnLatch(latch2);
    PostDTO postDTO =  postDAO.getPostDTOById(id);
    latch3.countDown();
    executorService.shutdownNow();

    return postDTO;
}
 
Example #24
Source File: SampleDataGenerator.java    From dddsample-core with MIT License 5 votes vote down vote up
public static void loadSampleData(final JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            loadLocationData(jdbcTemplate);
            loadCarrierMovementData(jdbcTemplate);
            loadCargoData(jdbcTemplate);
            loadItineraryData(jdbcTemplate);
            loadHandlingEventData(jdbcTemplate);
        }
    });
}
 
Example #25
Source File: CciLocalTransactionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Test if a transaction ( begin / commit ) is executed on the
 * LocalTransaction when CciLocalTransactionManager is specified as
 * transaction manager.
 */
@Test
public void testLocalTransactionCommit() throws ResourceException {
	final ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
	Connection connection = mock(Connection.class);
	Interaction interaction = mock(Interaction.class);
	LocalTransaction localTransaction = mock(LocalTransaction.class);
	final Record record = mock(Record.class);
	final InteractionSpec interactionSpec = mock(InteractionSpec.class);

	given(connectionFactory.getConnection()).willReturn(connection);
	given(connection.getLocalTransaction()).willReturn(localTransaction);
	given(connection.createInteraction()).willReturn(interaction);
	given(interaction.execute(interactionSpec, record, record)).willReturn(true);
	given(connection.getLocalTransaction()).willReturn(localTransaction);

	CciLocalTransactionManager tm = new CciLocalTransactionManager();
	tm.setConnectionFactory(connectionFactory);
	TransactionTemplate tt = new TransactionTemplate(tm);

	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(connectionFactory));
			CciTemplate ct = new CciTemplate(connectionFactory);
			ct.execute(interactionSpec, record, record);
		}
	});

	verify(localTransaction).begin();
	verify(interaction).close();
	verify(localTransaction).commit();
	verify(connection).close();
}
 
Example #26
Source File: NotificationServiceImpTestNglTCaseNew.java    From olat with Apache License 2.0 5 votes vote down vote up
@Test
public void isSubscribed_subscriptionExists() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            Publisher publisher = publisherDao.savePublisher(daoObjectMother.createForumOnePublisher());
            Subscriber subscriber = subscriberDao.createAndSaveSubscriber(subscriberIdentity);
            subscriptionDao.createOrReuseSubscription(subscriber, publisher);
        }
    });

    assertTrue("Subscription should exists", notificationServiceImpl.isSubscribed(new NotificationSubscriptionContext(subscriberIdentity,
            ForumNotificationTypeHandler.FORUM_SOURCE_TYPE, sourceId, Publisher.ContextType.COURSE, contextId, null)));
}
 
Example #27
Source File: FirstTccActionImpl.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
/**
 * 二阶段回滚
 * @param businessActionContext
 * @return
 */
@Override
public boolean rollback(BusinessActionContext businessActionContext) {
    //分布式事务ID
    final String xid = businessActionContext.getXid();
    //账户ID
    final String accountNo = String.valueOf(businessActionContext.getActionContext("accountNo"));
    //转出金额
    final double amount = Double.valueOf(String.valueOf(businessActionContext.getActionContext("amount")));
    return fromDsTransactionTemplate.execute(new TransactionCallback<Boolean>() {

        @Override
        public Boolean doInTransaction(TransactionStatus status) {
            try{
                Account account = fromAccountDAO.getAccountForUpdate(accountNo);
                if(account == null){
                    //账户不存在,回滚什么都不做
                    return true;
                }
                //释放冻结金额
                account.setFreezedAmount(account.getFreezedAmount()  - amount);
                fromAccountDAO.updateFreezedAmount(account);
                System.out.println(String.format("Undo prepareMinus account[%s] amount[%f], dtx transaction id: %s.", accountNo, amount, xid));
                return true;
            }catch (Throwable t){
                t.printStackTrace();
                status.setRollbackOnly();
                return false;
            }
        }
    });
}
 
Example #28
Source File: UserService.java    From gocd with Apache License 2.0 5 votes vote down vote up
public void disable(final List<String> usersToBeDisabled, LocalizedOperationResult result) {
    synchronized (disableUserMutex) {
        if (willDisableAllAdmins(usersToBeDisabled)) {
            result.badRequest("There must be atleast one admin user enabled!");
            return;
        }
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                userDao.disableUsers(usersToBeDisabled);
            }
        });
    }
}
 
Example #29
Source File: WebSphereUowTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void newTransactionWithRollbackOnly() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			status.setRollbackOnly();
			return "result";
		}
	}));

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
	assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());

	assertEquals(0, manager.getUOWTimeout());
	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertTrue(manager.getRollbackOnly());
}
 
Example #30
Source File: Neo4jTransactionManagerTest.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void shouldParticipateInOngoingTransactionWithCommit() throws Exception {

	when(userTransaction.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE,
			Status.STATUS_ACTIVE);

	JtaTransactionManager txManager = new JtaTransactionManager(userTransaction);
	TransactionTemplate txTemplate = new TransactionTemplate(txManager);

	txTemplate.execute(new TransactionCallbackWithoutResult() {

		@Override
		protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

			assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
			assertThat(transactionStatus.isNewTransaction()).isTrue();
			assertThat(TransactionSynchronizationManager.hasResource(driver)).isFalse();

			Transaction nativeTransaction = retrieveTransaction(driver, databaseName);

			assertThat(nativeTransaction).isNotNull();
			assertThat(TransactionSynchronizationManager.hasResource(driver)).isTrue();
		}
	});

	verify(userTransaction).begin();

	verify(driver).session(any(SessionConfig.class));

	verify(session, times(2)).isOpen();
	verify(session).beginTransaction(any(TransactionConfig.class));
	verify(session).close();

	verify(transaction, times(3)).isOpen();
	verify(transaction).commit();
	verify(transaction).close();
}