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: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);

    /*//  ww w  .  j a  v a  2  s  .c o  m
     * 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:org.danann.cernunnos.sql.TransactionTask.java

public void perform(final TaskRequest req, final TaskResponse res) {
    PlatformTransactionManager transactionManager = (PlatformTransactionManager) this.transactionManagerPhrase
            .evaluate(req, res);//from www.  j  a  va 2 s .  c  o m
    if (transactionManager == null) {
        //If no transaction manager was found there MUST be a DataSource
        final DataSource dataSource = (DataSource) this.dataSourcePhrase.evaluate(req, res);

        //Create a local DataSourceTransactionManager
        transactionManager = new DataSourceTransactionManager(dataSource);

        //Register the new tx manager in the response for later use if needed
        final String transactionManagerAttrName = (String) this.attributeNamePhrase.evaluate(req, res);
        res.setAttribute(transactionManagerAttrName, transactionManager);

        if (log.isDebugEnabled()) {
            String msg = "Created PlatformTransactionManager '" + transactionManager + "' for DataSource '"
                    + dataSource + "' and bound in response under attribute name '" + transactionManagerAttrName
                    + "'.";
            this.log.debug(msg);
        }
    } else {
        if (log.isDebugEnabled()) {
            String msg = "Found PlatformTransactionManager '" + transactionManager + "' in request.";
            this.log.debug(msg);
        }
    }

    //Create the tx template
    final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

    //Execute the transaction in a callback
    final TransactionCallback transactionCallback = new PerformSubtasksTransactionCallback(this, req, res);
    transactionTemplate.execute(transactionCallback);
}

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);

    /*/*from w  ww . j  a  v a2s  .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:org.cleverbus.test.AbstractDbTest.java

protected Message[] createAndSaveMessages(final int messageCount, final ExternalSystemExtEnum sourceSystem,
        final ServiceExtEnum service, final String operationName, final String payload) {
    TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager);
    return tx.execute(new TransactionCallback<Message[]>() {
        @Override//  w w w.j  a va  2  s  .  c o m
        public Message[] doInTransaction(TransactionStatus status) {
            Message[] messages = new Message[messageCount];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = createMessage(sourceSystem, service, operationName, payload);
                messages[i].setMsgTimestamp(DateTime.now().plusSeconds(i * 5).toDate());
                em.persist(messages[i]);
            }
            em.flush();
            return messages;
        }
    });
}

From source file:de.iteratec.iteraplan.presentation.UserContextInitializationServiceImpl.java

/** {@inheritDoc} */
public String initializeUserContext(HttpServletRequest req, Authentication authentication) {
    try {/*from w  ww . ja v  a 2  s  . co  m*/
        final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        final TransactionCallback<String> transactionCallback = new StoreContextCallback(req, authentication);

        return transactionTemplate.execute(transactionCallback);
    } catch (TransactionException e) {
        LOGGER.error("Data source is not available", e);
        throw new IteraplanTechnicalException(IteraplanErrorMessages.LOGIN_DB_DATASOURCE_NOT_AVAILABLE, e);
    }
}

From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java

public JdbcMonitorDao(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager,
        int purgeOldFailures, int purgeOldStatus) {
    this.jdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
    this.transactionTemplate = new TransactionTemplate(transactionManager);

    this.purgeOldFailure = TimeUnit.MILLISECONDS.convert(purgeOldFailures, TimeUnit.MINUTES);
    this.purgeOldStatus = TimeUnit.MILLISECONDS.convert(purgeOldStatus, TimeUnit.MINUTES);
}

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 {/*from   w  w  w.  ja  va  2 s . c  om*/
            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:org.openremote.beehive.configuration.www.DevicesAPI.java

@DELETE
@Path("/{deviceId}")
public Response deleteDevice(@PathParam("deviceId") Long deviceId) {
    final Device existingDevice = account.getDeviceById(deviceId);

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override/*  www . jav a2s  .  com*/
        public Object doInTransaction(TransactionStatus transactionStatus) {
            account.removeDevice(existingDevice);
            deviceRepository.delete(existingDevice);
            return null;
        }
    });

    return Response.ok().build();

}

From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStore.java

/**
 * Sets the connection pool provider and initializes the tables in the dbms if missing
 *//*from   www.  ja  va 2 s.com*/
public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    DataSourceTransactionManager dsTransactionManager = new DataSourceTransactionManager(dataSource);
    this.tt = new TransactionTemplate(dsTransactionManager);
    this.jt = new SimpleJdbcTemplate(dsTransactionManager.getDataSource());
}

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

@PUT
@Path("/{configurationId}")
public Response updateControllerConfiguration(@PathParam("configurationId") Long configurationId,
        final ControllerConfigurationDTOIn configurationDTO) {
    final ControllerConfiguration existingConfiguration = account
            .getControllerConfigurationById(configurationId);

    ControllerConfiguration optionalControllerConfigurationWithSameName = account
            .getControllerConfigurationByName(configurationDTO.getName());

    if (optionalControllerConfigurationWithSameName != null
            && !optionalControllerConfigurationWithSameName.getId().equals(existingConfiguration.getId())) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A controller configuration with the same name already exists"))
                .build();// ww w  .j  av  a2s.  c om
    }

    return Response.ok(new ControllerConfigurationDTOOut(new TransactionTemplate(platformTransactionManager)
            .execute(new TransactionCallback<ControllerConfiguration>() {
                @Override
                public ControllerConfiguration doInTransaction(TransactionStatus transactionStatus) {
                    existingConfiguration.setCategory(configurationDTO.getCategory());
                    existingConfiguration.setName(configurationDTO.getName());
                    existingConfiguration.setValue(configurationDTO.getValue());
                    controllerConfigurationRepository.save(existingConfiguration);
                    return existingConfiguration;
                }
            }))).build();
}