Example usage for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult

List of usage examples for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallbackWithoutResult TransactionCallbackWithoutResult.

Prototype

TransactionCallbackWithoutResult

Source Link

Usage

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

/**
 * Saves an account.//from   w  w w  .  java 2 s.co  m
 */
public void saveAccount(UserAccount account) {
    // write the database
    final UserAccountImpl userAccount = (UserAccountImpl) account;
    userAccount.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            UserAccountDAO userAccountDAO = userAccount.getUserAccountDAO();
            userAccountDAO.saveAccount(userAccount);
        }
    });
    updateUserAccountInfo(userAccount);
}

From source file:org.jspresso.hrsample.development.MongoTestDataPersister.java

private void clearPresiousData() {
    final MongoBackendController mongoBackendController = getBackendController();
    mongoBackendController.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        @Override//from   ww w .jav a 2 s  .  c o m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            List<Company> companies = mongoBackendController.findByQuery(new Query(), null, Company.class);
            for (Company company : companies) {
                try {
                    mongoBackendController.cleanRelationshipsOnDeletion(company, false);
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace(System.err);
                }
            }
            List<City> cities = mongoBackendController.findByQuery(new Query(), null, City.class);
            for (City city : cities) {
                try {
                    mongoBackendController.cleanRelationshipsOnDeletion(city, false);
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                    e.printStackTrace(System.err);
                }
            }
        }
    });
}

From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private void updateStateAndQueueForParsing(final Long documentId, final String content, final String etag,
        final Date lastModifiedDate, final Date retrievalDate) {

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*from  w  w  w. ja v  a2 s .  c  o  m*/
        protected void doInTransactionWithoutResult(TransactionStatus txStatus) {
            final Document attachedDocument = DocumentRetrievalTaskImpl.this.documentDao.get(documentId);
            attachedDocument.setEtag(etag);
            attachedDocument.setLastModifiedDate(lastModifiedDate);
            attachedDocument.setRetrievalDate(retrievalDate);

            if (attachedDocument.getDocumentContent() == null) {
                final DocumentContent documentContent = new DocumentContent(attachedDocument, content);
                attachedDocument.setDocumentContent(documentContent);
                DocumentRetrievalTaskImpl.this.documentDao.add(documentContent);
            }

            DocumentRetrievalTaskImpl.this.documentDao.update(attachedDocument);

            // do in transaction to make sure failure to queue doesn't leave
            // dead doc
            requestParse(documentId, content);
        }
    });
}

From source file:edu.northwestern.bioinformatics.studycalendar.osgi.felixcm.internal.PscFelixPersistenceManager.java

public void delete(final String pid) throws IOException {
    log.debug("Deleting all properties for {}", pid);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override//from  w  w  w  .java 2 s  .  c  o m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            // bulk delete doesn't cascade for some reason
            getHibernateTemplate().deleteAll(getProperties(pid));
        }
    });
}

From source file:com.thoughtworks.go.server.dao.PipelineSqlMapDaoIntegrationTest.java

private void savePipeline(final Pipeline pipeline) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*from  w w w  . j  ava  2s  .co  m*/
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            materialRepository.save(pipeline.getBuildCause().getMaterialRevisions());
            pipelineDao.saveWithStages(pipeline);
        }
    });
}

From source file:com.osrdata.etltoolbox.fileloader.FileSpecification.java

/**
 * Loads specified file into target targetTable. This operation transactional and will rollback any database operations if
 * there are any errors processing the data.
 *
 * @param sourceFile source file to be loaded
 * @throws IOException on error reading file
 * @throws ParseException on error parsing fields from file
 *//* ww  w  .j  a v a  2  s .co  m*/
public void load(final File sourceFile) throws IOException, ParseException {
    this.sourceFile = sourceFile;
    Matcher matcher = sourcePattern.matcher(sourceFile.getName());
    etlDate = new Date();
    etlType = "I";
    if (matcher.find()) {
        if (dateGroup != null && dateGroup.intValue() <= matcher.groupCount()) {
            etlDate = new SimpleDateFormat(dateFormat).parse(matcher.group(dateGroup.intValue()));
        }
        if (typeGroup != null && typeGroup.intValue() <= matcher.groupCount()) {
            etlType = matcher.group(typeGroup.intValue()).substring(0, 1).toUpperCase();
        }
    }
    recordId = new BigDecimal(new SimpleDateFormat("yyyyMMdd").format(etlDate) + "0000000000");

    DataSourceTransactionManager txManager = new DataSourceTransactionManager(targetDs);
    TransactionTemplate txTemplate = new TransactionTemplate(txManager);
    targetTemplate = new JdbcTemplate(targetDs);

    log.info("Processing source file " + sourceFile.getName());
    numRecords = 0l;
    try {
        txTemplate.execute(new TransactionCallbackWithoutResult() {
            public void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    boolean loadFlag = false;
                    Integer fileId = selectAuditFile();
                    if (fileId != null && replaceExisting) {
                        deleteExisting(fileId);
                        updateAuditFile(fileId);
                        loadFlag = true;
                    } else if (fileId == null) {
                        fileId = insertAuditFile();
                        loadFlag = true;
                    }

                    if (loadFlag) {
                        CSVReader reader = new CSVReader(new FileReader(sourceFile), parserSeparator,
                                parserQuotechar, parserEscape, parserLine, parserStrictQuotes,
                                parserIgnoreLeadingWhiteSpace);
                        String[] values;
                        startTime = System.currentTimeMillis();
                        while ((values = reader.readNext()) != null) {
                            add(values, fileId);
                            numRecords++;
                            if (trace > 0l && numRecords % trace == 0l) {
                                log.info("\tProcessed " + getCount(numRecords) + " records in " + getDuration()
                                        + " (" + getRecordsPerSecond() + " rps)");
                            }
                        }
                        reader.close();
                        insertTarget();
                    } else {
                        log.info("\tSkipping previously loaded file" + sourceFile.getName());
                    }
                } catch (RuntimeException e) {
                    throw e;
                } catch (Throwable e) {
                    log.error("\tError at record " + numRecords + " in " + sourceFile.getName());
                    throw new RuntimeException(e);
                }
            }
        });
    } catch (RuntimeException e) {
        log.error("\tAn exception occurred while processing record " + numRecords + " in "
                + sourceFile.getName() + ". All transactions for this file have been rolled back.", e);
    }
    log.info("\tCompleted processing of " + getCount(numRecords) + " records in " + getDuration() + " ("
            + getRecordsPerSecond() + " rps)");
}

From source file:com.mothsoft.alexis.engine.numeric.TopicActivityDataSetImporter.java

private void recordAggregateTopicActivity(final Long userId, final Date startDate, final BigInteger total) {

    logger.debug("Recording aggregate topic activity for user: " + userId + "; (" + startDate.toString() + ", "
            + total + ")");

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*from ww w .  java 2  s .  com*/
        protected void doInTransactionWithoutResult(TransactionStatus txStatus) {
            DataSet dataSet = TopicActivityDataSetImporter.this.dataSetDao
                    .findAggregateTopicActivityDataSet(userId);

            if (dataSet == null) {
                final DataSetType type = TopicActivityDataSetImporter.this.dataSetTypeDao
                        .findSystemDataSetType(DataSetType.TOPIC_ACTIVITY);
                dataSet = new DataSet(userId, "*All Topics*", type, true);
                TopicActivityDataSetImporter.this.dataSetDao.add(dataSet);
            }

            final DataSetPoint totalPoint = new DataSetPoint(dataSet, startDate, total.doubleValue());
            TopicActivityDataSetImporter.this.dataSetPointDao.add(totalPoint);
        }
    });
}

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

/**
 * Clears a till for an IN_PROGRESS balance.
 *
 * @param balance the current till balance
 * @param account the account to deposit to
 * @throws TillRuleException if the balance doesn't have a till
 */// w  w w  .j a  va2s. c  o m
public void clearTill(final FinancialAct balance, final Party account) {
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            clearInProgressTill(balance, account);
        }
    });
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that stock is updated correctly if an item is saved twice in the one transaction, but the first
 * save is incomplete./*from   ww  w  .  j  av a 2  s .c  o m*/
 */
@Test
public void testPartialSaveInTxn() {
    final List<FinancialAct> acts = createInvoice();
    final FinancialAct invoice = acts.get(0);
    final FinancialAct item = acts.get(1);
    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity, false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(item);
            save(item);
            save(invoice);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    save(acts); // stock shouldn't change if resaved
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Clone/merge of component lists with holes. See bug 757.
 *//*w  w  w  .j  a  v a 2s.c  o m*/
@Test
public void testCloneComponentListWithHoles() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();

    EnhancedDetachedCriteria employeeCriteria = EnhancedDetachedCriteria.forClass(Employee.class);
    final Employee emp = hbc.findFirstByCriteria(employeeCriteria, EMergeMode.MERGE_KEEP, Employee.class);

    List<ContactInfo> alternativeContacts = new ArrayList<ContactInfo>();
    alternativeContacts.add(hbc.getEntityFactory().createComponentInstance(ContactInfo.class));
    alternativeContacts.add(null);
    alternativeContacts.add(hbc.getEntityFactory().createComponentInstance(ContactInfo.class));
    emp.setAlternativeContacts(alternativeContacts);

    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            hbc.cloneInUnitOfWork(emp);
        }
    });
    emp.addToAlternativeContacts(hbc.getEntityFactory().createComponentInstance(ContactInfo.class));
    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            hbc.cloneInUnitOfWork(emp);
        }
    });
}