org.springframework.transaction.support.TransactionTemplate Java Examples

The following examples show how to use org.springframework.transaction.support.TransactionTemplate. 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: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	final TransactionSynchronization synch = mock(TransactionSynchronization.class);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
			TransactionSynchronizationManager.registerSynchronization(synch);
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setRollbackOnly();
	verify(synch).beforeCompletion();
	verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
}
 
Example #2
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
		}
	});

	verify(ut).begin();
	verify(ut).commit();
}
 
Example #3
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithNestedBegin() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			// something transactional
		}
	});

	verify(ut).begin();
	verify(ut).commit();
}
 
Example #4
Source File: NotificationServiceImpTestNglTCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@AfterMethod
public void cleanUp() {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {

            subscriberDao.deleteSubscriber(alf);
            subscriberDao.deleteSubscriber(berta);
            subscriberDao.deleteSubscriber(clara);
            subscriberDao.deleteSubscriber(subscriberIdentity);
            subscriberDao.deleteSubscriber(publisherIdentity);

            Publisher publisher = publisherDao.findPublisher(ForumNotificationTypeHandler.FORUM_SOURCE_TYPE, sourceId);
            if (publisher != null)
                publisherDao.deletePublisher(publisher);

        }
    });
}
 
Example #5
Source File: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown TransactionSuspensionNotSupportedException");
	}
	catch (TransactionSuspensionNotSupportedException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #6
Source File: MongoTransactionTemplateLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTransactionTemplate_whenPerformTransaction_thenSuccess() {
    mongoTemplate.setSessionSynchronization(SessionSynchronization.ALWAYS);                                     
    TransactionTemplate transactionTemplate = new TransactionTemplate(mongoTransactionManager);
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            mongoTemplate.insert(new User("Kim", 20));
            mongoTemplate.insert(new User("Jack", 45));
        };
    });

    Query query = new Query().addCriteria(Criteria.where("name")
        .is("Jack"));
    List<User> users = mongoTemplate.find(query, User.class);
    
    assertThat(users.size(), is(1));
}
 
Example #7
Source File: TransactionSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void transactionTemplateWithException() {
	TestTransactionManager tm = new TestTransactionManager(false, true);
	TransactionTemplate template = new TransactionTemplate(tm);
	final RuntimeException ex = new RuntimeException("Some application exception");
	try {
		template.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				throw ex;
			}
		});
		fail("Should have propagated RuntimeException");
	}
	catch (RuntimeException caught) {
		// expected
		assertTrue("Correct exception", caught == ex);
		assertTrue("triggered begin", tm.begin);
		assertTrue("no commit", !tm.commit);
		assertTrue("triggered rollback", tm.rollback);
		assertTrue("no rollbackOnly", !tm.rollbackOnly);
	}
}
 
Example #8
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronizationName("SYNCHRONIZATION_NEVER");
	tt.setTimeout(10);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(ut).setTransactionTimeout(10);
	verify(ut).begin();
	verify(ut, atLeastOnce()).getStatus();
	verify(ut).rollback();
}
 
Example #9
Source File: AbstractDbDialect.java    From DataLink with Apache License 2.0 6 votes vote down vote up
public AbstractDbDialect(final JdbcTemplate jdbcTemplate, LobHandler lobHandler) {
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // 初始化transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    // 初始化一些数据
    jdbcTemplate.execute(new ConnectionCallback() {

        public Object doInConnection(Connection c) throws SQLException, DataAccessException {
            DatabaseMetaData meta = c.getMetaData();
            databaseName = meta.getDatabaseProductName();
            databaseMajorVersion = meta.getDatabaseMajorVersion();
            databaseMinorVersion = meta.getDatabaseMinorVersion();

            return null;
        }
    });

    initTables(jdbcTemplate);
}
 
Example #10
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	ptm.setTransactionSynchronization(JtaTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	ptm.afterPropertiesSet();

	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
			status.setRollbackOnly();
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #11
Source File: NotifySubscribersPerformance.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test
public void notifySubscribers() {

    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            long startTime = System.currentTimeMillis();

            NotifyStatistics notifyStatistics = notificationServiceImpl.notifySubscribers();
            log.info("notifyStatistics.getDeliveredCounter(): " + notifyStatistics.getDeliveredCounter());
            log.info("notifyStatistics.getFailedCounter(): " + notifyStatistics.getFailedCounter());
            log.info("notifyStatistics.getTotalCounter(): " + notifyStatistics.getTotalCounter());

            long endTime = System.currentTimeMillis();
            long duration = (endTime - startTime) / 1000;
            log.info("TOTAL EXECUTION_TIME_IN_SECONDS[" + duration + "]  NEEDED FOR THE NOTIFY PROCESS TO NOTIFY [" + NUMBER_OF_SUBSCRIBERS
                    + "] SUBSCRIBERS WITH THE APPROPRIATE [" + (NUMBER_OF_SUBSCRIBERS * NUMBER_OF_SUBSCRIPTIONS_FOR_ONE_SUBSCRIBER) + "] EVENTS ");
            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 #12
Source File: HibernateXmlConverter.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Schreibt alle Objekte der Datenbank in den angegebenen Writer.<br/>
 * <b>Warnung!</b> Bei der Serialisierung von Collections wird derzeit nur {@link java.util.Set} sauber unterstützt.
 * @param writer Ziel für die XML-Datei.
 * @param includeHistory bei false werden die History Einträge nicht geschrieben
 * @param preserveIds If true, the object ids will be preserved, otherwise new ids will be assigned through xstream.
 */
public void dumpDatabaseToXml(final Writer writer, final boolean includeHistory, final boolean preserveIds)
{
  final TransactionTemplate tx = new TransactionTemplate(new HibernateTransactionManager(hibernate.getSessionFactory()));
  tx.execute(new TransactionCallback() {
    public Object doInTransaction(final TransactionStatus status)
    {
      hibernate.execute(new HibernateCallback() {
        public Object doInHibernate(final Session session) throws HibernateException
        {
          writeObjects(writer, includeHistory, session, preserveIds);
          status.setRollbackOnly();
          return null;
        }
      });
      return null;
    }
  });
}
 
Example #13
Source File: JtaTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);
	willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly();

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				status.setRollbackOnly();
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #14
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception {
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).begin();
	verify(tm).commit();
	verify(tm).resume(tx);
}
 
Example #15
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithIsolationLevel() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION);

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown InvalidIsolationLevelException");
	}
	catch (InvalidIsolationLevelException ex) {
		// expected
	}
}
 
Example #16
Source File: DatabaseMasterSelectorImpl.java    From EasyTransaction with Apache License 2.0 6 votes vote down vote up
private void initInstanceIdAndRecord() {
    TransactionTemplate transTemplate = new TransactionTemplate(transManager);
 transTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            
            Integer maxInstanceId = jdbcTemplate.queryForObject(GET_MAX_INSTANCE_ID, Integer.class, new Object[] {applicationName});
            instanceId = maxInstanceId + 1;
            int update = jdbcTemplate.update(INSERT_INSTANCE_CONTROL_LINE, applicationName,instanceId,instanceName);
            if(update != 1) {
                throw new RuntimeException("insert instance record failed! instanceId:" + maxInstanceId + " updated:" + update);
            }
            return null;
        }
    });
}
 
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: JtaTransactionManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception {
	TransactionManager tm = mock(TransactionManager.class);
	Transaction tx = mock(Transaction.class);
	given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE);
	given(tm.suspend()).willReturn(tx);

	JtaTransactionManager ptm = newJtaTransactionManager(tm);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
		}
	});
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());

	verify(tm).begin();
	verify(tm).commit();
	verify(tm).resume(tx);
}
 
Example #19
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithPropagationSupports() throws Exception {
	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
	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());
			assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example #20
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnCommitAndRollbackOnCommitFailure() throws Exception {
	willThrow(new SQLException("Cannot commit")).given(con).commit();

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

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	verify(con).rollback();
	verify(con).close();
}
 
Example #21
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testTransactionWithExceptionOnRollback() throws Exception {
	given(con.getAutoCommit()).willReturn(true);
	willThrow(new SQLException("Cannot rollback")).given(con).rollback();

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

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).rollback();
	ordered.verify(con).setAutoCommit(true);
	verify(con).close();
}
 
Example #22
Source File: MultithreadedDaoTestNgITCaseNew.java    From olat with Apache License 2.0 6 votes vote down vote up
@Test(threadPoolSize = 2, invocationCount = 2)
public void testSubscriptionUpdate() {

    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {

            Subscription subscription = daoSubscription.findAll().get(0);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Date date = new Date();
            System.out.println("Thread " + Thread.currentThread().getId() + " date:" + date.toString());
            subscription.setLastNotifiedDate(date);
            daoSubscription.update(subscription);

        }
    });

}
 
Example #23
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willThrow(new SystemException("system exception"));

	try {
		JtaTransactionManager ptm = newJtaTransactionManager(ut);
		TransactionTemplate tt = new TransactionTemplate(ptm);
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				// something transactional
			}
		});
		fail("Should have thrown TransactionSystemException");
	}
	catch (TransactionSystemException ex) {
		// expected
	}
}
 
Example #24
Source File: JtaTransactionManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception {
	UserTransaction ut = mock(UserTransaction.class);
	given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE);

	JtaTransactionManager ptm = newJtaTransactionManager(ut);
	TransactionTemplate tt = new TransactionTemplate(ptm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
			}
		});
		fail("Should have thrown TransactionSuspensionNotSupportedException");
	}
	catch (TransactionSuspensionNotSupportedException ex) {
		// expected
	}
	assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
}
 
Example #25
Source File: NotificationConcurrencyPublishEventNGTest.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) {

            List<Subscriber> subscribers = notificationTestDataGenerator.generateSubscribers(NUMBER_OF_SUBSCRIBERS);
            publisher = notificationTestDataGenerator.generatePublishers(NUMBER_OF_PUBLISHERS).get(0);
            notificationTestDataGenerator.generateSubscriptionsForListSubscribersAndOnePublisher(subscribers, publisher);
            creatorIdentity = notificationTestDataGenerator.generateIdentities(NUMBER_OF_CREATOR_IDENTITIES).get(0);
            assertEquals(NUMBER_OF_SUBSCRIBERS, notificationServiceImpl.getAllSubscriberKeys().size());
            // setup publishing - to execute to be sure that before second publishing which is already measured also UPDATE to OBSOLETE happens
            notificationServiceImpl.publishEvent(getPublishEventTO());
            System.out.println("setup finished");

        }
    });
}
 
Example #26
Source File: MemberDataSourceConfig.java    From EasyReport with Apache License 2.0 5 votes vote down vote up
@Primary
@Bean(name = "memberTransactionTemplate")
public TransactionTemplate transactionTemplate(@Qualifier("memberTransactionManager") final
DataSourceTransactionManager transactionManager)
    throws Exception {
    return this.createTransactionTemplate(transactionManager);
}
 
Example #27
Source File: DataSourceTransactionManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testTransactionRollbackOnly() throws Exception {
	tm.setTransactionSynchronization(DataSourceTransactionManager.SYNCHRONIZATION_NEVER);
	TransactionTemplate tt = new TransactionTemplate(tm);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());

	ConnectionHolder conHolder = new ConnectionHolder(con);
	conHolder.setTransactionActive(true);
	TransactionSynchronizationManager.bindResource(ds, conHolder);
	final RuntimeException ex = new RuntimeException("Application exception");
	try {
		tt.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
				assertTrue("Has thread connection", TransactionSynchronizationManager.hasResource(ds));
				assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
				assertTrue("Is existing transaction", !status.isNewTransaction());
				throw ex;
			}
		});
		fail("Should have thrown RuntimeException");
	}
	catch (RuntimeException ex2) {
		// expected
		assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
		assertEquals("Correct exception thrown", ex, ex2);
	}
	finally {
		TransactionSynchronizationManager.unbindResource(ds);
	}

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
}
 
Example #28
Source File: GetNewsPerformance.java    From olat with Apache License 2.0 5 votes vote down vote up
private void generateEvents(final Publisher publisher, final int counter) {
    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            notificationServiceImpl.publishEvent(getPublishEventTO(publisher, counter));
        }
    });
}
 
Example #29
Source File: DataSourceTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionWithIsolationAndReadOnly() throws Exception {
	given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED);
	given(con.getAutoCommit()).willReturn(true);

	TransactionTemplate tt = new TransactionTemplate(tm);
	tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
	tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
	tt.setReadOnly(true);
	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	tt.execute(new TransactionCallbackWithoutResult() {
		@Override
		protected void doInTransactionWithoutResult(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
			assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
			// something transactional
		}
	});

	assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
	InOrder ordered = inOrder(con);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
	ordered.verify(con).setAutoCommit(false);
	ordered.verify(con).commit();
	ordered.verify(con).setAutoCommit(true);
	ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
	verify(con).close();
}
 
Example #30
Source File: ConferenceTest.java    From spring4-sandbox with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeTestCase() {
	log.debug("==================before test case=========================");
	user = userRepository.save(new User("hantsy"));
	log.debug("user id @" + user.getId());
	SecurityUtils.user = user;
	conferenceRepository.save(newConference());

	transactionTemplate = new TransactionTemplate(transactionManager);
}