Java Code Examples for org.springframework.transaction.support.DefaultTransactionDefinition

The following examples show how to use org.springframework.transaction.support.DefaultTransactionDefinition. These examples are extracted from open source projects. 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
public void handleWaitingTickets() {
    Map<Boolean, List<Event>> activeEvents = eventManager.getActiveEvents().stream()
        .collect(Collectors.partitioningBy(this::isWaitingListFormEnabled));
    activeEvents.get(true).forEach(event -> {
        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        try {
            ticketReservationManager.revertTicketsToFreeIfAccessRestricted(event.getId());
            revertTicketToFreeIfCategoryIsExpired(event);
            distributeAvailableSeats(event);
            transactionManager.commit(transaction);
        } catch(Exception ex) {
            if(!(ex instanceof TransactionException)) {
                transactionManager.rollback(transaction);
            }
            log.error("cannot process waiting list for event {}", event.getShortName(), ex);
        }
    });
    activeEvents.get(false).forEach(eventManager::resetReleasedTickets);
}
 
Example 2
Source Project: spring-analysis-note   Source File: TransactionSupportTests.java    License: MIT License 6 votes vote down vote up
@Test
public void existingTransaction() {
	PlatformTransactionManager tm = new TestTransactionManager(true, true);
	DefaultTransactionStatus status1 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
	assertTrue("Must have transaction", status1.getTransaction() != null);
	assertTrue("Must not be new transaction", !status1.isNewTransaction());

	DefaultTransactionStatus status2 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
	assertTrue("Must have transaction", status2.getTransaction() != null);
	assertTrue("Must not be new transaction", !status2.isNewTransaction());

	try {
		DefaultTransactionStatus status3 = (DefaultTransactionStatus)
				tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
		assertTrue("Must have transaction", status3.getTransaction() != null);
		assertTrue("Must not be new transaction", !status3.isNewTransaction());
	}
	catch (NoTransactionException ex) {
		fail("Should not have thrown NoTransactionException");
	}
}
 
Example 3
@Test
public void noExistingTransaction() {
	ReactiveTransactionManager tm = new ReactiveTestTransactionManager(false, true);

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).consumeNextWith(actual ->
				assertFalse(actual.hasTransaction())
			).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED))
			.cast(GenericReactiveTransaction.class).subscriberContext(TransactionContextManager.createTransactionContext())
			.as(StepVerifier::create).consumeNextWith(actual -> {
				assertTrue(actual.hasTransaction());
				assertTrue(actual.isNewTransaction());
			}).verifyComplete();

	tm.getReactiveTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY))
			.subscriberContext(TransactionContextManager.createTransactionContext()).cast(GenericReactiveTransaction.class)
			.as(StepVerifier::create).expectError(IllegalTransactionStateException.class).verify();
}
 
Example 4
/**
 * 补偿的时候,不走分布式事务处理.
 *
 * @param point point 切点
 * @param info  信息
 * @return Object
 * @throws Throwable ex
 */
@Override
public Object handler(final ProceedingJoinPoint point, final TxTransactionInfo info) throws Throwable {
    TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID);

    PlatformTransactionManager platformTransactionManager =
            TransactionManagerHelper.getTransactionManager(info.getTransactionManager());
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def);
    try {
        final Object proceed = point.proceed();
        platformTransactionManager.commit(transactionStatus);
        return proceed;
    } catch (Throwable e) {
        platformTransactionManager.rollback(transactionStatus);
        throw e;
    } finally {
        TxTransactionLocal.getInstance().removeTxGroupId();
        CompensationLocal.getInstance().removeCompensationId();
    }
}
 
Example 5
@Test
public void transactionTemplateWithException() {
	ReactiveTestTransactionManager tm = new ReactiveTestTransactionManager(false, true);
	TransactionalOperator operator = TransactionalOperator.create(tm, new DefaultTransactionDefinition());
	RuntimeException ex = new RuntimeException("Some application exception");

	Mono.error(ex).as(operator::transactional)
			.as(StepVerifier::create)
			.expectError(RuntimeException.class)
			.verify();

	assertHasBegan(tm);
	assertHasNotCommitted(tm);
	assertHasRolledBack(tm);
	assertHasNotSetRollbackOnly(tm);
	assertHasCleanedUp(tm);
}
 
Example 6
@Test
public void testTransactionRollback() 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(new SessionCallback<Void>() {
		@Override
		public Void doInJms(Session sess) {
			assertTrue(sess == session);
			return null;
		}
	});
	tm.rollback(ts);

	verify(session).rollback();
	verify(session).close();
	verify(con).close();
}
 
Example 7
@Test
public void uowManagerFoundInJndi() {
	MockUOWManager manager = new MockUOWManager();
	ExpectedLookupTemplate jndiTemplate =
			new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager();
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			return "result";
		}
	}));

	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example 8
@Test
public void propagationMandatoryFailsInCaseOfNoExistingTransaction() {
	MockUOWManager manager = new MockUOWManager();
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager);
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

	try {
		ptm.execute(definition, new TransactionCallback<String>() {
			@Override
			public String doInTransaction(TransactionStatus status) {
				return "result";
			}
		});
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example 9
Source Project: nh-micro   Source File: MicroServiceTemplateSupport.java    License: Apache License 2.0 6 votes vote down vote up
public Object execGroovyRetObjByDbTran(String groovyName, String methodName,
			Object... paramArray) throws Exception{
/*		MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType);
		DataSource dataSource=microDao.getMicroDataSource();
		PlatformTransactionManager  transactionManager=new DataSourceTransactionManager(dataSource);*/
		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
	    	Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray);
	    	transactionManager.commit(status);
	    	return retObj;
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw ex;
	    }
		
	}
 
Example 10
/**
 * Supports Integer values for the isolation level constants
 * as well as isolation level names as defined on the
 * {@link org.springframework.transaction.TransactionDefinition TransactionDefinition interface}.
 */
@Override
protected Object resolveSpecifiedLookupKey(Object lookupKey) {
	if (lookupKey instanceof Integer) {
		return lookupKey;
	}
	else if (lookupKey instanceof String) {
		String constantName = (String) lookupKey;
		if (!constantName.startsWith(DefaultTransactionDefinition.PREFIX_ISOLATION)) {
			throw new IllegalArgumentException("Only isolation constants allowed");
		}
		return constants.asNumber(constantName);
	}
	else {
		throw new IllegalArgumentException(
				"Invalid lookup key - needs to be isolation level Integer or isolation level name String: " + lookupKey);
	}
}
 
Example 11
public DataBaseTransactionLogWritterImpl(ObjectSerializer objectSerializer,DataSource dataSource, ByteFormIdCodec idCodec,String tablePrefix) {
	super();
	this.objectSerializer = objectSerializer;
	this.idCodec = idCodec;
	this.dataSource = dataSource;
	transactionManager = new DataSourceTransactionManager(dataSource);
	transactionTemplate = new TransactionTemplate(transactionManager, new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
	
	if(!StringUtils.isEmpty(tablePrefix)) {
		tablePrefix = tablePrefix.trim();
		
		cleanLog = cleanLog.replace("trans_log_detail", tablePrefix + "trans_log_detail");
		cleanLog = cleanLog.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
		deleteUnfinishedTag = deleteUnfinishedTag.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
		insertTransDetail = insertTransDetail.replace("trans_log_detail", tablePrefix + "trans_log_detail");
		insertUnfinished = insertUnfinished.replace("trans_log_unfinished", tablePrefix + "trans_log_unfinished");
	}

}
 
Example 12
@Test
public void noExistingTransaction() {
	PlatformTransactionManager tm = new TestTransactionManager(false, true);
	DefaultTransactionStatus status1 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS));
	assertTrue("Must not have transaction", status1.getTransaction() == null);

	DefaultTransactionStatus status2 = (DefaultTransactionStatus)
			tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED));
	assertTrue("Must have transaction", status2.getTransaction() != null);
	assertTrue("Must be new transaction", status2.isNewTransaction());

	try {
		tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_MANDATORY));
		fail("Should not have thrown NoTransactionException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}
}
 
Example 13
Source Project: spring-analysis-note   Source File: JmsTransactionManagerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testLazyTransactionalSession() throws JMSException {
	ConnectionFactory cf = mock(ConnectionFactory.class);
	Connection con = mock(Connection.class);
	final Session session = mock(Session.class);

	JmsTransactionManager tm = new JmsTransactionManager(cf);
	tm.setLazyResourceRetrieval(true);
	TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition());

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

	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 Project: sakai   Source File: SampleDataLoader.java    License: 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 15
Source Project: frostmourne   Source File: AlarmAdminService.java    License: MIT License 6 votes vote down vote up
public boolean delete(Long alarmId) {
    Alarm alarm = alarmMapper.selectByPrimaryKey(alarmId);
    if (alarm == null) {
        return false;
    }
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    TransactionStatus status = frostmourneTransactionManager.getTransaction(def);
    try {
        alarmMapper.deleteByPrimaryKey(alarmId);
        alertMapper.deleteByAlarm(alarmId);
        metricMapper.deleteByAlarm(alarmId);
        ruleMapper.deleteByAlarm(alarmId);
        rulePropertyMapper.deleteByAlarm(alarmId);
        recipientMapper.deleteByAlarm(alarmId);
        scheduleService.removeJob(Math.toIntExact(alarm.getJob_id()));
    } catch (Exception ex) {
        frostmourneTransactionManager.rollback(status);
    }
    frostmourneTransactionManager.commit(status);
    return true;
}
 
Example 16
/**
 * Supports Integer values for the isolation level constants
 * as well as isolation level names as defined on the
 * {@link org.springframework.transaction.TransactionDefinition TransactionDefinition interface}.
 */
@Override
protected Object resolveSpecifiedLookupKey(Object lookupKey) {
	if (lookupKey instanceof Integer) {
		return lookupKey;
	}
	else if (lookupKey instanceof String) {
		String constantName = (String) lookupKey;
		if (!constantName.startsWith(DefaultTransactionDefinition.PREFIX_ISOLATION)) {
			throw new IllegalArgumentException("Only isolation constants allowed");
		}
		return constants.asNumber(constantName);
	}
	else {
		throw new IllegalArgumentException(
				"Invalid lookup key - needs to be isolation level Integer or isolation level name String: " + lookupKey);
	}
}
 
Example 17
@Override
public <R> R execute(@NonNull TransactionDefinition definition, @NonNull TransactionCallback<Connection, R> callback) {
    ArgumentUtils.requireNonNull("callback", callback);
    ArgumentUtils.requireNonNull("definition", definition);

    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setReadOnly(definition.isReadOnly());
    def.setIsolationLevel(definition.getIsolationLevel().getCode());
    def.setPropagationBehavior(definition.getPropagationBehavior().ordinal());
    def.setName(definition.getName());
    final Duration timeout = definition.getTimeout();
    if (!timeout.isNegative()) {
        def.setTimeout((int) timeout.getSeconds());
    }
    TransactionTemplate template = new TransactionTemplate(transactionManager, def);
    return template.execute(status -> {
                try {
                    return callback.call(new JpaTransactionStatus(status));
                } catch (RuntimeException | Error ex) {
                    throw ex;
                } catch (Exception e) {
                    throw new UndeclaredThrowableException(e, "TransactionCallback threw undeclared checked exception");
                }
            }
    );
}
 
Example 18
Source Project: java-technology-stack   Source File: JtaTransactionManagerTests.java    License: MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithDoubleCommit() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
			Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first commit
	ptm.commit(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second commit attempt
		ptm.commit(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 19
@Test
public void uowManagerFoundInJndi() {
	MockUOWManager manager = new MockUOWManager();
	ExpectedLookupTemplate jndiTemplate =
			new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager);
	WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager();
	ptm.setJndiTemplate(jndiTemplate);
	ptm.afterPropertiesSet();

	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() {
		@Override
		public String doInTransaction(TransactionStatus status) {
			return "result";
		}
	}));

	assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType());
	assertFalse(manager.getJoined());
	assertFalse(manager.getRollbackOnly());
}
 
Example 20
Source Project: tddl   Source File: JDBCTemplateTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tractionRollBackTest() {
    JdbcTemplate andorJT = new JdbcTemplate(us);
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(us);
    TransactionStatus ts = transactionManager.getTransaction(def);

    try {
        sql = String.format("insert into %s (pk,name) values(?,?)", normaltblTableName);
        andorJT.update(sql, new Object[] { RANDOM_ID, name });
        sql = String.format("select * from %s where pk= ?", normaltblTableName);
        Map re = andorJT.queryForMap(sql, new Object[] { RANDOM_ID });
        Assert.assertEquals(name, String.valueOf(re.get("NAME")));
        // 回滚
        transactionManager.rollback(ts);
    } catch (DataAccessException ex) {
        transactionManager.rollback(ts);
        throw ex;
    } finally {
    }
    // 验证查询不到数据
    sql = String.format("select * from %s where pk= ?", normaltblTableName);
    List le = andorJT.queryForList(sql, new Object[] { RANDOM_ID });
    Assert.assertEquals(0, le.size());
}
 
Example 21
@Test
public void jtaTransactionManagerWithDoubleCommit() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
			Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	TransactionStatus status = ptm.getTransaction(new DefaultTransactionDefinition());
	assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
	// first commit
	ptm.commit(status);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		// second commit attempt
		ptm.commit(status);
		fail("Should have thrown IllegalTransactionStateException");
	}
	catch (IllegalTransactionStateException ex) {
		// expected
	}

	verify(ut).begin();
	verify(ut).commit();
}
 
Example 22
Source Project: sdn-rx   Source File: Neo4jTransactionManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void triggerCommitCorrectly() {

	when(driver.defaultTypeSystem()).thenReturn(typeSystem);
	when(driver.session(any(SessionConfig.class))).thenReturn(session);
	when(session.beginTransaction(any(TransactionConfig.class))).thenReturn(transaction);
	when(transaction.run(anyString(), anyMap())).thenReturn(statementResult);
	when(session.isOpen()).thenReturn(true);
	when(transaction.isOpen()).thenReturn(true, false);

	Neo4jTransactionManager txManager = new Neo4jTransactionManager(driver);
	TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());

	Neo4jClient client = Neo4jClient.create(driver);
	client.query("RETURN 1").run();

	txManager.commit(txStatus);

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

	verify(session).isOpen();
	verify(session).beginTransaction(any(TransactionConfig.class));

	verify(transaction, times(2)).isOpen();
	verify(transaction).commit();
	verify(transaction).close();

	verify(session).close();
}
 
Example 23
Source Project: sdn-rx   Source File: Neo4jTransactionManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void usesBookmarksCorrectly() throws Exception {

	when(driver.defaultTypeSystem()).thenReturn(typeSystem);
	when(driver.session(any(SessionConfig.class))).thenReturn(session);
	when(session.beginTransaction(any(TransactionConfig.class))).thenReturn(transaction);
	Bookmark bookmark = new Bookmark() {
		@Override public Set<String> values() {
			return Collections.singleton("blubb");
		}

		@Override public boolean isEmpty() {
			return false;
		}
	};
	when(session.lastBookmark()).thenReturn(bookmark);
	when(transaction.run(anyString(), anyMap())).thenReturn(statementResult);
	when(session.isOpen()).thenReturn(true);
	when(transaction.isOpen()).thenReturn(true, false);

	Neo4jTransactionManager txManager = spy(new Neo4jTransactionManager(driver));
	Neo4jBookmarkManager bookmarkManager = mock(Neo4jBookmarkManager.class);
	injectBookmarkManager(txManager, bookmarkManager);

	TransactionStatus txStatus = txManager.getTransaction(new DefaultTransactionDefinition());

	Neo4jClient client = Neo4jClient.create(driver);
	client.query("RETURN 1").run();

	txManager.commit(txStatus);

	verify(txManager).doBegin(any(), any(TransactionDefinition.class));
	verify(bookmarkManager).getBookmarks();
	verify(txManager).doCommit(any(DefaultTransactionStatus.class));
	verify(bookmarkManager).updateBookmarks(anyCollection(), eq(bookmark));

}
 
Example 24
Source Project: spring-analysis-note   Source File: DefaultJpaDialectTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testDefaultTransactionDefinition() throws Exception {
	DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
	definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);

	try {
		dialect.beginTransaction(null, definition);
		fail("expected exception");
	}
	catch (TransactionException e) {
		// ok
	}
}
 
Example 25
Source Project: nh-micro   Source File: MicroServiceTemplateSupport.java    License: Apache License 2.0 5 votes vote down vote up
public Integer getSeqByMysql(String seqKey){

		PlatformTransactionManager  transactionManager=MicroTranManagerHolder.getTransactionManager(dbName);
	    DefaultTransactionDefinition def =new DefaultTransactionDefinition();
	    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	    TransactionStatus status=transactionManager.getTransaction(def);
	    try
	    {
			String sql="select get_micro_seq('"+seqKey+"') as seq";
			List retList=getInnerDao().queryObjJoinByCondition(sql);
			if(retList==null){
				transactionManager.commit(status);
				return null;
			}
			Map retMap=(Map) retList.get(0);
			Integer seq=(Integer) retMap.get("seq");
			transactionManager.commit(status);
			return seq;	    	
	    }
	    catch(Exception ex)
	    {
	    	transactionManager.rollback(status);
	        throw new RuntimeException("getseq error",ex);
	    }


	}
 
Example 26
Source Project: iaf   Source File: PullingListenerContainer.java    License: Apache License 2.0 5 votes vote down vote up
public void configure() {
	if (receiver.getNumThreadsPolling() > 0 && receiver.getNumThreadsPolling() < receiver.getNumThreads()) {
		pollToken = new Semaphore(receiver.getNumThreadsPolling());
	}
	processToken = new Semaphore(receiver.getNumThreads());
	maxThreadCount = receiver.getNumThreads();
	if (receiver.isTransacted()) {
		DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
		if (receiver.getTransactionTimeout() > 0) {
			txDef.setTimeout(receiver.getTransactionTimeout());
		}
		txNew = txDef;
	}
}
 
Example 27
Source Project: studio   Source File: DependencyServiceImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Set<String> upsertDependencies(String site, String path)
        throws SiteNotFoundException, ContentNotFoundException, ServiceLayerException {
    Set<String> toRet = new HashSet<String>();
    logger.debug("Resolving dependencies for content site: " + site + " path: " + path);
    Map<String, Set<String>> dependencies = dependencyResolver.resolve(site, path);
    List<DependencyEntity> dependencyEntities = new ArrayList<>();
    if (dependencies != null) {
        logger.debug("Found " + dependencies.size() + " dependencies. Create entities to insert into database.");
        for (String type : dependencies.keySet()) {
            dependencyEntities.addAll(createDependencyEntities(site, path, dependencies.get(type), type, toRet));
        }

        logger.debug("Preparing transaction for database updates.");
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setName("upsertDependencies");

        logger.debug("Starting transaction.");
        TransactionStatus txStatus = transactionManager.getTransaction(defaultTransactionDefinition);

        try {
            logger.debug("Delete all source dependencies for site: " + site + " path: " + path);
            deleteAllSourceDependencies(site, path);
            logger.debug("Insert all extracted dependencies entries for site: " + site + " path: " + path);
            insertDependenciesIntoDatabase(dependencyEntities);
            logger.debug("Committing transaction.");
            transactionManager.commit(txStatus);
        } catch (Exception e) {
            logger.debug("Rolling back transaction.");
            transactionManager.rollback(txStatus);
            throw new ServiceLayerException("Failed to upsert dependencies for site: " + site + " path: " + path, e);
        }

    }
    return toRet;
}
 
Example 28
@Test
void getConnection_NoReadReplicaAvailableReadOnlyTransactionActive_returnsDefaultDataSource()
		throws Exception {

	// Arrange
	DataSource defaultDataSource = mock(DataSource.class);
	Connection connection = mock(Connection.class);

	when(defaultDataSource.getConnection()).thenReturn(connection);

	ReadOnlyRoutingDataSource readOnlyRoutingDataSource = new ReadOnlyRoutingDataSource();
	readOnlyRoutingDataSource.setTargetDataSources(Collections.emptyMap());
	readOnlyRoutingDataSource.setDefaultTargetDataSource(defaultDataSource);
	readOnlyRoutingDataSource.afterPropertiesSet();

	LazyConnectionDataSourceProxy dataSource = new LazyConnectionDataSourceProxy(
			readOnlyRoutingDataSource);

	DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
	transactionDefinition.setReadOnly(true);

	TransactionTemplate transactionTemplate = new TransactionTemplate(
			new DataSourceTransactionManager(dataSource), transactionDefinition);

	// Act
	Connection connectionReturned = transactionTemplate.execute(status -> {
		try {
			return ((ConnectionProxy) dataSource.getConnection())
					.getTargetConnection();
		}
		catch (SQLException e) {
			fail(e.getMessage());
		}
		return null;
	});

	// Assert
	assertThat(connectionReturned).isSameAs(connection);
}
 
Example 29
@Test
public void commitWithoutExistingTransaction() {
	ReactiveTestTransactionManager tm = new ReactiveTestTransactionManager(false, true);
	tm.getReactiveTransaction(new DefaultTransactionDefinition()).flatMap(tm::commit)
			.subscriberContext(TransactionContextManager.createTransactionContext())
			.as(StepVerifier::create).verifyComplete();

	assertHasBegan(tm);
	assertHasCommitted(tm);
	assertHasNoRollback(tm);
	assertHasNotSetRollbackOnly(tm);
	assertHasCleanedUp(tm);
}
 
Example 30
Source Project: cjs_ssms   Source File: Transactioner.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 开启事物
 * @param transactionManager
 */
public void start(DataSourceTransactionManager transactionManager) {
  DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  /*PROPAGATION_REQUIRES_NEW:  事物隔离级别,开启新事务*/
  def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
  status =  transactionManager.getTransaction(def);
}