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

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

Introduction

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

Prototype

TransactionCallback

Source Link

Usage

From source file:nl.strohalm.cyclos.utils.TransactionHelperImpl.java

private <T> RunResult<T> runInCurrentThreadWithResult(final TransactionCallback<T> callback,
        final boolean runTransactional) {
    RunResult<T> result;//from w ww  . j  a  va  2s .  c  o  m
    while (true) {
        try {
            result = transactionTemplate.execute(new TransactionCallback<RunResult<T>>() {
                @Override
                public RunResult<T> doInTransaction(final TransactionStatus status) {
                    final RunResult<T> result = new RunResult<T>();
                    try {
                        // Run the callback in transaction
                        result.result = callback.doInTransaction(status);
                        // If got to this point, there were no errors. Commit depends on the status
                        result.commit = !status.isRollbackOnly();
                    } catch (final LockingException e) {
                        // On locking exceptions, we have to retry
                        status.setRollbackOnly();
                        result.retry = true;
                    } catch (final ApplicationException e) {
                        // ApplicationExceptions controls whether rollbacks are done
                        if (e.isShouldRollback()) {
                            status.setRollbackOnly();
                        } else {
                            result.commit = true;
                        }
                        result.error = e;
                    } catch (final Throwable e) {
                        // On any other exception, rollback
                        status.setRollbackOnly();
                        result.error = e;
                    }
                    return result;
                }
            });
        } catch (Throwable t) {
            result = new RunResult<T>();
            if (ExceptionHelper.isLockingException(t)) {
                result.retry = true;
            } else {
                result.error = t;
            }
        }
        // Run the transaction commit / rollback listeners
        CurrentTransactionData.detachListeners().runListeners(result.commit);
        CurrentTransactionData.cleanup();
        if (!result.retry) {
            // No retry is needed - break the loop
            break;
        }
    }

    // If the callback is a Transactional, we should invoke the afterCommit() method on commit
    if (runTransactional) {
        result.maybeRunAfterCommit(callback);
    }
    return result;
}

From source file:org.akaza.openclinica.ws.EventEndpoint.java

/**
 * if NAMESPACE_URI_V1:scheduleRequest execute this method
 * //from  w ww .  j a va 2s. com
 */
@PayloadRoot(localPart = "scheduleRequest", namespace = NAMESPACE_URI_V1)
public Source scheduleEvent(@XPathParam("//e:event") final NodeList event) throws Exception {

    return getTransactionTemplate().execute(new TransactionCallback<Source>() {
        public Source doInTransaction(TransactionStatus status) {
            Source result = null;
            try {
                result = scheduleEventInTransaction(event);
                assert (result != null);
            } catch (Throwable t) {
                logger.error(t.getMessage());
                logger.error(ExceptionUtils.getStackTrace(t));
                throw new RuntimeException("Error processing schedule event request", t);
            }
            return result;
        }
    });
}

From source file:org.apache.camel.bam.processor.BamProcessorSupport.java

@SuppressWarnings("unchecked")
public void process(final Exchange exchange) {
    for (int i = 1; i <= retryCount; i++) {
        if (i > 1) {
            LOG.info("Retrying attempt: " + i);
            try {
                Thread.sleep(retrySleep);
            } catch (InterruptedException e) {
                LOG.debug("Caught: " + e, e);
            }//from   ww  w . j av a 2 s. c  om
        }
        try {
            transactionTemplate.execute(new TransactionCallback() {
                public Object doInTransaction(TransactionStatus status) {
                    try {
                        Object key = getCorrelationKey(exchange);

                        T entity = loadEntity(exchange, key);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Correlation key: " + key + " with entity: " + entity);
                        }
                        processEntity(exchange, entity);

                        return entity;
                    } catch (Exception e) {
                        return onError(status, e);
                    }
                }
            });
            if (i > 1) {
                LOG.info("Attempt " + i + " worked!");
            }
            return;
        } catch (Exception e) {
            LOG.warn("Failed to complete transaction: " + e, e);
        }
    }
}

From source file:org.apache.camel.component.jdbc.aggregationrepository.JdbcAggregationRepository.java

@SuppressWarnings("unchecked")
public Exchange add(final CamelContext camelContext, final String correlationId, final Exchange exchange) {
    return (Exchange) transactionTemplate.execute(new TransactionCallback() {

        public Exchange doInTransaction(TransactionStatus status) {
            String sql;//w ww.j av a2 s  . c  o  m
            Exchange result = null;
            final String key = correlationId;

            try {
                final byte[] data = codec.marshallExchange(camelContext, exchange);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Adding exchange with key: [" + key + "]");
                }

                String insert = "INSERT INTO " + getRepositoryName() + " (" + EXCHANGE + ", " + ID
                        + ") VALUES (?, ?)";
                String update = "UPDATE " + getRepositoryName() + " SET " + EXCHANGE + " = ? WHERE " + ID
                        + " = ?";

                boolean present = jdbcTemplate.queryForInt(
                        "SELECT COUNT (*) FROM " + getRepositoryName() + " WHERE " + ID + " = ?", key) != 0;
                sql = present ? update : insert;

                // Recover existing exchange with that ID
                if (isReturnOldExchange() && present) {
                    result = get(key, getRepositoryName(), camelContext);
                }

                jdbcTemplate.execute(sql, new AbstractLobCreatingPreparedStatementCallback(getLobHandler()) {
                    @Override
                    protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException {
                        lobCreator.setBlobAsBytes(ps, 1, data);
                        ps.setString(2, key);
                    }
                });

            } catch (IOException e) {
                throw new RuntimeException("Error adding to repository " + repositoryName + " with key " + key,
                        e);
            }

            return result;
        }
    });

}

From source file:org.apache.camel.component.jdbc.aggregationrepository.JdbcAggregationRepository.java

@SuppressWarnings("unchecked")
private Exchange get(final String key, final String repositoryName, final CamelContext camelContext) {
    return (Exchange) transactionTemplateReadOnly.execute(new TransactionCallback() {
        public Exchange doInTransaction(TransactionStatus status) {
            try {
                final byte[] data = jdbcTemplate.queryForObject(
                        "SELECT " + EXCHANGE + " FROM " + repositoryName + " WHERE " + ID + " = ?",
                        new Object[] { key }, byte[].class);
                return codec.unmarshallExchange(camelContext, data);
            } catch (EmptyResultDataAccessException ex) {
                return null;
            } catch (IOException ex) {
                // Rollback the transaction
                throw new RuntimeException("Error getting key " + key + " from repository " + repositoryName,
                        ex);//w w w .  j a v a  2 s. c  o  m
            } catch (ClassNotFoundException ex) {
                // Rollback the transaction
                throw new RuntimeException(ex);
            }
        }
    });
}

From source file:org.apache.camel.component.jdbc.aggregationrepository.JdbcAggregationRepository.java

@SuppressWarnings("unchecked")
public Set<String> getKeys() {
    return (LinkedHashSet<String>) transactionTemplateReadOnly.execute(new TransactionCallback() {
        public LinkedHashSet<String> doInTransaction(TransactionStatus status) {
            List<String> keys = jdbcTemplate.query("SELECT " + ID + " FROM " + getRepositoryName(),
                    new RowMapper<String>() {
                        public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                            String id = rs.getString(ID);
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("getKey [" + id + "]");
                            }//  w ww. ja  va2 s . c  om
                            return id;
                        }
                    });
            return new LinkedHashSet<String>(keys);
        }
    });
}

From source file:org.apache.camel.component.jdbc.aggregationrepository.JdbcAggregationRepository.java

@SuppressWarnings("unchecked")
public Set<String> scan(CamelContext camelContext) {
    return (LinkedHashSet<String>) transactionTemplateReadOnly.execute(new TransactionCallback() {
        public LinkedHashSet<String> doInTransaction(TransactionStatus status) {
            List<String> keys = jdbcTemplate.query("SELECT " + ID + " FROM " + getRepositoryNameCompleted(),
                    new RowMapper<String>() {
                        public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                            String id = rs.getString(ID);
                            if (LOG.isTraceEnabled()) {
                                LOG.trace("getKey [" + id + "]");
                            }//  w  w w .j av  a  2s  .  com
                            return id;
                        }
                    });
            return new LinkedHashSet<String>(keys);
        }
    });
}

From source file:org.apache.ctakes.ytex.kernel.dao.KernelEvaluationDaoImpl.java

@Override
public KernelEvaluation storeKernelEval(final KernelEvaluation kernelEvaluation) {
    KernelEvaluation kEval = getKernelEval(kernelEvaluation.getCorpusName(), kernelEvaluation.getExperiment(),
            kernelEvaluation.getLabel(), kernelEvaluation.getFoldId(), kernelEvaluation.getParam1(),
            kernelEvaluation.getParam2());
    if (kEval == null) {
        txTemplate.execute(new TransactionCallback<Object>() {

            @Override//from ww w .  j a va 2  s  . c  om
            public Object doInTransaction(TransactionStatus txStatus) {
                try {
                    getSessionFactory().getCurrentSession().save(kernelEvaluation);
                } catch (Exception e) {
                    log.warn(
                            "couldn't save kernel evaluation, maybe somebody else did. try to retrieve kernel eval");
                    if (log.isDebugEnabled())
                        log.debug("error saving kernel eval", e);
                    txStatus.setRollbackOnly();
                }
                return null;
            }
        });
        kEval = getKernelEval(kernelEvaluation.getCorpusName(), kernelEvaluation.getExperiment(),
                kernelEvaluation.getLabel(), kernelEvaluation.getFoldId(), kernelEvaluation.getParam1(),
                kernelEvaluation.getParam2());
    }
    return kEval;
}

From source file:org.apache.ctakes.ytex.kernel.evaluator.CorpusKernelEvaluatorImpl.java

public void evaluateKernelOnCorpus(final Map<Long, Node> instanceIDMap, int nMod, int nSlice,
        boolean evalTest) {
    KernelEvaluation kernelEvaluationTmp = new KernelEvaluation();
    kernelEvaluationTmp.setExperiment(this.getExperiment());
    kernelEvaluationTmp.setFoldId(this.getFoldId());
    kernelEvaluationTmp.setLabel(this.getLabel());
    kernelEvaluationTmp.setCorpusName(this.getName());
    kernelEvaluationTmp.setParam1(getParam1());
    kernelEvaluationTmp.setParam2(getParam2());
    final KernelEvaluation kernelEvaluation = this.kernelEvaluationDao.storeKernelEval(kernelEvaluationTmp);
    final List<Long> documentIds = new ArrayList<Long>();
    final List<Long> testDocumentIds = new ArrayList<Long>();
    loadDocumentIds(documentIds, testDocumentIds, instanceIDQuery);
    if (!evalTest) {
        // throw away the test ids if we're not going to evaluate them
        testDocumentIds.clear();/*from   w ww .j  a  va 2  s  . c  o  m*/
    }
    int nStart = 0;
    int nEnd = documentIds.size();
    int total = documentIds.size();
    if (nMod > 0) {
        nMod = Math.min(total, nMod);
    }
    if (nMod > 0 && nSlice > nMod) {
        log.info("more slices than documents, skipping slice: " + nSlice);
        return;
    }
    if (nMod > 0) {
        int sliceSize = total / nMod;
        nStart = sliceSize * (nSlice - 1);
        if (nSlice != nMod)
            nEnd = nStart + sliceSize;
    }
    for (int i = nStart; i < nEnd; i++) {
        // left hand side of kernel evaluation
        final long instanceId1 = documentIds.get(i);
        if (log.isInfoEnabled())
            log.info("evaluating kernel for instance_id1 = " + instanceId1);
        // list of instance ids right hand side of kernel evaluation
        final SortedSet<Long> rightDocumentIDs = new TreeSet<Long>(testDocumentIds);
        if (i < documentIds.size()) {
            // rightDocumentIDs.addAll(documentIds.subList(i + 1,
            // documentIds.size() - 1));
            rightDocumentIDs.addAll(documentIds.subList(i, documentIds.size()));
        }
        // remove instances already evaluated
        for (KernelEvaluationInstance kEval : this.kernelEvaluationDao
                .getAllKernelEvaluationsForInstance(kernelEvaluation, instanceId1)) {
            rightDocumentIDs.remove(
                    instanceId1 == kEval.getInstanceId1() ? kEval.getInstanceId2() : kEval.getInstanceId1());
        }
        // kernel evaluations for this instance are done in a single tx
        // hibernate can batch insert these
        txTemplate.execute(new TransactionCallback<Object>() {

            @Override
            public Object doInTransaction(TransactionStatus arg0) {
                evalInstance(instanceIDMap, kernelEvaluation, instanceId1, rightDocumentIDs);
                return null;
            }
        });

    }
}

From source file:org.apache.ctakes.ytex.kernel.evaluator.CorpusKernelEvaluatorImpl.java

/**
 * load the document ids from the instanceIDQuery
 * /*w  w  w . j  a  v a 2 s. com*/
 * @param documentIds
 * @param testDocumentIds
 * @param instanceIDQuery
 */
private void loadDocumentIds(final List<Long> documentIds, final List<Long> testDocumentIds,
        final String instanceIDQuery) {
    txTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public List<Integer> doInTransaction(TransactionStatus arg0) {
            jdbcTemplate.query(instanceIDQuery, new RowCallbackHandler() {
                Boolean trainFlag = null;

                /**
                 * <ul>
                 * <li>1st column - document id
                 * <li>2nd column - optional - train/test flag (train = 1)
                 * </ul>
                 */
                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    if (trainFlag == null) {
                        // see how many columns there are
                        // if we have 2 columsn, then we assume that the 2nd
                        // column has the train/test flag
                        // else we assume everything is training data
                        trainFlag = rs.getMetaData().getColumnCount() == 2;
                    }
                    long id = rs.getLong(1);
                    int train = trainFlag.booleanValue() ? rs.getInt(2) : 1;
                    if (train != 0) {
                        documentIds.add(id);
                    } else {
                        testDocumentIds.add(id);
                    }
                }
            });
            return null;
        }
    });
}