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.springextensions.db4o.Db4oTransactionManagerTest.java

@Test
public void testInvalidIsolation() throws Exception {
    final ExtObjectContainer container = mock(ExtObjectContainer.class);

    PlatformTransactionManager tm = new Db4oTransactionManager(container);
    TransactionTemplate tt = new TransactionTemplate(tm);

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    try {//from  www  . j a va  2s  . c o  m
        tt.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                Assert.assertTrue(TransactionSynchronizationManager.hasResource(container),
                        "Has thread session");
                Db4oTemplate template = new Db4oTemplate(container);
                template.execute(new Db4oCallback() {
                    public Object doInDb4o(ObjectContainer cont) {
                        return null;
                    }
                });
            }
        });
        Assert.fail("Should have thrown InvalidIsolationLevelException");
    } catch (InvalidIsolationLevelException e) {
        // it's okay
    }

    Assert.assertTrue(!TransactionSynchronizationManager.hasResource(container), "Has no container");
    Assert.assertTrue(!TransactionSynchronizationManager.isSynchronizationActive(),
            "JTA synchronizations not active");

    // TODO verify(container)....; exception thrown?
}

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

@Transactional(propagation = Propagation.NOT_SUPPORTED)
@CacheEvict(value = { WallRideCacheConfiguration.ARTICLE_CACHE,
        WallRideCacheConfiguration.PAGE_CACHE }, allEntries = true)
public List<Tag> bulkDeleteTag(TagBulkDeleteRequest bulkDeleteRequest, final BindingResult result) {
    List<Tag> tags = new ArrayList<>();
    for (long id : bulkDeleteRequest.getIds()) {
        final TagDeleteRequest deleteRequest = new TagDeleteRequest.Builder().id(id)
                .language(bulkDeleteRequest.getLanguage()).build();

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

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
        Tag tag = null;//from  w w w  . j  a  v a  2  s.  co  m
        try {
            tag = transactionTemplate.execute(new TransactionCallback<Tag>() {
                public Tag doInTransaction(TransactionStatus status) {
                    return deleteTag(deleteRequest, result);
                }
            });
            tags.add(tag);
        } catch (Exception e) {
            logger.debug("Errors: {}", r);
            result.addAllErrors(r);
        }
    }
    return tags;
}

From source file:ch.tatool.app.service.impl.UserAccountServiceImpl.java

/**
  * Opens an account data object.//from  w  w  w.jav  a2  s.c o  m
  * 
  * The account object is backed by the database. The password is conveniently used
  * as database password, which would fail in case of incorrect password.
  */
public UserAccount loadAccount(Info info, String password) {
    UserAccountImpl.InfoImpl infoImpl = (UserAccountImpl.InfoImpl) info;

    // load the database support objects (spring does all the wiring work for us
    Properties properties = new Properties();
    String dataPath = new File(infoImpl.getFolder(), "data").getAbsolutePath();
    properties.setProperty("account.data.folder", dataPath);
    if (password != null && password.length() > 0) {
        properties.setProperty("account.password", password);
    } else {
        properties.setProperty("account.password", "");
    }

    BeanFactory beanFactory = ContextUtils.createBeanFactory(configurationFilePath, properties);

    // create an account object, and bind it to the database
    final UserAccountImpl userAccount = new UserAccountImpl();
    userAccount.setFolder(infoImpl.getFolder());
    userAccount.setBeanFactory(beanFactory);
    userAccount.setPassword(password);
    userAccount.setName(infoImpl.getName());
    userAccount.setId(infoImpl.getId());

    // initialize transaction management
    PlatformTransactionManager transactionManager = (PlatformTransactionManager) beanFactory
            .getBean("userAccountTxManager");
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    userAccount.setTransactionTemplate(transactionTemplate);

    // load the account in a transaction
    try {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                UserAccountDAO userAccountDAO = userAccount.getUserAccountDAO();
                userAccountDAO.loadAccount(userAccount);
            }
        });

    } catch (org.hibernate.ObjectNotFoundException onfe) {
        logger.warn("Databasee entry for account does not exist anymore. Got the database deleted?");
        throw new RuntimeException("Unable to load user account due to missing data");
    }

    changeLocale(userAccount);

    return userAccount;
}

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

/**
 * Start clearing the till.//from   ww  w .  j  a  va 2 s.c  o  m
 * <p/>
 * This sets the status of the till balance to IN_PROGRESS, so that any new payments or refunds don't affect it.
 * <p/>
 * If the cash float is different to the existing cash float for the till, an adjustment will be created.
 *
 * @param balance   the till balance
 * @param cashFloat the amount remaining in the till
 * @throws TillRuleException         if the balance is not UNCLEARED
 * @throws ArchetypeServiceException for any archetype service error
 */
public void startClearTill(final FinancialAct balance, final BigDecimal cashFloat) {
    if (!balance.getStatus().equals(TillBalanceStatus.UNCLEARED)) {
        throw new TillRuleException(InvalidStatusForStartClear, balance.getStatus());
    }
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            if (isClearInProgress(getTillRef(balance, service))) {
                throw new TillRuleException(ClearInProgress);
            }
            balance.setStatus(TillBalanceStatus.IN_PROGRESS);
            Till till = getTillBean(balance);
            addAdjustment(balance, cashFloat, till);
            service.save(balance);
            till.setTillFloat(cashFloat);
            till.setLastCleared(new Date());
            till.save();
        }
    });
}

From source file:org.web4thejob.context.ContextUtil.java

public static TransactionTemplate getTransactionWrapper() {
    return new TransactionTemplate(rootContext.getBean(PlatformTransactionManager.class));
}

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

@DELETE
@Path("/{configurationId}")
public Response deleteControllerConfiguration(@PathParam("configurationId") Long configurationid) {
    final ControllerConfiguration existingConfiguration = account
            .getControllerConfigurationById(configurationid);

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override/*from  w ww. ja  v a  2  s.  c  o  m*/
        public Object doInTransaction(TransactionStatus transactionStatus) {
            account.removeControllerConfigurations(existingConfiguration);
            controllerConfigurationRepository.delete(existingConfiguration);
            return null;
        }
    });

    return Response.ok().build();

}

From source file:org.jasig.cas.ticket.registry.JpaTicketRegistryTests.java

void addTicketInTransaction(final Ticket ticket) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.addTicket(ticket);
            return null;
        }//  w  w  w .ja  v  a  2s  .co m
    });
}

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

@Test
public void testTransactionRollback() throws FcrepoOperationFailedException {
    final String baseUrl = "http://localhost:8080/rest";
    final String tx = "tx:1234567890";
    final URI commitUri = URI.create(baseUrl + "/" + tx + FcrepoConstants.COMMIT);
    final URI beginUri = URI.create(baseUrl + FcrepoConstants.TRANSACTION);
    final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
    txMgr.setBaseUrl(baseUrl);/*from w ww.ja  v  a  2 s.  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(mockClient.post(eq(beginUri))).thenReturn(mockPostBuilder);
    when(mockClient.post(eq(commitUri))).thenReturn(mockPostBuilder2);
    when(mockPostBuilder.perform()).thenReturn(new FcrepoResponse(beginUri, 201,
            singletonMap("Location", singletonList(baseUrl + "/" + tx)), null));
    when(mockPostBuilder2.perform()).thenReturn(new FcrepoResponse(commitUri, 201, emptyMap(), null));

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

    assertEquals(tx, txObj.getSessionId());
    assertFalse(status.isCompleted());

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

    txMgr.rollback(status);

    txObj = (FcrepoTransactionObject) status.getTransaction();

    assertNull(txObj.getSessionId());
    assertTrue(status.isCompleted());
}

From source file:com.bitsofproof.supernode.core.TxHandler.java

public void validateCacheAndSend(final Tx t, final BitcoinPeer peer) throws ValidationException {
    ValidationException exception = network.getStore().runInCacheContext(new BlockStore.CacheContextRunnable() {
        @Override//from  w  w  w  .  j  a va2  s . c om
        public void run(TxOutCache cache) throws ValidationException {
            synchronized (unconfirmed) {
                if (!unconfirmed.containsKey(t.getHash())) {
                    ValidationException exception = new TransactionTemplate(transactionManager)
                            .execute(new TransactionCallback<ValidationException>() {
                                @Override
                                public ValidationException doInTransaction(TransactionStatus status) {
                                    status.setRollbackOnly();

                                    try {
                                        network.getStore().validateTransaction(t, availableOutput);
                                        sendTransaction(t, peer);
                                        cacheTransaction(t);
                                        notifyListener(t);
                                        if (peer == null) {
                                            synchronized (own) {
                                                own.add(t.getHash());
                                            }
                                        }
                                        return null;
                                    } catch (ValidationException e) {
                                        return e;
                                    }
                                }
                            });
                    if (exception != null) {
                        throw exception;
                    }
                }
            }
        }
    });
    if (exception != null) {
        log.debug("REJECTING transaction " + t.getHash());
        throw exception;
    }
}

From source file:org.jasig.cas.ticket.registry.JpaTicketRegistryTests.java

void deleteTicketInTransaction(final String ticketId) {
    new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() {
        public Void doInTransaction(final TransactionStatus status) {
            jpaTicketRegistry.deleteTicket(ticketId);
            return null;
        }/* w  ww .j  av  a 2  s .  c  o  m*/
    });
}