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:eu.databata.Propagator.java

public void setTransactionManager(final PlatformTransactionManager transactionManager) {
    Validate.notNull(transactionManager);
    this.transactionTemplate = new TransactionTemplate(transactionManager);
    this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}

From source file:com.jnj.b2b.test.orders.B2BAcceleratorTestOrderData.java

protected String placeOrderAndApproveByB2BApprover(final String userID, final String purchaseOrderNumber) {
    LOG.debug(String.format(// w  w w  . j a  v a2s .  co  m
            "******************Starting Attempt to setup and create order for PONumber: %s for " + "%s ",
            purchaseOrderNumber, userID));

    final TransactionTemplate template = new TransactionTemplate(getTransactionManager());
    template.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED);
    return template.execute(new TransactionCallback<String>() {
        @Override
        public String doInTransaction(final TransactionStatus status) {
            String orderCode = null;
            final Map<String, Long> products = new HashMap<String, Long>();
            products.put(PRODUCT_C, Long.valueOf(5));
            final OrderData orderData = placeOrder(userID, products, createUsAddressData(), purchaseOrderNumber,
                    Jnjb2bTestConstants.STANDARD_COSTCENTER, null);

            orderCode = orderData == null ? null : orderData.getCode();

            if (orderCode != null) {
                b2bApproverApproveThisOrder(orderCode);
            }
            return orderCode;
        }
    });
}

From source file:com.octanner.test.orders.B2BAcceleratorTestOrderData.java

protected String placeOrderAndApproveByB2BApprover(final String userID, final String purchaseOrderNumber) {
    LOG.debug(String.format(/*w  w  w .j ava 2 s  . c om*/
            "******************Starting Attempt to setup and create order for PONumber: %s for " + "%s ",
            purchaseOrderNumber, userID));

    final TransactionTemplate template = new TransactionTemplate(getTransactionManager());
    template.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED);
    return template.execute(new TransactionCallback<String>() {
        @Override
        public String doInTransaction(final TransactionStatus status) {
            String orderCode = null;
            final Map<String, Long> products = new HashMap<String, Long>();
            products.put(PRODUCT_C, Long.valueOf(5));
            final OrderData orderData = placeOrder(userID, products, createUsAddressData(), purchaseOrderNumber,
                    OctannerTestConstants.STANDARD_COSTCENTER, null);

            orderCode = orderData == null ? null : orderData.getCode();

            if (orderCode != null) {
                b2bApproverApproveThisOrder(orderCode);
            }
            return orderCode;
        }
    });
}

From source file:database.DataLoader.java

private void moveBranches() throws SQLException, ClassNotFoundException, Exception {
    try {//from  www.  j  a  va  2 s  .  c  o m
        final String tableName = BRANCH;
        final ResultSet branchSet = getFromOldBase(getSelectAll(tableName));
        while (branchSet.next()) {
            TransactionTemplate temp = new TransactionTemplate(transactionManager);
            temp.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus ts) {
                    Long oldId = 0L;
                    try {
                        oldId = branchSet.getLong("id");
                        String name = branchSet.getString("name");
                        String letter = branchSet.getString("letter");
                        boolean canUseFreeAuthors = branchSet.getBoolean("can_use_free_authors");
                        Branch branch = new Branch();
                        branch.setAbbrevation(letter);
                        branch.setFreeAuthors(canUseFreeAuthors);
                        branch.setName(name);
                        saveObjectAndLink(branch, oldId, tableName);
                    } catch (Exception e) {
                        ts.setRollbackOnly();
                        String message = "branch: " + oldId + " " + StringAdapter.getStackExeption(e);
                        addErrorMessage(message);
                    }
                }
            });

        }
    } catch (Throwable th) {
        log.warn("moveBranches " + StringAdapter.getStackExeption(th));
    }
}

From source file:org.tibetjungle.demo.service.DataSourcePopulator.java

public void setPlatformTransactionManager(PlatformTransactionManager platformTransactionManager) {
    this.tt = new TransactionTemplate(platformTransactionManager);
}

From source file:database.DataLoader.java

private void moveOrderReadyFiles() throws Exception {
    ResultSet set = getOrderReadyFilesFromOldBase();
    while (set.next()) {
        initFtpClient();//  w  w  w.j a v a2s  . c o m
        try {
            final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
            transactionTemplate.execute(new OrderReadyFileTransactionCallback(set));
        } finally {
            logoutFtpClient();
        }
    }
}

From source file:ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.java

private void processReindexing() {
    if (System.currentTimeMillis() < myNextReindexPass) {
        return;//from  w ww. ja va  2  s. com
    }

    TransactionTemplate tt = new TransactionTemplate(myTransactionMgr);
    tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus theArg0) {
            int maxResult = 1000;
            Page<TermConcept> resources = myConceptDao
                    .findResourcesRequiringReindexing(new PageRequest(0, maxResult));
            if (resources.hasContent() == false) {
                myNextReindexPass = System.currentTimeMillis() + DateUtils.MILLIS_PER_MINUTE;
                return;
            }

            ourLog.info("Indexing {} / {} concepts", resources.getContent().size(),
                    resources.getTotalElements());

            int count = 0;
            StopWatch stopwatch = new StopWatch();

            for (TermConcept resourceTable : resources) {
                saveConcept(resourceTable);
                count++;
            }

            ourLog.info("Indexed {} / {} concepts in {}ms - Avg {}ms / resource",
                    new Object[] { count, resources.getContent().size(), stopwatch.getMillis(),
                            stopwatch.getMillisPerOperation(count) });
        }
    });

}

From source file:org.openvpms.archetype.rules.finance.account.CustomerAccountRules.java

/**
 * Reverses an act.// www  .j  a  va2  s.  c  o m
 * <p/>
 * If the act to be reversed is an invoice, charge items and medication acts will be unlinked from patient history.
 * Reminders and investigations will be retained.
 *
 * @param act       the act to reverse
 * @param startTime the start time of the reversal
 * @param notes     notes indicating the reason for the reversal, to set the 'notes' node if the act has one.
 *                  May be {@code null}
 * @param reference the reference. If {@code null}, the act identifier will be used
 * @param hide      if {@code true}, hide the reversal iff the act being reversed isn't already hidden
 * @return the reversal of {@code act}
 * @throws ArchetypeServiceException for any archetype service error
 */
public FinancialAct reverse(final FinancialAct act, Date startTime, String notes, String reference,
        boolean hide) {
    final ActBean original = new ActBean(act, service);
    if (!original.getValues("reversal").isEmpty()) {
        throw new IllegalStateException("Act=" + act.getId() + " has already been reversed");
    }
    IMObjectCopier copier = new IMObjectCopier(new CustomerActReversalHandler(act));
    final List<IMObject> objects = copier.apply(act);
    FinancialAct reversal = (FinancialAct) objects.get(0);
    ActBean bean = new ActBean(reversal, service);
    bean.setValue("reference", !StringUtils.isEmpty(reference) ? reference : act.getId());
    bean.setValue("notes", notes);
    reversal.setStatus(FinancialActStatus.POSTED);
    reversal.setActivityStartTime(startTime);

    original.addNodeRelationship("reversal", reversal);

    if (hide && !original.getBoolean("hide")) {
        bean.setValue("hide", hide);
        original.setValue("hide", hide);
    }

    // This smells. The original acts needs to be saved without using the rule based archetype service, to avoid
    // triggering rules. The other acts need to be saved with rules enabled, in order to update the balance.
    // TODO
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            List<IMObject> noRules = new ArrayList<IMObject>();
            noRules.add(act);

            if (TypeHelper.isA(act, CustomerAccountArchetypes.INVOICE)) {
                removeInvoiceFromPatientHistory(act, noRules);
            }
            service.save(noRules);
            ruleService.save(objects);
        }
    });
    return reversal;
}

From source file:com._4dconcept.springframework.data.marklogic.datasource.DatabaseConnectorJtaTransactionTest.java

private void doTestJtaTransactionCommitWithNewTransactionWithinEmptyTransaction(final boolean requiresNew,
        boolean notSupported) throws Exception {

    if (notSupported) {
        given(userTransaction.getStatus()).willReturn(Status.STATUS_ACTIVE, Status.STATUS_NO_TRANSACTION,
                Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
        given(transactionManager.suspend()).willReturn(transaction);
    } else {//from   www.j av a2s. c o m
        given(userTransaction.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION,
                Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
    }

    final ContentSource contentSource = mock(ContentSource.class);
    final Session session1 = mock(Session.class);
    final Session session2 = mock(Session.class);
    given(contentSource.newSession()).willReturn(session1, session2);

    final JtaTransactionManager ptm = new JtaTransactionManager(userTransaction, transactionManager);
    TransactionTemplate tt = new TransactionTemplate(ptm);
    tt.setPropagationBehavior(notSupported ? TransactionDefinition.PROPAGATION_NOT_SUPPORTED
            : TransactionDefinition.PROPAGATION_SUPPORTS);

    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
            assertSame(session1, ContentSourceUtils.getSession(contentSource));

            TransactionTemplate tt2 = new TransactionTemplate(ptm);
            tt2.setPropagationBehavior(requiresNew ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                    : TransactionDefinition.PROPAGATION_REQUIRED);
            tt2.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
                    assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
                    assertTrue(TransactionSynchronizationManager.isActualTransactionActive());
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                    assertSame(session2, ContentSourceUtils.getSession(contentSource));
                }
            });

            assertTrue(TransactionSynchronizationManager.isSynchronizationActive());
            assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly());
            assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
            assertSame(session1, ContentSourceUtils.getSession(contentSource));
        }
    });
    assertFalse(TransactionSynchronizationManager.isSynchronizationActive());
    verify(userTransaction).begin();
    verify(userTransaction).commit();
    if (notSupported) {
        verify(transactionManager).resume(transaction);
    }
    verify(session2).close();
    verify(session1).close();
}