Java Code Examples for org.springframework.transaction.support.TransactionTemplate#setTransactionManager()

The following examples show how to use org.springframework.transaction.support.TransactionTemplate#setTransactionManager() . 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: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testTransactionCommitWithAutoDetectedDataSourceAndNoConnection() throws SQLException {
	final DataSource ds = mock(DataSource.class);
	final JdoDialect dialect = mock(JdoDialect.class);

	given(pmf.getConnectionFactory()).willReturn(ds);
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);
	TransactionTemplate tt = new TransactionTemplate();
	given(dialect.getJdbcConnection(pm, false)).willReturn(null);

	JdoTransactionManager tm = new JdoTransactionManager();
	tm.setPersistenceManagerFactory(pmf);
	tm.setJdoDialect(dialect);
	tm.afterPropertiesSet();
	tt.setTransactionManager(tm);
	final List l = new ArrayList();
	l.add("test");
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf));
			assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds));
			PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true).flush();
			return l;
		}
	});
	assertTrue("Correct result list", result == l);

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds));

	verify(pm).flush();
	verify(pm).close();
	verify(dialect).beginTransaction(tx, tt);
	verify(dialect).cleanupTransaction(null);
	verify(tx).commit();
}
 
Example 2
Source File: IdempotentConsumerInTransactionTest.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    SimpleRegistry registry = new SimpleRegistry();
    auditDataSource = EmbeddedDataSourceFactory.getDataSource("sql/schema.sql");
    registry.put("auditDataSource", auditDataSource);

    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(auditDataSource);
    registry.put("transactionManager", transactionManager);

    SpringTransactionPolicy propagationRequired = new SpringTransactionPolicy();
    propagationRequired.setTransactionManager(transactionManager);
    propagationRequired.setPropagationBehaviorName("PROPAGATION_REQUIRED");
    registry.put("PROPAGATION_REQUIRED", propagationRequired);

    auditLogDao = new AuditLogDao(auditDataSource);

    TransactionTemplate transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(transactionManager);
    transactionTemplate.setPropagationBehaviorName("PROPAGATION_REQUIRES_NEW");

    idempotentRepository = new JdbcMessageIdRepository(auditDataSource, transactionTemplate, "ws");

    CamelContext camelContext = new DefaultCamelContext(registry);
    SqlComponent sqlComponent = new SqlComponent();
    sqlComponent.setDataSource(auditDataSource);
    camelContext.addComponent("sql", sqlComponent);
    return camelContext;
}
 
Example 3
Source File: BootstrapTestUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void bootstrap(WebApplicationContext context) {
  ContextRefreshedEvent event = mock(ContextRefreshedEvent.class);
  when(event.getApplicationContext()).thenReturn(context);

  TransactionTemplate template = new TransactionTemplate();
  template.setTransactionManager(transactionManager);
  try {
    runAsSystem(() -> initialize(template, event));
  } catch (Exception unexpected) {
    LOG.error("Error bootstrapping tests!", unexpected);
    throw new RuntimeException(unexpected);
  }
}
 
Example 4
Source File: JPAIdempotentConsumerIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testJPAIdempotentConsumer() throws Exception {
    final TransactionTemplate transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new JtaTransactionManager(userTransaction));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

    final JpaMessageIdRepository messageIdRepository = new JpaMessageIdRepository(entityManagerFactory, transactionTemplate, "myProcessorName");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .idempotentConsumer(simple("${header.messageId}"), messageIdRepository)
            .to("mock:result");
        }
    });

    camelctx.start();
    try {
        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mockEndpoint.expectedMessageCount(1);

        // Send 5 messages with the same messageId header. Only 1 should be forwarded to the mock:result endpoint
        ProducerTemplate template = camelctx.createProducerTemplate();
        for (int i = 0; i < 5; i++) {
            template.requestBodyAndHeader("direct:start", null, "messageId", "12345");
        }

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 5
Source File: JdbcAuditor.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public void logEvent(final AuditEvent event) {
	TransactionTemplate transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(getDataSource()));
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    	
    	@Override
           protected void doInTransactionWithoutResult(TransactionStatus status) {
       	    int id = getNextEventId();

       		Object[] eventData = new Object[8];
       	    eventData[0] = id;
       		eventData[1] = event.getDate();
       		eventData[2] = event.getUsername();
       		eventData[3] = event.getAction();
       		eventData[4] = event.getSession();
       		eventData[5] = event.getIp();
       		eventData[6] = event.getLevel();
       		eventData[7] = event.getErrorMessage();
       		
       	    getJdbcTemplate().update(INSERT_EVENT_SQL, eventData);
       	    
       	    Map<String, Object> context = event.getContext();
       	    for (String name : context.keySet()) {
           		Object[] contextData = new Object[3];
           		contextData[0] = id;
           		contextData[1] = name;
           		contextData[2] = context.get(name);

       	    	getJdbcTemplate().update(INSERT_CONTEXT_SQL, contextData);
       	    }
           }
           
    });
}
 
Example 6
Source File: SpringContextConfig.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Bean("template")
TransactionTemplate transactionTemplate(){
    TransactionTemplate template = new TransactionTemplate();
    template.setTransactionManager(transactionManager);
    return template;
}
 
Example 7
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransactionCommitWithDataSource() throws SQLException {
	final DataSource ds = mock(DataSource.class);
	JdoDialect dialect = mock(JdoDialect.class);
	final Connection con = mock(Connection.class);
	ConnectionHandle conHandle = new SimpleConnectionHandle(con);

	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);
	TransactionTemplate tt = new TransactionTemplate();
	given(dialect.getJdbcConnection(pm, false)).willReturn(conHandle);

	JdoTransactionManager tm = new JdoTransactionManager();
	tm.setPersistenceManagerFactory(pmf);
	tm.setDataSource(ds);
	tm.setJdoDialect(dialect);
	tt.setTransactionManager(tm);
	final List l = new ArrayList();
	l.add("test");
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf));
			assertTrue("Has thread con", TransactionSynchronizationManager.hasResource(ds));
			PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
			return l;
		}
	});
	assertTrue("Correct result list", result == l);

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds));

	verify(pm).close();
	verify(dialect).beginTransaction(tx, tt);
	verify(dialect).releaseJdbcConnection(conHandle, pm);
	verify(dialect).cleanupTransaction(null);
	verify(tx).commit();
}
 
Example 8
Source File: JdoTransactionManagerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransactionCommitWithAutoDetectedDataSource() throws SQLException {
	final DataSource ds = mock(DataSource.class);
	JdoDialect dialect = mock(JdoDialect.class);
	final Connection con = mock(Connection.class);
	ConnectionHandle conHandle = new SimpleConnectionHandle(con);

	given(pmf.getConnectionFactory()).willReturn(ds);
	given(pmf.getPersistenceManager()).willReturn(pm);
	given(pm.currentTransaction()).willReturn(tx);
	TransactionTemplate tt = new TransactionTemplate();
	given(dialect.getJdbcConnection(pm, false)).willReturn(conHandle);

	JdoTransactionManager tm = new JdoTransactionManager();
	tm.setPersistenceManagerFactory(pmf);
	tm.setJdoDialect(dialect);
	tm.afterPropertiesSet();
	tt.setTransactionManager(tm);
	final List l = new ArrayList();
	l.add("test");
	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf));
			assertTrue("Has thread con", TransactionSynchronizationManager.hasResource(ds));
			PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true);
			return l;
		}
	});
	assertTrue("Correct result list", result == l);

	assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf));
	assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds));

	verify(pm).close();
	verify(dialect).beginTransaction(tx, tt);
	verify(dialect).releaseJdbcConnection(conHandle, pm);
	verify(dialect).cleanupTransaction(null);
	verify(tx).commit();
}
 
Example 9
Source File: ExecutionAssignerServiceTest.java    From score with Apache License 2.0 4 votes vote down vote up
@Bean
public TransactionTemplate transactionTemplate() {
    TransactionTemplate bean = new TransactionTemplate();
    bean.setTransactionManager(Mockito.mock(PlatformTransactionManager.class));
    return bean;
}
 
Example 10
Source File: PlatformBootstrapper.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void bootstrap(ContextRefreshedEvent event) {
  TransactionTemplate transactionTemplate = new TransactionTemplate();
  transactionTemplate.setTransactionManager(transactionManager);
  transactionTemplate.execute(
      (action) -> {
        try {
          RunAsSystemAspect.runAsSystem(
              () -> {
                LOG.info("Bootstrapping registries ...");
                bootstrappingEventPublisher.publishBootstrappingStartedEvent();

                LOG.trace("Populating data source with ACL tables ...");
                dataSourceAclTablesPopulator.populate();
                LOG.debug("Populated data source with ACL tables");

                LOG.trace("Bootstrapping transaction exception translators ...");
                transactionExceptionTranslatorRegistrar.register(event.getApplicationContext());
                LOG.debug("Bootstrapped transaction exception translators");

                LOG.trace("Registering repository collections ...");
                repoCollectionBootstrapper.bootstrap(event, POSTGRESQL);
                LOG.trace("Registered repository collections");

                LOG.trace("Registering system entity meta data ...");
                systemEntityTypeRegistrar.register(event);
                LOG.trace("Registered system entity meta data");

                LOG.trace("Registering system packages ...");
                systemPackageRegistrar.register(event);
                LOG.trace("Registered system packages");

                LOG.trace("Registering entity factories ...");
                entityFactoryRegistrar.register(event);
                LOG.trace("Registered entity factories");

                LOG.trace("Registering entity factories ...");
                systemRepositoryDecoratorFactoryRegistrar.register(event);
                LOG.trace("Registered entity factories");
                LOG.debug("Bootstrapped registries");

                LOG.trace("Registering dynamic decorator factories ...");
                dynamicRepositoryDecoratorFactoryRegistrar.register(
                    event.getApplicationContext());
                LOG.trace("Registered dynamic repository decorator factories");

                LOG.trace("Bootstrapping system entity types ...");
                systemEntityTypeBootstrapper.bootstrap(event);
                LOG.debug("Bootstrapped system entity types");

                LOG.trace("Registering job factories ...");
                jobFactoryRegistrar.register(event);
                LOG.trace("Registered job factories");

                LOG.trace("Populating database with I18N strings ...");
                i18nPopulator.populateL10nStrings();
                LOG.trace("Populated database with I18N strings");

                LOG.trace("Populating database with Dynamic Decorator Configurations ...");
                dynamicDecoratorPopulator.populate();
                LOG.trace("Populated database with Dynamic Decorators Configurations");

                LOG.trace("Populating the entity type registry ...");
                entityTypeRegistryPopulator.populate();
                LOG.trace("Populated the entity type registry");

                bootstrappingEventPublisher.publishBootstrappingFinishedEvent();
              });
        } catch (Exception unexpected) {
          LOG.error("Error bootstrapping tests!", unexpected);
          throw new RuntimeException(unexpected);
        }
        return (Void) null;
      });
}