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.ohdsi.webapi.feasibility.PerformFeasibilityTasklet.java

@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext)
        throws Exception {
    Date startTime = Calendar.getInstance().getTime();
    Map<String, Object> jobParams = chunkContext.getStepContext().getJobParameters();
    Integer studyId = Integer.valueOf(jobParams.get("study_id").toString());
    Integer sourceId = Integer.valueOf(jobParams.get("source_id").toString());
    boolean isValid = false;

    DefaultTransactionDefinition requresNewTx = new DefaultTransactionDefinition();
    requresNewTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    TransactionStatus initStatus = this.transactionTemplate.getTransactionManager()
            .getTransaction(requresNewTx);
    FeasibilityStudy study = this.feasibilityStudyRepository.findOne(studyId);

    CohortDefinition resultDef = study.getResultRule();
    if (resultDef != null) {
        CohortGenerationInfo resultInfo = findCohortGenerationInfoBySourceId(resultDef.getGenerationInfoList(),
                sourceId);//from  w ww.  ja v  a 2 s .  c om
        resultInfo.setIsValid(false).setStatus(GenerationStatus.RUNNING).setStartTime(startTime)
                .setExecutionDuration(null);
    }
    StudyGenerationInfo studyInfo = findStudyGenerationInfoBySourceId(study.getStudyGenerationInfoList(),
            sourceId);
    studyInfo.setIsValid(false);
    studyInfo.setStartTime(startTime);
    studyInfo.setStatus(GenerationStatus.RUNNING);

    this.feasibilityStudyRepository.save(study);
    this.transactionTemplate.getTransactionManager().commit(initStatus);

    try {
        final int[] ret = this.transactionTemplate.execute(new TransactionCallback<int[]>() {

            @Override
            public int[] doInTransaction(final TransactionStatus status) {
                return doTask(chunkContext);
            }
        });
        log.debug("Update count: " + ret.length);
        isValid = true;
    } catch (final TransactionException e) {
        isValid = false;
        log.error(e.getMessage(), e);
        throw e;//FAIL job status
    } finally {
        TransactionStatus completeStatus = this.transactionTemplate.getTransactionManager()
                .getTransaction(requresNewTx);
        Date endTime = Calendar.getInstance().getTime();
        study = this.feasibilityStudyRepository.findOne(studyId);
        resultDef = study.getResultRule();
        if (resultDef != null) {
            CohortGenerationInfo resultInfo = findCohortGenerationInfoBySourceId(
                    resultDef.getGenerationInfoList(), sourceId);
            resultInfo = findCohortGenerationInfoBySourceId(resultDef.getGenerationInfoList(), sourceId);
            resultInfo.setIsValid(isValid);
            resultInfo.setExecutionDuration(new Integer((int) (endTime.getTime() - startTime.getTime())));
            resultInfo.setStatus(GenerationStatus.COMPLETE);
        }

        studyInfo = findStudyGenerationInfoBySourceId(study.getStudyGenerationInfoList(), sourceId);
        studyInfo.setIsValid(isValid);
        studyInfo.setExecutionDuration(new Integer((int) (endTime.getTime() - startTime.getTime())));
        studyInfo.setStatus(GenerationStatus.COMPLETE);

        this.feasibilityStudyRepository.save(study);
        this.transactionTemplate.getTransactionManager().commit(completeStatus);
    }

    return RepeatStatus.FINISHED;
}

From source file:com.vladmihalcea.HibernateCriteriaTest.java

private Product getProduct_Mercilessly() {
    return transactionTemplate.execute(new TransactionCallback<Product>() {
        @Override//from ww w. j  a v  a2  s  .co  m
        public Product doInTransaction(TransactionStatus transactionStatus) {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> query = cb.createQuery(Product.class);
            Root<Product> productRoot = query.from(Product.class);

            query.select(productRoot)
                    .where(cb.and(cb.equal(productRoot.get(Product_.code), "tvCode"), cb.gt(
                            productRoot.get(Product_.warehouseProductInfo).get(WarehouseProductInfo_.quantity),
                            50)));
            return entityManager.createQuery(query).getSingleResult();
        }
    });
}

From source file:com.mothsoft.alexis.engine.textual.ParseResponseMessageListener.java

private Term findOrCreateTerm(final String value, final PartOfSpeech partOfSpeech) {
    final int maxTries = 20;
    int retryCount = maxTries;

    Term term = null;/*from   w  ww .j  ava  2 s.c  om*/
    while (term == null && retryCount > 0) {
        retryCount--;

        try {
            term = this.transactionTemplate.execute(new TransactionCallback<Term>() {
                public Term doInTransaction(TransactionStatus status) {
                    try {
                        Term term = ParseResponseMessageListener.this.termDao.find(value, partOfSpeech);
                        if (term == null) {
                            term = new Term(value, partOfSpeech);
                            ParseResponseMessageListener.this.termDao.add(term);
                        }
                        return term;
                    } catch (JpaSystemException e) {
                        throw new TransactionSystemException(e.getLocalizedMessage());
                    }
                }
            });
        } catch (TransactionException e) {
            if (retryCount == 0) {
                logger.error("Retried transaction " + maxTries + " times; failed every time!" + e, e);
                throw e;
            } else {
                logger.warn("Experienced transaction failure: " + e.getLocalizedMessage() + "; will retry!");
                continue;
            }
        }
    }

    return term;
}

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

private void markResourceAsIndexingFailed(final long theId) {
    TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    txTemplate.execute(new TransactionCallback<Void>() {
        @Override/*from  w ww. j a va 2 s .  co  m*/
        public Void doInTransaction(TransactionStatus theStatus) {
            ourLog.info("Marking resource with PID {} as indexing_failed", new Object[] { theId });
            Query q = myEntityManager
                    .createQuery("UPDATE ResourceTable t SET t.myIndexStatus = :status WHERE t.myId = :id");
            q.setParameter("status", INDEX_STATUS_INDEXING_FAILED);
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceTag t WHERE t.myResourceId = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamCoords t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamDate t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamNumber t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery(
                    "DELETE FROM ResourceIndexedSearchParamQuantity t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamString t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamToken t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager
                    .createQuery("DELETE FROM ResourceIndexedSearchParamUri t WHERE t.myResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceLink t WHERE t.mySourceResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            q = myEntityManager.createQuery("DELETE FROM ResourceLink t WHERE t.myTargetResourcePid = :id");
            q.setParameter("id", theId);
            q.executeUpdate();

            return null;
        }
    });
}

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

@DELETE
@Path("/{sensorId}")
public Response deleteSensor(@PathParam("sensorId") Long sensorId) {
    final Sensor existingSensor = device.getSensorById(sensorId);

    new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Object>() {
        @Override/*from  w  ww  .  ja v a2s. co m*/
        public Object doInTransaction(TransactionStatus transactionStatus) {
            device.removeSensor(existingSensor);
            sensorRepository.delete(existingSensor);
            return null;
        }
    });

    return Response.ok().build();
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedProjects(int page, int size) {
    ObjectNode result;//from   w  w  w  .j av  a2 s.c o  m

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            ObjectNode resultNode = Json.newObject();
            long count = 0;
            List<Flow> pagedFlows = new ArrayList<Flow>();
            List<Map<String, Object>> rows = null;
            rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS, (page - 1) * size, size);

            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }
            for (Map row : rows) {
                Flow flow = new Flow();
                flow.id = (Long) row.get("flow_id");
                flow.level = (Integer) row.get("flow_level");
                flow.appId = (Integer) row.get("app_id");
                flow.group = (String) row.get("flow_group");
                flow.name = (String) row.get("flow_name");
                flow.path = (String) row.get("flow_path");
                flow.appCode = (String) row.get("app_code");
                if (StringUtils.isNotBlank(flow.path)) {
                    int index = flow.path.indexOf(":");
                    if (index != -1) {
                        flow.path = flow.path.substring(0, index);
                    }
                }
                Object created = row.get("created_time");
                if (created != null) {
                    flow.created = created.toString();
                }
                Object modified = row.get("modified_time");
                if (modified != null) {
                    flow.modified = row.get("modified_time").toString();
                }

                int jobCount = 0;

                if (flow.id != null && flow.id != 0) {
                    try {
                        jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID,
                                new Object[] { flow.appId, flow.id }, Integer.class);
                        flow.jobCount = jobCount;
                    } catch (EmptyResultDataAccessException e) {
                        Logger.error("Exception = " + e.getMessage());
                    }
                }
                pagedFlows.add(flow);
            }
            resultNode.set("flows", Json.toJson(pagedFlows));
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));

            return resultNode;
        }
    });
    return result;
}

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

/**
 * Tests the use of nested transactions.
 *//* w  w  w. ja v  a  2 s  .  com*/
@Test
public void testNestedTransactions() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    final TransactionTemplate tt = hbc.getTransactionTemplate();

    Serializable empId = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp.setFirstName("Committed");
                    return emp.getId();
                }
            });
            // asserts that UOW is still active after the end of the nested transaction.
            assertTrue("UOW should still be active since outer TX is ongoing.", hbc.isUnitOfWorkActive());
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria empById = DetachedCriteria.forClass(Employee.class);
    empById.add(Restrictions.eq(IEntity.ID, empId));
    Employee emp = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertTrue("Inner transaction should have been committed", "Committed".equals(emp.getFirstName()));

    Serializable emp2Id = tt.execute(new TransactionCallback<Serializable>() {

        @Override
        public Serializable doInTransaction(TransactionStatus status) {
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() {

                @Override
                public Serializable doInTransaction(TransactionStatus nestedStatus) {
                    DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
                    Employee emp2 = hbc.findFirstByCriteria(empCrit, null, Employee.class);
                    emp2.setFirstName("Rollbacked");
                    return emp2.getId();
                }
            });
            // forces rollback of outer TX.
            status.setRollbackOnly();
            return id;
        }
    });
    DetachedCriteria emp2ById = DetachedCriteria.forClass(Employee.class);
    emp2ById.add(Restrictions.eq(IEntity.ID, emp2Id));
    Employee emp2 = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class);
    assertFalse("Inner transaction should have been rollbacked", "Rollbacked".equals(emp2.getFirstName()));

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            City newCity = hbc.getEntityFactory().createEntityInstance(City.class);
            newCity.setName("Test City");

            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            String testZip = nestedTT.execute(new TransactionCallback<String>() {

                @Override
                public String doInTransaction(TransactionStatus nestedStatus) {
                    return "12345";
                }
            });
            newCity.setZip(testZip);
            hbc.registerForUpdate(newCity);
        }
    });

    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            final City randomCity = hbc.findFirstByCriteria(DetachedCriteria.forClass(City.class),
                    EMergeMode.MERGE_KEEP, City.class);
            TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager());
            nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            nestedTT.execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus nestedStatus) {
                    DetachedCriteria cityById = DetachedCriteria.forClass(City.class);
                    cityById.add(Restrictions.eq(IEntity.ID, randomCity.getId()));
                    City innerRandomCity = (City) cityById.getExecutableCriteria(hbc.getHibernateSession())
                            .uniqueResult();
                    // If we reach this point without exception, there is no mix between the inner TX and the outer UOW.
                    // See bug #1118
                }
            });
        }
    });
}

From source file:org.openvpms.archetype.rules.patient.reminder.ReminderRulesTestCase.java

/**
 * Tests the {@link ReminderRules#markMatchingRemindersCompleted(List)} method.
 *//*from   w  w  w .ja v  a  2s.  c o  m*/
@Test
public void testMarkMatchingRemindersCompletedForList() {
    Entity reminderType = ReminderTestHelper.createReminderType();

    Party patient1 = TestHelper.createPatient();
    Party patient2 = TestHelper.createPatient();

    // create reminders for patient1 and patient2
    Act reminder0 = ReminderTestHelper.createReminder(patient1, reminderType);
    Act reminder1 = ReminderTestHelper.createReminder(patient2, reminderType);
    save(reminder0, reminder1);
    checkReminder(reminder0, ReminderStatus.IN_PROGRESS);
    checkReminder(reminder1, ReminderStatus.IN_PROGRESS);

    Act reminder2 = ReminderTestHelper.createReminder(patient1, reminderType);
    Act reminder3 = ReminderTestHelper.createReminder(patient2, reminderType);
    Act reminder3dup = ReminderTestHelper.createReminder(patient2, reminderType); // duplicates reminder3
    final List<Act> reminders = Arrays.asList(reminder2, reminder3, reminder3dup);
    PlatformTransactionManager mgr = (PlatformTransactionManager) applicationContext.getBean("txnManager");
    TransactionTemplate template = new TransactionTemplate(mgr);
    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            save(reminders);
            rules.markMatchingRemindersCompleted(reminders);
            return null;
        }
    });

    checkReminder(reminder0, ReminderStatus.COMPLETED);
    checkReminder(reminder1, ReminderStatus.COMPLETED);
    checkReminder(reminder2, ReminderStatus.IN_PROGRESS);
    checkReminder(reminder3, ReminderStatus.IN_PROGRESS);
    checkReminder(reminder3dup, ReminderStatus.COMPLETED); // as it duplicates reminder3
}

From source file:com.javaetmoi.core.persistence.hibernate.TestLazyLoadingUtil.java

/**
 * Tests the method {@link LazyLoadingUtil#deepHydrate(org.hibernate.Session, Object)
        /* ww w.j a v a  2s .  c o m*/
 **/
@Test
public void deepResolveAddress() {
    // Loading an entity and hydrating its graph is done in a single transaction
    Address dbLyon = transactionTemplate.execute(new TransactionCallback<Address>() {

        public Address doInTransaction(TransactionStatus status) {
            Address address = (Address) sessionFactory.getCurrentSession().get(Address.class, 200);
            LazyLoadingUtil.deepHydrate(sessionFactory.getCurrentSession(), address);
            return address;
        }
    });

    assertEquals("No LazyInitializationException should be thrown", dbLyon.getEmployee().getName(),
            tom.getName());
    assertEquals("Compare in-memory and database loaded addresses", lyon, dbLyon);
    assertEquals("Compare projetcs size", lyon.getEmployee().getProjects().size(),
            dbLyon.getEmployee().getProjects().size());
}

From source file:org.ensembl.gti.seqstore.database.JdbcSeqStore.java

@Override
public long storeGenome(long sessionId, Genome genome) {
    long id;//from   w ww . j  av  a 2s  .  com
    try {
        id = transactionTemplate.execute(new TransactionCallback<Long>() {
            @Override
            public Long doInTransaction(TransactionStatus status) {
                KeyHolder keyHolder = new GeneratedKeyHolder();
                template.update(new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                        PreparedStatement pst = con.prepareStatement(STORE_GENOME_SQL,
                                new String[] { "name", "assembly", "genebuild", "tax_id", "session_id" });
                        pst.setString(1, genome.getGenomeName());
                        pst.setString(2, genome.getAssembly());
                        pst.setString(3, genome.getGenebuild());
                        pst.setInt(4, genome.getTaxId());
                        pst.setLong(5, sessionId);
                        return pst;
                    }
                }, keyHolder);
                return (Long) keyHolder.getKey();
            }
        });
    } catch (DuplicateKeyException e) {
        String msg = "Cannot store genome " + genome.toString() + " as it already exists";
        log.error(msg, e);
        throw new DuplicateSeqObjException(msg, e);
    }
    log.debug("New genome " + id);
    return id;
}