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:nl.clockwork.mule.ebms.dao.AbstractEbMSDAO.java

public AbstractEbMSDAO(PlatformTransactionManager transactionManager, javax.sql.DataSource dataSource) {
    transactionTemplate = new TransactionTemplate(transactionManager);
    jdbcTemplate = new JdbcTemplate(dataSource);
    simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public List<User> bulkDeleteUser(UserBulkDeleteRequest bulkDeleteForm, BindingResult result) {
    List<User> users = new ArrayList<>();
    for (long id : bulkDeleteForm.getIds()) {
        final UserDeleteRequest deleteRequest = new UserDeleteRequest.Builder().id(id).build();

        final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
        r.setMessageCodesResolver(messageCodesResolver);

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
        User user = null;/*from   w w  w  .ja  v a  2s. com*/
        try {
            user = transactionTemplate.execute(new TransactionCallback<User>() {
                public User doInTransaction(TransactionStatus status) {
                    try {
                        return deleteUser(deleteRequest, r);
                    } catch (BindException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            users.add(user);
        } catch (Exception e) {
            logger.debug("Errors: {}", r);
            result.addAllErrors(r);
        }
    }
    return users;
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceDescriptorTestCase.java

/**
 * Verifies that an archetype descriptor can be replaced with one of
 * the same name in a transaction.//  w ww. j  av a 2 s  . com
 */
@Test
public void testReplace() {
    String name = "archetype.dummy" + System.currentTimeMillis() + ".1.0";
    final ArchetypeDescriptor desc1 = createArchetypeDescriptor(name, getClass().getName(), "archetype.dummy",
            true);
    NodeDescriptor ndesc1 = createNodeDescriptor("name", "/name", "java.lang.String", 1, 1);
    desc1.addNodeDescriptor(ndesc1);
    save(desc1);

    final ArchetypeDescriptor desc2 = createArchetypeDescriptor(name, getClass().getName(), "archetype.dummy",
            true);
    NodeDescriptor ndesc2 = createNodeDescriptor("name2", "/name", "java.lang.String", 1, 1);
    // try and save desc2. Should fail.
    try {
        save(desc2);
        fail("Expected save with non-unique name to fail");
    } catch (Exception expected) {
    }

    desc2.addNodeDescriptor(ndesc2);

    // now remove desc1, and save desc2 in a transaction
    PlatformTransactionManager txnManager = (PlatformTransactionManager) applicationContext
            .getBean("txnManager");
    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            remove(desc1);
            save(desc2);
            return null;
        }
    });

    // verify the original descriptor can't be retrieved
    assertNull(get(desc1));

    ArchetypeDescriptor reloaded = get(desc2);
    assertNotNull(reloaded.getNodeDescriptor("name2"));
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedProjectsByApplication(String applicationName, int page, int size) {
    String application = applicationName.replace(".", " ");
    ObjectNode result = Json.newObject();

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    Integer appID = getApplicationIDByName(applicationName);
    if (appID != 0) {

        final int applicationID = appID;

        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_BY_APP_ID, applicationID,
                        (page - 1) * size, size);

                try {
                    count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
                } catch (EmptyResultDataAccessException e) {
                    Logger.error("Exception = " + e.getMessage());
                }/*w ww .  j a  va2  s. c o  m*/
                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 = DateFormat.format(created.toString());
                    }
                    Object modified = row.get("modified_time");
                    if (modified != null) {
                        flow.modified = DateFormat.format(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;
    }

    result = Json.newObject();
    result.put("count", 0);
    result.put("page", page);
    result.put("itemsPerPage", size);
    result.put("totalPages", 0);
    result.set("flows", Json.toJson(""));
    return result;
}

From source file:ro.nextreports.server.web.NextServerApplication.java

private SchedulerJob[] getSchedulerJobs() {
    PlatformTransactionManager transactionManager = (PlatformTransactionManager) getSpringBean(
            "transactionManager");
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    SchedulerJob[] schedulerJobs = transactionTemplate.execute(new TransactionCallback<SchedulerJob[]>() {

        public SchedulerJob[] doInTransaction(TransactionStatus transactionStatus) {
            StorageDao storageDao = (StorageDao) getSpringBean("storageDao");
            try {
                Entity[] entities = storageDao.getEntitiesByClassName(StorageConstants.SCHEDULER_ROOT,
                        SchedulerJob.class.getName());
                SchedulerJob[] schedulerJobs = new SchedulerJob[entities.length];
                System.arraycopy(entities, 0, schedulerJobs, 0, entities.length);

                return schedulerJobs;
            } catch (Exception e) {
                // TODO
                e.printStackTrace();/*  w ww.  j a  v  a 2  s .  com*/
                transactionStatus.setRollbackOnly();
                return null;
            }
        }

    });

    return schedulerJobs;
}

From source file:org.openvpms.archetype.rules.finance.invoice.ChargeItemDocumentLinkerTestCase.java

/**
 * Saves the changes in a transaction.// w w w.j  av a2s. c om
 *
 * @param changes the changes
 */
private void saveInTxn(final PatientHistoryChanges changes) {
    PlatformTransactionManager mgr = (PlatformTransactionManager) applicationContext.getBean("txnManager");
    TransactionTemplate template = new TransactionTemplate(mgr);
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            changes.save();
            return null;
        }
    });
}

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

@Test(expected = TransactionSystemException.class)
public void testTransactionRollbackError() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI rollbackUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.ROLLBACK);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*from www. ja  va2s  . com*/
    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(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(rollbackUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform())
            .thenThrow(new FcrepoOperationFailedException(rollbackUri, 400, "Bad Request"));

    DefaultTransactionStatus status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);

    final FcrepoTransactionObject txObj = (FcrepoTransactionObject) status.getTransaction();
    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

    status = (DefaultTransactionStatus) txMgr.getTransaction(txDef);
    txMgr.rollback(status);
}

From source file:com.exxonmobile.ace.hybris.test.orders.B2BAcceleratorTestOrderData.java

protected String placeOrderAndApproveByB2BApprover(final String userID, final String purchaseOrderNumber) {
    LOG.debug(String.format(/*from  w  w  w  .  ja  va  2 s.c  o 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,
                    ExxonmobilTestConstants.STANDARD_COSTCENTER, null);

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

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

From source file:de.hybris.platform.yb2bacceleratortest.orders.B2BAcceleratorTestOrderData.java

protected String placeOrderAndApproveByB2BApprover(final String userID, final String purchaseOrderNumber) {
    LOG.debug(String.format(/*  w ww  .  j  ava  2s .  com*/
            "******************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,
                    YB2BAcceleratorTestConstants.STANDARD_COSTCENTER, null);

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

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

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

protected String placeOrderAndApproveByB2BApprover(final String userID, final String purchaseOrderNumber) {
    LOG.debug(String.format(//from   ww w  .  ja  v a 2  s . c o  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,
                    MitreTestConstants.STANDARD_COSTCENTER, null);

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

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