Example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW

List of usage examples for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW

Introduction

In this page you can find the example usage for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW.

Prototype

int PROPAGATION_REQUIRES_NEW

To view the source code for org.springframework.transaction TransactionDefinition PROPAGATION_REQUIRES_NEW.

Click Source Link

Document

Create a new transaction, suspending the current transaction if one exists.

Usage

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * //from   w ww . ja  v  a 2 s .  com
 * Check that not existing control are created.
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void creationControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userForCreation");
        List<DbeExpendControl> controls = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertTrue(controls.size() == 0);
        // Update limits.
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        limitService.proccesLimit(tx);
        transactionManager.commit(status);
        controls = controlService.getExpendDataForUserAppProvCurrencyObCountry(tx.getTxEndUserId(),
                tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(), tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controls);
        Assert.assertTrue(controls.size() == 3);
        // All the new control have to be set to 0
        for (DbeExpendControl control : controls) {
            Assert.assertTrue(control.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0);
        }
        ProcessingLimitServiceTest.logger.debug("Controls:" + controls.size());
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());

    }
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * /*  w  w w.j av  a  2s  . com*/
 * Check that not existing control are created.
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void creationControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userForCreation");

        List<DbeExpendControl> controls = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertTrue(controls.isEmpty());

        // Update limits.
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        limitService.proccesLimit(tx);
        transactionManager.commit(status);

        controls = controlService.getExpendDataForUserAppProvCurrency(tx.getTxEndUserId(),
                tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controls);
        Assert.assertTrue(controls.size() == 3);

        // All the new control have to be set to 0
        for (DbeExpendControl control : controls) {
            Assert.assertTrue(control.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0);
        }
        ProcessingLimitServiceTest.logger.debug("Controls:" + controls.size());
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());

    }
}

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

@Scheduled(fixedDelay = DateUtils.MILLIS_PER_MINUTE)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
@Override//from ww w  . ja  va 2s  . co m
public void purgeInactiveSubscriptions() {
    if (getConfig().isSchedulingDisabled()) {
        return;
    }

    Long purgeInactiveAfterMillis = getConfig().getSubscriptionPurgeInactiveAfterMillis();
    if (getConfig().isSubscriptionEnabled() == false || purgeInactiveAfterMillis == null) {
        return;
    }

    Date cutoff = new Date(System.currentTimeMillis() - purgeInactiveAfterMillis);
    Collection<SubscriptionTable> toPurge = mySubscriptionTableDao.findInactiveBeforeCutoff(cutoff);
    for (SubscriptionTable subscriptionTable : toPurge) {

        final IdDt subscriptionId = subscriptionTable.getSubscriptionResource().getIdDt();
        ourLog.info("Deleting inactive subscription {} - Created {}, last client poll {}",
                new Object[] { subscriptionId.toUnqualified(), subscriptionTable.getCreated(),
                        subscriptionTable.getLastClientPoll() });
        TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
        txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        txTemplate.execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus theStatus) {
                delete(subscriptionId, null);
                return null;
            }
        });
    }
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from   w  w  w  .ja  va2  s.  co  m*/
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }
    // check that
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        boolean finded = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                finded = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(finded);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

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:org.alfresco.util.transaction.SpringAwareUserTransaction.java

/**
 * @throws NotSupportedException if an attempt is made to reuse this instance
 *///w ww.j  a va 2s  .  c  o  m
public synchronized void begin() throws NotSupportedException, SystemException {
    // make sure that the status and info align - the result may or may not be null
    @SuppressWarnings("unused")
    TransactionInfo txnInfo = getTransactionInfo();
    if (internalStatus != Status.STATUS_NO_TRANSACTION) {
        throw new NotSupportedException("The UserTransaction may not be reused");
    }

    // check 

    if ((propagationBehaviour != TransactionDefinition.PROPAGATION_REQUIRES_NEW)) {
        if (!readOnly && TransactionSynchronizationManager.isSynchronizationActive()
                && TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            throw new IllegalStateException("Nested writable transaction in a read only transaction");
        }
    }

    // begin a transaction
    try {
        internalTxnInfo = createTransactionIfNecessary((Method) null, (Class<?>) null); // super class will just pass nulls back to us
    } catch (CannotCreateTransactionException e) {
        throw new ConnectionPoolException("The DB connection pool is depleted.", e);
    }

    internalStatus = Status.STATUS_ACTIVE;
    threadId = Thread.currentThread().getId();

    // Record that transaction details now that begin was successful
    isBeginMatched = false;
    if (isCallStackTraced) {
        // get the stack trace
        Exception e = new Exception();
        e.fillInStackTrace();
        beginCallStack = e.getStackTrace();
    }

    // done
    if (logger.isDebugEnabled()) {
        logger.debug("Began user transaction: " + this);
    }
}

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from   w  ww .j ava 2  s .c o  m*/
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);

        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }

        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }

    // check that
    try {
        tx.setFtChargedAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();

        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);

        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        boolean found = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                found = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(found);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

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  w  w w.  java  2  s.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();
}

From source file:com.goodhuddle.huddle.service.impl.MemberServiceImpl.java

@Override
public ImportMembersResults importMembers(MultipartFile multipartFile, Long[] tagIds) {
    final ImportMembersResults results = new ImportMembersResults();
    results.setSuccess(true);//from   w w w .  j a  v a 2  s.c o m

    try {
        final Huddle huddle = huddleService.getHuddle();

        if (!multipartFile.isEmpty()) {

            File file = fileStore.getTempFile(fileStore.createTempFile(multipartFile.getBytes()));

            final CSVReader reader = new CSVReader(new FileReader(file));
            if (reader.readNext() != null) {
                // skipped header row

                final List<Tag> tags = new ArrayList<>();
                if (tagIds != null) {
                    for (Long tagId : tagIds) {
                        tags.add(tagRepository.findByHuddleAndId(huddle, tagId));
                    }
                }

                boolean done = false;
                while (!done) {
                    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
                    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
                    done = txTemplate.execute(new TransactionCallback<Boolean>() {

                        @Override
                        public Boolean doInTransaction(TransactionStatus status) {
                            try {
                                int i = 0;
                                String[] nextLine;
                                while ((nextLine = reader.readNext()) != null) {
                                    String email = nextLine[0];
                                    String firstName = nextLine[1];
                                    String lastName = nextLine[2];
                                    String postCode = nextLine[3];
                                    String phone = nextLine[4];

                                    Member member = memberRepository.findByHuddleAndEmailIgnoreCase(huddle,
                                            email);
                                    if (member != null) {
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        List<Tag> memberTags = member.getTags();
                                        if (memberTags == null) {
                                            memberTags = new ArrayList<>();
                                        }
                                        outer: for (Tag tag : tags) {
                                            for (Tag memberTag : memberTags) {
                                                if (memberTag.getId() == member.getId()) {
                                                    break outer;
                                                }
                                            }
                                            memberTags.add(tag);
                                        }
                                        member.setTags(memberTags);
                                        memberRepository.save(member);
                                        results.setNumUpdated(results.getNumUpdated() + 1);
                                    } else {
                                        member = new Member();
                                        member.setHuddle(huddle);
                                        member.setEmail(email);
                                        member.setFirstName(firstName);
                                        member.setLastName(lastName);
                                        member.setPostCode(postCode);
                                        member.setPhone(phone);
                                        member.setTags(tags);
                                        memberRepository.save(member);
                                        results.setNumImported(results.getNumImported() + 1);
                                    }

                                    if (i++ > 30) {
                                        return false;
                                    }
                                }
                                return true;
                            } catch (IOException e) {
                                log.error("Error importing file: " + e, e);
                                results.setSuccess(false);
                                results.setErrorMessage("Error importing file: " + e);
                                return true;
                            }
                        }
                    });
                }

            }

        } else {
            log.info("Empty file was uploaded");
            results.setSuccess(false);
            results.setErrorMessage("Empty file was uploaded");
        }
    } catch (IOException e) {
        results.setSuccess(false);
        results.setErrorMessage("Error uploading file: " + e);
    }

    return results;
}