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:org.opennms.ng.dao.support.UpsertTemplate.java

/**
 * After creating the UpsertTemplate call this method to attempt the upsert.
 *///from w  w  w. j  a v  a2 s .  co m
public T execute() {
    TransactionTemplate template = new TransactionTemplate(m_transactionManager);
    template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return template.execute(new TransactionCallback<T>() {

        @Override
        public T doInTransaction(TransactionStatus status) {
            return doUpsert();
        }
    });

}

From source file:com.hs.mail.imap.mailbox.DefaultMailboxManager.java

public Mailbox createMailbox(final long ownerID, final String mailboxName) {
    return (Mailbox) getTransactionTemplate().execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            try {
                MailboxDao dao = DaoFactory.getMailboxDao();
                return dao.createMailbox(ownerID, mailboxName);
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }/*from w  w  w .ja  v a  2 s.c o m*/
        }
    });
}

From source file:org.cleverbus.test.AbstractDbTest.java

protected Message[] createAndSaveMessages(final int messageCount, final MessageProcessor initializer) {
    TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager);
    return tx.execute(new TransactionCallback<Message[]>() {
        @Override/*from   w  w w .j  a  v  a 2 s .  co  m*/
        public Message[] doInTransaction(TransactionStatus status) {
            Message[] messages = new Message[messageCount];
            for (int i = 0; i < messages.length; i++) {
                messages[i] = createMessage(ExternalSystemTestEnum.CRM, ServiceTestEnum.CUSTOMER,
                        "testOperation", "test payload");

                try {
                    initializer.process(messages[i]);
                } catch (Exception exc) {
                    throw new RuntimeException(exc);
                }
                em.persist(messages[i]);
            }
            em.flush();
            return messages;
        }
    });
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Executes the callback inside of a {@link JpaInterceptor} inside of a {@link TransactionCallback}
 *///w  w  w . ja  va  2  s.c om
public final <T> T executeInTransaction(final Callable<T> callable) {
    return execute(new Callable<T>() {
        @Override
        public T call() throws Exception {
            return transactionOperations.execute(new TransactionCallback<T>() {
                @Override
                public T doInTransaction(TransactionStatus status) {
                    try {
                        return callable.call();
                    } catch (RuntimeException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    });
}

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

/**
 * Get the number of sessions in a module
 * /*from   www .j  a  va 2  s . c  om*/
 * @param module the module to check
 * @param includeUnfinished whether to include unfinished module (modules without end time)
 * @return
 */
public long getSessionCount(Module module, final boolean includeUnfinished) {
    final ModuleImpl moduleImpl = (ModuleImpl) module;
    return (Long) moduleImpl.getTransactionTemplate().execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return moduleImpl.getSessionDAO().getSessionCount(moduleImpl, includeUnfinished);
        }
    });
}

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  ww  w . ja  v  a2  s  .  co  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:com.vladmihalcea.HibernateCriteriaTest.java

private List<Product> getProducts_Mercilessly() {
    return transactionTemplate.execute(new TransactionCallback<List<Product>>() {
        @Override/*from  w w  w  .  j a  va 2  s.  c om*/
        public List<Product> doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> product = query.from(Product.class);
            query.select(product);
            query.distinct(true);

            List<Predicate> criteria = new ArrayList<Predicate>();
            criteria.add(cb.like(cb.lower(product.get(Product_.name)), "%tv%"));

            Subquery<Long> subQuery = query.subquery(Long.class);
            Root<Image> infoRoot = subQuery.from(Image.class);
            Join<Image, Product> productJoin = infoRoot.join(Image_.product);
            subQuery.select(productJoin.<Long>get(Product_.id));

            subQuery.where(cb.gt(infoRoot.get(Image_.index), 0));
            criteria.add(cb.in(product.get(Product_.id)).value(subQuery));
            query.where(cb.and(criteria.toArray(new Predicate[criteria.size()])));
            return entityManager.createQuery(query).getResultList();
        }
    });
}

From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java

public <K, T extends Persistable<K>> List<T> loadAll(final Class<T> type, final List<? extends K> identities) {
    List<T> p_objects = _executeTx("loadAll", type, identities, new TransactionCallback<List<T>>() {
        public List<T> doInTransaction(final TransactionStatus status) {
            return getDao(type).loadAll(identities);
        }/*from  www  . jav  a2 s.  c  o m*/
    });

    return p_objects;
}

From source file:com.thoughtworks.go.fixture.PipelineWithRunOnAllJob.java

public Pipeline schedulePipeline(final BuildCause buildCause) {
    return (Pipeline) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            materialRepository.save(buildCause.getMaterialRevisions());
            return PipelineMother.schedule(pipelineConfig(), buildCause);
        }/*  w  w w.  j a v a  2s.c om*/
    });
}

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

private BigInteger importTopicDataForTopic(final Long topicId, final Date startDate, final Date endDate) {
    logger.debug(String.format("Importing topic activity for topic: %d between %s and %s", topicId,
            startDate.toString(), endDate.toString()));

    final String queryString = "SELECT DATE_FORMAT(td.creation_date, '%Y-%m-%d %H:00:00') as the_hour, "
            + " COUNT(td.id) from topic_document td INNER JOIN topic on topic.id = td.topic_id "
            + " WHERE td.creation_date >= ? AND td.creation_date <= ? AND td.topic_id = ? "
            + " GROUP BY the_hour ORDER BY td.creation_date";

    final BigInteger count = this.transactionTemplate.execute(new TransactionCallback<BigInteger>() {
        @Override// w  w w  . j av a  2  s . co m
        public BigInteger doInTransaction(TransactionStatus txStatus) {
            final Query query = TopicActivityDataSetImporter.this.em.createNativeQuery(queryString);
            query.setParameter(1, startDate);
            query.setParameter(2, endDate);
            query.setParameter(3, topicId);

            final List<?> results = query.getResultList();

            if (results == null || results.isEmpty()) {
                return BigInteger.ZERO;
            } else {
                final Object[] array = (Object[]) results.get(0);
                return (BigInteger) array[1];
            }
        }
    });

    logger.debug("Data set point: (" + startDate + ", " + count + ")");

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            TopicActivityDataSet dataSet = TopicActivityDataSetImporter.this.dataSetDao
                    .findTopicActivityDataSet(topicId);

            if (dataSet == null) {
                final DataSetType type = TopicActivityDataSetImporter.this.dataSetTypeDao
                        .findSystemDataSetType(DataSetType.TOPIC_ACTIVITY);
                final Topic topic = TopicActivityDataSetImporter.this.topicDao.get(topicId);
                dataSet = new TopicActivityDataSet(topic, type);
                TopicActivityDataSetImporter.this.em.persist(dataSet);
            }

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

    return count;
}