Example usage for org.springframework.transaction.support TransactionTemplate TransactionTemplate

List of usage examples for org.springframework.transaction.support TransactionTemplate TransactionTemplate

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionTemplate TransactionTemplate.

Prototype

public TransactionTemplate(PlatformTransactionManager transactionManager) 

Source Link

Document

Construct a new TransactionTemplate using the given transaction manager.

Usage

From source file:org.drools.container.spring.beans.persistence.VariablePersistenceStrategyTest.java

@Test
public void testTransactionsRollback() throws Exception {
    final List<?> list = new ArrayList<Object>();
    PlatformTransactionManager txManager = (PlatformTransactionManager) ctx.getBean("txManager");

    final Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, ctx.getBean("myEmf"));
    env.set(EnvironmentName.TRANSACTION_MANAGER, txManager);
    env.set(EnvironmentName.GLOBALS, new MapGlobalResolver());

    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, new ObjectMarshallingStrategy[] {
            new JPAPlaceholderResolverStrategy(env),
            new SerializablePlaceholderResolverStrategy(ClassObjectMarshallingStrategyAcceptor.DEFAULT) });

    final KnowledgeStoreService kstore = (KnowledgeStoreService) ctx.getBean("kstore1");
    final KnowledgeBase kbRollback = (KnowledgeBase) ctx.getBean("kbRollback");

    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
    final StatefulKnowledgeSession ksession = (StatefulKnowledgeSession) txTemplate
            .execute(new TransactionCallback() {

                public Object doInTransaction(TransactionStatus status) {
                    StatefulKnowledgeSession kNewSession = kstore.newStatefulKnowledgeSession(kbRollback, null,
                            env);//  ww w  . j  av  a  2 s  .  com
                    kNewSession.setGlobal("list", list);
                    kNewSession.insert(1);
                    kNewSession.insert(2);
                    return kNewSession;
                }
            });

    final int sessionId = ksession.getId();

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession.insert(3);
            status.setRollbackOnly();
            return null;
        }
    });

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession.fireAllRules();
            return null;
        }
    });

    assertEquals(2, list.size());

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession.insert(3);
            ksession.insert(4);
            return null;
        }
    });

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession.insert(5);
            ksession.insert(6);
            status.setRollbackOnly();
            return null;
        }
    });

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession.fireAllRules();
            return null;
        }
    });

    assertEquals(4, list.size());

    ksession.dispose();

    // now load the ksession
    final StatefulKnowledgeSession ksession2 = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId,
            kbRollback, null, env);

    txTemplate = new TransactionTemplate(txManager);
    txTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            ksession2.setGlobal("list", list);
            ksession2.insert(7);
            ksession2.insert(8);
            return null;
        }
    });

    txTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            ksession2.fireAllRules();
            return null;
        }
    });

    assertEquals(6, list.size());
}

From source file:py.una.pol.karaku.test.cucumber.DatabasePopulatorCucumberExecutionListener.java

/**
 * @param testContext//from  w  w  w.  j  av a 2 s .  c o  m
 * @param file
 * @param slsce
 */
private void executeSQL(TestContext testContext, String file, SingleLineSqlCommandExtractor slsce) {

    BufferedReader br;
    ClassPathResource cpr = getClassPathResource(file, testContext);
    br = _getBr(cpr);
    // File f = new File(scriptPath);
    // FileReader fr = new FileReader(file);

    final String[] commands = slsce.extractCommands(br);
    if (commands == null) {
        return;
    }
    final HibernateTransactionManager tm = getTransactionManager(testContext);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {

            for (String s : commands) {
                if (StringUtils.isInvalid(s)) {
                    continue;
                }

                SQLQuery sql = tm.getSessionFactory().getCurrentSession().createSQLQuery(s.trim());
                sql.executeUpdate();
            }

        }
    });

}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that stock is updated correctly if a charge is saved multiple times in a transaction.
 *//*from   ww  w.  j  av a2 s  . com*/
@Test
public void testMultipleSaveInTxn() {
    final List<FinancialAct> acts = createInvoice();
    FinancialAct item = acts.get(1);
    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity, false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(acts);
            save(acts);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    save(acts); // stock shouldn't change if resaved
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Test cleanup routine called after each test method.
 *
 * @throws  Exception  On errors.//w  w  w . ja  v  a2s  . c o m
 */
@AfterTransaction
public void tearDown() throws Exception {
    new TransactionTemplate(txManager).execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(final TransactionStatus status) {

            final ProjectConfig projectFromDb = configManager.find(ProjectConfig.class, testProject.getId());
            if (projectFromDb != null) {
                configManager.delete(projectFromDb);
            }
        }
    });
}

From source file:org.springextensions.neodatis.NeoDatisTransactionManagerTest.java

@Test
public void testWrongIsolationLevel() {
    final ODB odb = Mockito.mock(ODB.class);
    Mockito.when(odb.store(Mockito.isNull())).thenThrow(new RuntimeException());
    PlatformTransactionManager tm = new NeoDatisTransactionManager(odb);
    TransactionTemplate tmpl = new TransactionTemplate(tm);

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

    tmpl.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {//  w  ww  .  ja v a 2  s.co  m
        tmpl.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(odb));
                NeoDatisTemplate neoDatisTemplate = new NeoDatisTemplate(odb);
                neoDatisTemplate.store(null);
                transactionStatus.setRollbackOnly();
            }
        });
        Assert.fail("Should throw an exception.");
    } catch (InvalidIsolationLevelException e) {
        // is ok
    }

    Assert.assertFalse("Should not have a resource", TransactionSynchronizationManager.hasResource(odb));
    Assert.assertFalse("There should no active synchronizations",
            TransactionSynchronizationManager.isSynchronizationActive());

}

From source file:org.openremote.beehive.configuration.www.CommandsAPI.java

@PUT
@Path("/{commandId}")
public Response udpateCommand(@PathParam("commandId") Long commandId, final CommandDTOIn commandDTO) {
    final Command existingCommand = device.getCommandById(commandId);

    Command optionalCommandWithSameName = device.getCommandByName(commandDTO.getName());
    if (optionalCommandWithSameName != null
            && !optionalCommandWithSameName.getId().equals(existingCommand.getId())) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A command with the same name already exists")).build();
    }/*  www  .  java 2s .c om*/

    return Response.ok(new CommandDTOOut(
            new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Command>() {
                @Override
                public Command doInTransaction(TransactionStatus transactionStatus) {
                    // TODO: check for more optimal solution, e.g. go over existing attributes and update individually
                    // and add/delete as required
                    // -> currently delete and re-creates protocol / protocol_attr records

                    protocolRepository.delete(existingCommand.getProtocol());

                    populateCommandFromDTO(existingCommand, commandDTO);
                    commandRepository.save(existingCommand);
                    return existingCommand;
                }
            }))).build();
}

From source file:org.opennms.ng.dao.support.UpsertTemplate.java

/**
 * After creating the UpsertTemplate call this method to attempt the upsert.
 *///from  w ww .ja  v a 2  s  .  co m
public T execute() {
    TransactionTemplate template = new TransactionTemplate(m_transactionManager);
    template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return template.execute(new TransactionCallback<T>() {

        @Override
        public T doInTransaction(TransactionStatus status) {
            return doUpsert();
        }
    });

}

From source file:ca.uhn.fhir.jpa.dao.dstu3.FhirResourceDaoSubscriptionDstu3.java

@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public synchronized int pollForNewUndeliveredResources() {
    if (getConfig().isSubscriptionEnabled() == false) {
        return 0;
    }/*from  w w w  . j  a  va2  s .  c om*/
    ourLog.trace("Beginning pollForNewUndeliveredResources()");

    // SubscriptionCandidateResource

    Collection<Long> subscriptions = mySubscriptionTableDao
            .findSubscriptionsWhichNeedToBeChecked(SubscriptionStatusEnum.ACTIVE.getCode(), new Date());

    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    int retVal = 0;
    for (final Long nextSubscriptionTablePid : subscriptions) {
        retVal += txTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus theStatus) {
                SubscriptionTable nextSubscriptionTable = mySubscriptionTableDao
                        .findOne(nextSubscriptionTablePid);
                return pollForNewUndeliveredResources(nextSubscriptionTable);
            }
        });
    }

    return retVal;
}

From source file:org.cleverbus.test.AbstractDbTest.java

protected Message[] createAndSaveMessages(final int messageCount, final MessageProcessor initializer) {
    TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager);
    return tx.execute(new TransactionCallback<Message[]>() {
        @Override/*www  .ja v  a2  s .c  om*/
        public Message[] doInTransaction(TransactionStatus status) {
            Message[] messages = new Message[messageCount];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = createMessage(ExternalSystemTestEnum.CRM, ServiceTestEnum.CUSTOMER,
                        "testOperation", "test payload");

                try {
                    initializer.process(messages[i]);
                } catch (Exception exc) {
                    throw new RuntimeException(exc);
                }
                em.persist(messages[i]);
            }
            em.flush();
            return messages;
        }
    });
}

From source file:org.surfnet.cruncher.config.SpringConfiguration.java

@Bean
public TransactionTemplate transactionTemplate() {
    return new TransactionTemplate(transactionManager());
}