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:com.dianping.lion.service.impl.ConfigServiceImpl.java

public ConfigServiceImpl(PlatformTransactionManager transactionManager) {
    this.transactionTemplate = new TransactionTemplate(transactionManager);
    this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}

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

private Bundle batch(final RequestDetails theRequestDetails, Bundle theRequest) {
    ourLog.info("Beginning batch with {} resources", theRequest.getEntry().size());
    long start = System.currentTimeMillis();

    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    Bundle resp = new Bundle();
    resp.setType(BundleType.BATCHRESPONSE);
    OperationOutcome ooResp = new OperationOutcome();
    resp.addEntry().setResource(ooResp);

    /*/*w w  w. j  ava  2s .  c  om*/
     * For batch, we handle each entry as a mini-transaction in its own database transaction so that if one fails, it doesn't prevent others
     */

    for (final BundleEntryComponent nextRequestEntry : theRequest.getEntry()) {

        TransactionCallback<Bundle> callback = new TransactionCallback<Bundle>() {
            @Override
            public Bundle doInTransaction(TransactionStatus theStatus) {
                Bundle subRequestBundle = new Bundle();
                subRequestBundle.setType(BundleType.TRANSACTION);
                subRequestBundle.addEntry(nextRequestEntry);

                Bundle subResponseBundle = transaction((ServletRequestDetails) theRequestDetails,
                        subRequestBundle, "Batch sub-request");
                return subResponseBundle;
            }
        };

        BaseServerResponseException caughtEx;
        try {
            Bundle nextResponseBundle = txTemplate.execute(callback);
            caughtEx = null;

            BundleEntryComponent subResponseEntry = nextResponseBundle.getEntry().get(0);
            resp.addEntry(subResponseEntry);
            /*
             * If the individual entry didn't have a resource in its response, bring the sub-transaction's OperationOutcome across so the client can see it
             */
            if (subResponseEntry.getResource() == null) {
                subResponseEntry.setResource(nextResponseBundle.getEntry().get(0).getResource());
            }

        } catch (BaseServerResponseException e) {
            caughtEx = e;
        } catch (Throwable t) {
            ourLog.error("Failure during BATCH sub transaction processing", t);
            caughtEx = new InternalErrorException(t);
        }

        if (caughtEx != null) {
            BundleEntryComponent nextEntry = resp.addEntry();

            OperationOutcome oo = new OperationOutcome();
            oo.addIssue().setSeverity(IssueSeverity.ERROR).setDiagnostics(caughtEx.getMessage());
            nextEntry.setResource(oo);

            BundleEntryResponseComponent nextEntryResp = nextEntry.getResponse();
            nextEntryResp.setStatus(toStatusString(caughtEx.getStatusCode()));
        }

    }

    long delay = System.currentTimeMillis() - start;
    ourLog.info("Batch completed in {}ms", new Object[] { delay });
    ooResp.addIssue().setSeverity(IssueSeverity.INFORMATION)
            .setDiagnostics("Batch completed in " + delay + "ms");

    return resp;
}

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

private Bundle batch(final RequestDetails theRequestDetails, Bundle theRequest) {
    ourLog.info("Beginning batch with {} resources", theRequest.getEntry().size());
    long start = System.currentTimeMillis();

    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    Bundle resp = new Bundle();
    resp.setType(BundleTypeEnum.BATCH_RESPONSE);
    OperationOutcome ooResp = new OperationOutcome();
    resp.addEntry().setResource(ooResp);

    /*//from   w  w w. j a va2  s  .c om
     * For batch, we handle each entry as a mini-transaction in its own database transaction so that if one fails, it doesn't prevent others
     */

    for (final Entry nextRequestEntry : theRequest.getEntry()) {

        TransactionCallback<Bundle> callback = new TransactionCallback<Bundle>() {
            @Override
            public Bundle doInTransaction(TransactionStatus theStatus) {
                Bundle subRequestBundle = new Bundle();
                subRequestBundle.setType(BundleTypeEnum.TRANSACTION);
                subRequestBundle.addEntry(nextRequestEntry);

                Bundle subResponseBundle = transaction((ServletRequestDetails) theRequestDetails,
                        subRequestBundle, "Batch sub-request");
                return subResponseBundle;
            }
        };

        BaseServerResponseException caughtEx;
        try {
            Bundle nextResponseBundle = txTemplate.execute(callback);
            caughtEx = null;

            Entry subResponseEntry = nextResponseBundle.getEntry().get(0);
            resp.addEntry(subResponseEntry);
            /*
             * If the individual entry didn't have a resource in its response, bring the sub-transaction's OperationOutcome across so the client can see it
             */
            if (subResponseEntry.getResource() == null) {
                subResponseEntry.setResource(nextResponseBundle.getEntry().get(0).getResource());
            }

        } catch (BaseServerResponseException e) {
            caughtEx = e;
        } catch (Throwable t) {
            ourLog.error("Failure during BATCH sub transaction processing", t);
            caughtEx = new InternalErrorException(t);
        }

        if (caughtEx != null) {
            Entry nextEntry = resp.addEntry();

            OperationOutcome oo = new OperationOutcome();
            oo.addIssue().setSeverity(IssueSeverityEnum.ERROR).setDiagnostics(caughtEx.getMessage());
            nextEntry.setResource(oo);

            EntryResponse nextEntryResp = nextEntry.getResponse();
            nextEntryResp.setStatus(toStatusString(caughtEx.getStatusCode()));
        }

    }

    long delay = System.currentTimeMillis() - start;
    ourLog.info("Batch completed in {}ms", new Object[] { delay });
    ooResp.addIssue().setSeverity(IssueSeverityEnum.INFORMATION)
            .setDiagnostics("Batch completed in " + delay + "ms");

    return resp;
}

From source file:alfio.manager.system.DataMigrator.java

@Autowired
public DataMigrator(EventMigrationRepository eventMigrationRepository, EventRepository eventRepository,
        TicketCategoryRepository ticketCategoryRepository, @Value("${alfio.version}") String currentVersion,
        @Value("${alfio.build-ts}") String buildTimestamp, PlatformTransactionManager transactionManager,
        ConfigurationRepository configurationRepository, NamedParameterJdbcTemplate jdbc) {
    this.eventMigrationRepository = eventMigrationRepository;
    this.eventRepository = eventRepository;
    this.ticketCategoryRepository = ticketCategoryRepository;
    this.configurationRepository = configurationRepository;
    this.jdbc = jdbc;
    this.currentVersion = parseVersion(currentVersion);
    this.currentVersionAsString = currentVersion;
    this.buildTimestamp = ZonedDateTime.parse(buildTimestamp);
    this.transactionTemplate = new TransactionTemplate(transactionManager,
            new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
}

From source file:fi.hsl.parkandride.core.service.PredictionService.java

private void doUpdatePredictions() {
    log.info("Updating predictions");
    TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
    txTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); // TODO: set in Core/JdbcConfiguration
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    for (Long predictorId : findPredictorsNeedingUpdate()) {
        try {//w ww .j av  a2  s.c o m
            txTemplate.execute(tx -> {
                updatePredictor(predictorId);
                log.debug("Updating predictor {} done", predictorId);
                return null;
            });
        } catch (Exception e) {
            log.error("Failed to update predictor {}", predictorId, e);
        }
    }
}

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

@Override
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public synchronized int pollForNewUndeliveredResources() {
    if (getConfig().isSubscriptionEnabled() == false) {
        return 0;
    }//from  w  w  w .j a v  a  2 s.c  o  m
    ourLog.trace("Beginning pollForNewUndeliveredResources()");

    // SubscriptionCandidateResource

    Collection<Long> subscriptions = mySubscriptionTableDao
            .findSubscriptionsWhichNeedToBeChecked(SubscriptionStatusEnum.ACTIVE.getCode(), new Date());

    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    int retVal = 0;
    for (final Long nextSubscriptionTablePid : subscriptions) {
        retVal += txTemplate.execute(new TransactionCallback<Integer>() {
            @Override
            public Integer doInTransaction(TransactionStatus theStatus) {
                SubscriptionTable nextSubscriptionTable = mySubscriptionTableDao
                        .findOne(nextSubscriptionTablePid);
                return pollForNewUndeliveredResources(nextSubscriptionTable);
            }
        });
    }

    return retVal;
}

From source file:alfio.manager.AdminReservationRequestManager.java

private Result<Triple<TicketReservation, List<Ticket>, Event>> processReservation(
        AdminReservationRequest request, Pair<Event, User> p) {
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    TransactionTemplate template = new TransactionTemplate(transactionManager, definition);
    return template.execute(status -> {
        try {//from w  ww. j av  a2s.  co m
            String eventName = p.getLeft().getShortName();
            String username = p.getRight().getUsername();
            Result<Triple<TicketReservation, List<Ticket>, Event>> result = adminReservationManager
                    .createReservation(request.getBody(), eventName, username)
                    .flatMap(r -> adminReservationManager.confirmReservation(eventName, r.getLeft().getId(),
                            username));
            if (!result.isSuccess()) {
                status.setRollbackOnly();
            }
            return result;
        } catch (Exception ex) {
            status.setRollbackOnly();
            return Result.error(singletonList(ErrorCode.custom("", ex.getMessage())));
        }
    });
}

From source file:org.seasar.dbflute.unit.spring.SpringTestCase.java

/**
 * {@inheritDoc}/*from   w w w.  j a  v a 2  s .c om*/
 */
@Override
protected TransactionResource beginNewTransaction() { // user method
    final String managerKey = "transactionManager";
    if (!hasComponent(managerKey)) {
        return null;
    }
    final PlatformTransactionManager manager = getComponent(managerKey);
    final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    final TransactionStatus status = manager.getTransaction(def);
    final SpringTransactionResource resource = new SpringTransactionResource();
    resource.setTransactionManager(manager);
    resource.setTransactionStatus(status);
    return resource; // for thread-fire's transaction or manual transaction
}

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

/**
 * Update control dates/*from  w  ww  . j a va2  s  . co m*/
 * 
 * @param controls
 */
private void updateDate(List<DbeExpendControl> controls) {
    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 : controls) {
        control.setDtNextPeriodStart(cal.getTime());
        controlService.createOrUpdate(control);
    }
    transactionManager.commit(status);

}

From source file:org.cfr.capsicum.datasource.CayenneTransactionManager.java

/**
 * This implementation sets the isolation level but ignores the timeout.
 *///from  w  ww . jav  a 2 s  . c  om
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    CayenneTransactionObject txObject = (CayenneTransactionObject) transaction;
    Connection con = null;

    try {
        if (txObject.getConnectionHolder() == null
                || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
            Connection newCon = this.dataSource.getConnection();
            if (logger.isDebugEnabled()) {
                logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
            }
            ObjectContext context = null;
            if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
                Injector injector = this.cayenneRuntime.getInjector();
                context = injector.getInstance(ObjectContextFactory.class).createContext();
            } else {
                context = BaseContext.getThreadObjectContext();
            }
            txObject.setConnectionHolder(new CayenneConnectionHolder(newCon, context), true);
            BaseContext.bindThreadObjectContext(context);
        }

        txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
        con = txObject.getConnectionHolder().getConnection();

        Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
        txObject.setPreviousIsolationLevel(previousIsolationLevel);

        // Switch to manual commit if necessary. This is very expensive in
        // some
        // JDBC drivers,
        // so we don't want to do it unnecessarily (for example if we've
        // explicitly
        // configured the connection pool to set it already).
        if (con.getAutoCommit()) {
            txObject.setMustRestoreAutoCommit(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
            }
            con.setAutoCommit(false);
        }
        txObject.getConnectionHolderEx().setTransactionActive(true);

        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewConnectionHolder()) {
            TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());
        }
    }

    catch (SQLException ex) {
        DataSourceUtils.releaseConnection(con, this.dataSource);
        throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction",
                exceptionTranslator.convertJdbcAccessException(ex));
    }
}