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.openvpms.archetype.rules.finance.till.TillRules.java

/**
 * Clears a till for an IN_PROGRESS balance.
 *
 * @param balance the current till balance
 * @param account the account to deposit to
 * @throws TillRuleException if the balance doesn't have a till
 *///from   w  ww  .  j  a va2  s .  com
public void clearTill(final FinancialAct balance, final Party account) {
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            clearInProgressTill(balance, account);
        }
    });
}

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

/**
 * Verifies that stock is updated correctly if an item is saved twice in the one transaction, but the first
 * save is incomplete.// w  w  w  .  j  a  va  2  s.  c o m
 */
@Test
public void testPartialSaveInTxn() {
    final List<FinancialAct> acts = createInvoice();
    final FinancialAct invoice = acts.get(0);
    final 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(item);
            save(item);
            save(invoice);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

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

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test(expected = CannotCreateTransactionException.class)
public void testTransactionBeginError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*from w w  w.j  a v a  2s  . co  m*/
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockPostBuilder.perform()).thenThrow(new FcrepoOperationFailedException(beginUri, 400, "Bad Request"));

    txMgr.getTransaction(txDef);
}

From source file:com.hybris.datahub.outbound.adapter.TmallAdapter.java

private List<ErrorData> processItems(final TargetSystemPublication targetSystemPublication,
        final TargetItemMetadata targetItemMetadata) {
    final List<ErrorData> errors = Lists.newArrayList();
    final TransactionTemplate template = new TransactionTemplate(transactionManager);
    Pair<Integer, Long> elementsAndLastId = new ImmutablePair<>(0, 0L);
    do {//w ww . j  a va  2  s . c om
        final Long lastProcessedId = elementsAndLastId.getRight();
        elementsAndLastId = template.execute(status -> {
            final List<? extends TargetItem> items = getItems(targetItemMetadata, targetSystemPublication,
                    makePageable(lastProcessedId));
            final Pair<Integer, Long> pageElementsAndLastId;
            if (!CollectionUtils.isEmpty(items)) {
                for (final TargetItem targetItem : items) {
                    errors.addAll(doPublish(targetItem, targetSystemPublication));
                }
                pageElementsAndLastId = new ImmutablePair<>(items.size(),
                        getLastProcessedId(lastProcessedId, items));
            } else {
                pageElementsAndLastId = new ImmutablePair<>(0, 0L);
            }
            return pageElementsAndLastId;
        });
    } while (elementsAndLastId.getRight() > 0);
    return errors;
}

From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.java

private void markResourceAsIndexingFailed(final long theId) {
    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback<Void>() {
        @Override/*w ww.ja v a  2s .c om*/
        public Void doInTransaction(TransactionStatus theStatus) {
            ourLog.info("Marking resource with PID {} as indexing_failed", new Object[] { theId });
            Query q = myEntityManager
                    .createQuery("UPDATE ResourceTable t SET t.myIndexStatus = :status WHERE t.myId = :id");
            q.setParameter("status", INDEX_STATUS_INDEXING_FAILED);
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceTag t WHERE t.myResourceId = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamCoords t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamDate t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamNumber t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery(
                    "DELETE FROM ResourceIndexedSearchParamQuantity t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamString t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamToken t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamUri t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceLink t WHERE t.mySourceResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceLink t WHERE t.myTargetResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            return null;
        }
    });
}

From source file:org.openvpms.archetype.rules.finance.till.TillRules.java

/**
 * Clears a till for an UNCLEARED balance.
 * <p/>//from  w  w  w. ja v  a2 s .  c o m
 * If the cash float is different to the existing cash float for the till, an adjustment will be created.
 *
 * @param balance   the current till balance
 * @param cashFloat the amount remaining in the till
 * @param account   the account to deposit to
 * @throws TillRuleException if the balance doesn't have a till
 */
public void clearTill(final FinancialAct balance, final BigDecimal cashFloat, final Party account) {
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            clearUnclearedTill(balance, cashFloat, account);
        }
    });
}

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

@DELETE
@Path("/{sensorId}")
public Response deleteSensor(@PathParam("sensorId") Long sensorId) {
    final Sensor existingSensor = device.getSensorById(sensorId);

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override/*  w  w  w. j ava2s .  c  o  m*/
        public Object doInTransaction(TransactionStatus transactionStatus) {
            device.removeSensor(existingSensor);
            sensorRepository.delete(existingSensor);
            return null;
        }
    });

    return Response.ok().build();
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedProjects(int page, int size) {
    ObjectNode result;/*  www .  j  a va 2 s  .  c  om*/

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            ObjectNode resultNode = Json.newObject();
            long count = 0;
            List<Flow> pagedFlows = new ArrayList<Flow>();
            List<Map<String, Object>> rows = null;
            rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS, (page - 1) * size, size);

            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }
            for (Map row : rows) {
                Flow flow = new Flow();
                flow.id = (Long) row.get("flow_id");
                flow.level = (Integer) row.get("flow_level");
                flow.appId = (Integer) row.get("app_id");
                flow.group = (String) row.get("flow_group");
                flow.name = (String) row.get("flow_name");
                flow.path = (String) row.get("flow_path");
                flow.appCode = (String) row.get("app_code");
                if (StringUtils.isNotBlank(flow.path)) {
                    int index = flow.path.indexOf(":");
                    if (index != -1) {
                        flow.path = flow.path.substring(0, index);
                    }
                }
                Object created = row.get("created_time");
                if (created != null) {
                    flow.created = created.toString();
                }
                Object modified = row.get("modified_time");
                if (modified != null) {
                    flow.modified = row.get("modified_time").toString();
                }

                int jobCount = 0;

                if (flow.id != null && flow.id != 0) {
                    try {
                        jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID,
                                new Object[] { flow.appId, flow.id }, Integer.class);
                        flow.jobCount = jobCount;
                    } catch (EmptyResultDataAccessException e) {
                        Logger.error("Exception = " + e.getMessage());
                    }
                }
                pagedFlows.add(flow);
            }
            resultNode.set("flows", Json.toJson(pagedFlows));
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));

            return resultNode;
        }
    });
    return result;
}

From source file:org.fcrepo.camel.FcrepoTransactionManagerTest.java

@Test(expected = CannotCreateTransactionException.class)
public void testTransactionBeginNoLocationError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*from  w ww . j av a  2s.  c o  m*/
    TestUtils.setField(txMgr, "fcrepoClient", mockClient);

    final TransactionTemplate transactionTemplate = new TransactionTemplate(txMgr);
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRED);

    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();

    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201, emptyMap(), null));

    txMgr.getTransaction(txDef);
}