Example usage for org.springframework.transaction.support TransactionTemplate setPropagationBehavior

List of usage examples for org.springframework.transaction.support TransactionTemplate setPropagationBehavior

Introduction

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

Prototype

public final void setPropagationBehavior(int propagationBehavior) 

Source Link

Document

Set the propagation behavior.

Usage

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

/**
 * Tests the use of nested transactions.
 *///from  ww w. jav  a  2 s  . c o m
@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.apache.ctakes.ytex.kernel.KernelUtilImpl.java

@Override
public void fillGramMatrix(final KernelEvaluation kernelEvaluation, final SortedSet<Long> trainInstanceLabelMap,
        final double[][] trainGramMatrix) {
    // final Set<String> kernelEvaluationNames = new HashSet<String>(1);
    // kernelEvaluationNames.add(name);
    // prepare map of instance id to gram matrix index
    final Map<Long, Integer> trainInstanceToIndexMap = createInstanceIdToIndexMap(trainInstanceLabelMap);

    // iterate through the training instances
    for (Map.Entry<Long, Integer> instanceIdIndex : trainInstanceToIndexMap.entrySet()) {
        // index of this instance
        final int indexThis = instanceIdIndex.getValue();
        // id of this instance
        final long instanceId = instanceIdIndex.getKey();
        // get all kernel evaluations for this instance in a new transaction
        // don't want too many objects in hibernate session
        TransactionTemplate t = new TransactionTemplate(this.transactionManager);
        t.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
        t.execute(new TransactionCallback<Object>() {
            @Override// w  w w.  ja v a2 s. co  m
            public Object doInTransaction(TransactionStatus arg0) {
                List<KernelEvaluationInstance> kevals = getKernelEvaluationDao()
                        .getAllKernelEvaluationsForInstance(kernelEvaluation, instanceId);
                for (KernelEvaluationInstance keval : kevals) {
                    // determine the index of the instance
                    Integer indexOtherTrain = null;
                    long instanceIdOther = instanceId != keval.getInstanceId1() ? keval.getInstanceId1()
                            : keval.getInstanceId2();
                    // look in training set for the instance id
                    indexOtherTrain = trainInstanceToIndexMap.get(instanceIdOther);
                    if (indexOtherTrain != null) {
                        trainGramMatrix[indexThis][indexOtherTrain] = keval.getSimilarity();
                        trainGramMatrix[indexOtherTrain][indexThis] = keval.getSimilarity();
                    }
                }
                return null;
            }
        });
    }
    // put 1's in the diagonal of the training gram matrix
    for (int i = 0; i < trainGramMatrix.length; i++) {
        if (trainGramMatrix[i][i] == 0)
            trainGramMatrix[i][i] = 1;
    }
}

From source file:org.apache.ctakes.ytex.kernel.metric.ConceptSimilarityServiceImpl.java

public void init() {
    log.info("begin initialization for concept graph: " + conceptGraphName);
    cg = conceptDao.getConceptGraph(conceptGraphName);
    if (cg == null) {
        log.warn("concept graph null, name: " + conceptGraphName);
    } else {//  w  w w . ja  va  2  s  .  c  om
        initSimilarityMetricMap();
        if (isPreload()) {
            try {
                TransactionTemplate t = new TransactionTemplate(this.transactionManager);
                t.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
                t.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus arg0) {
                        initInfoContent();
                        initCuiTuiMapFromCorpus();
                        return null;
                    }
                });
            } catch (Exception e) {
                log.info("could not initialize cui-tui map: " + e.getMessage()
                        + ".  This is expected if you do not have umls installed in your db.");
            }
        }
    }
    log.info("end initialization for concept graph: " + conceptGraphName);
}

From source file:org.apache.ctakes.ytex.tools.SetupAuiFirstWord.java

public void setupAuiFirstWord() {
    UMLSDao umlsDao = KernelContextHolder.getApplicationContext().getBean(UMLSDao.class);
    TransactionTemplate t = new TransactionTemplate(
            KernelContextHolder.getApplicationContext().getBean(PlatformTransactionManager.class));
    t.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    // delete all records
    // umlsDao.deleteAuiFirstWord();

    // get all auis and their strings
    // restart processing after the last aui we processed.
    // if this is null, then just process everything
    String lastAui = umlsDao.getLastAui();
    List<Object[]> listAuiStr = null;
    do {//from  w  ww .j a va  2s . c o m
        // get the next 10k auis
        listAuiStr = umlsDao.getAllAuiStr(lastAui);
        // put the aui - fword pairs in a list
        List<UmlsAuiFirstWord> listFword = new ArrayList<UmlsAuiFirstWord>(1000);
        for (Object[] auiStr : listAuiStr) {
            String aui = (String) auiStr[0];
            String str = (String) auiStr[1];
            lastAui = aui;
            if (str.length() < 200) {
                try {
                    UmlsAuiFirstWord fw = this.tokenizeStr(aui, str);
                    if (fw == null)
                        log.error("Error tokenizing aui=" + aui + ", str=" + str);
                    else if (fw.getFword().length() > 70)
                        log.debug("fword too long: aui=" + aui + ", str=" + fw.getFword());
                    else if (fw.getTokenizedStr().length() > 250)
                        log.debug("string too long: aui=" + aui + ", str=" + str);
                    else {
                        if (log.isDebugEnabled())
                            log.debug("aui=" + aui + ", fw=" + fw);
                        listFword.add(fw);
                    }
                } catch (Exception e) {
                    log.error("Error tokenizing aui=" + aui + ", str=" + str, e);
                }
            } else {
                log.debug("Skipping aui because str to long: aui=" + aui + ", str=" + str);
            }
        }
        // batch insert
        if (listFword.size() > 0) {
            umlsDao.insertAuiFirstWord(listFword);
            log.info("inserted " + listFword.size() + " rows");
        }
    } while (listAuiStr.size() > 0);
}

From source file:org.apache.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

/**
 * load the map of uima annotation class name to mapper class name from the
 * database./* ww w  .jav  a 2 s  .c om*/
 * 
 * For some reason this is not getting executed within a transaction.
 * Manually wrap the db access in a transaction.
 * 
 * 
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public void afterPropertiesSet() {
    TransactionTemplate txTemplate = new TransactionTemplate(this.getTransactionManager());
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRED);
    txTemplate.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus arg0) {
            Query q = getSessionFactory().getCurrentSession().getNamedQuery("getUimaTypes");
            List<UimaType> uimaTypes = q.list();
            for (UimaType uimaType : uimaTypes) {
                uimaTypeMap.put(uimaType.getUimaTypeName(), uimaType);
            }
            initDocKeyMapping();
            return null;
        }
    });
}

From source file:org.apache.ranger.common.db.RangerTransactionSynchronizationAdapter.java

@Override
public void afterCompletion(int status) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Transaction completed with status {"
                + (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK") + "}");
    }/*www.j a  v a 2 s  .  c  om*/
    /* Thread runnables are expected to be executed only when the status is STATUS_ROLLED_BACK. Currently, executeOnTransactionCompletion()
     * is called only for those changes that are going to be rolled-back by TransactionSynchronizationManager - such
     * as when the operation returns HttpServletResponse.SC_NOT_MODIFIED status.
     */
    //if (status == STATUS_ROLLED_BACK) {
    final List<Runnable> threadRunnables = RUNNABLES.get();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Transaction completed, executing {" + threadRunnables.size() + "} runnables");
    }
    if (threadRunnables != null) {
        try {
            //Create new  transaction
            TransactionTemplate txTemplate = new TransactionTemplate(txManager);
            txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

            txTemplate.execute(new TransactionCallback<Object>() {
                public Object doInTransaction(TransactionStatus status) {
                    for (Runnable runnable : threadRunnables) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Executing runnable {" + runnable + "}");
                        }
                        try {
                            runnable.run();
                        } catch (RuntimeException e) {
                            LOG.error("Failed to execute runnable " + runnable, e);
                            break;
                        }
                    }

                    return null;
                }
            });
        } catch (Exception e) {
            LOG.error("Failed to commit TransactionService transaction", e);
            LOG.error("Ignoring...");
        }
    }

    //}
    RUNNABLES.remove();
}

From source file:org.apache.ranger.service.RangerTransactionService.java

public void executeAfterTransactionComplete(final Runnable task) {
    try {//from   ww w  .jav  a 2  s  .com
        scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                if (task != null) {
                    try {
                        //Create new  transaction
                        TransactionTemplate txTemplate = new TransactionTemplate(txManager);
                        txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

                        txTemplate.execute(new TransactionCallback<Object>() {
                            public Object doInTransaction(TransactionStatus status) {
                                task.run();
                                return null;
                            }
                        });
                    } catch (Exception e) {
                        LOG.error("Failed to commit TransactionService transaction", e);
                        LOG.error("Ignoring...");
                    }
                }
            }
        }, 1000L, MILLISECONDS);
    } catch (Exception e) {
        LOG.error("Failed to schedule TransactionService transaction:", e);
        LOG.error("Ignroing...");
    }
}

From source file:org.fcrepo.camel.FcrepoEndpoint.java

/**
 * Create a template for use in transactions
 *
 * @return a transaction template//from   w w  w  .j av  a  2  s.c om
 */
public TransactionTemplate createTransactionTemplate() {
    final TransactionTemplate transactionTemplate;

    if (getTransactionManager() != null) {
        transactionTemplate = new TransactionTemplate(getTransactionManager());
    } else {
        final FcrepoTransactionManager txMgr = new FcrepoTransactionManager();
        txMgr.setBaseUrl(getBaseUrlWithScheme());
        txMgr.setAuthUsername(getAuthUsername());
        txMgr.setAuthPassword(getAuthPassword());
        txMgr.setAuthHost(getAuthHost());
        transactionTemplate = new TransactionTemplate(txMgr);
    }
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    transactionTemplate.afterPropertiesSet();
    return transactionTemplate;
}

From source file:org.hyperic.hibernate.id.HQMultipleHiLoPerTableGenerator.java

private synchronized Number _generate(final SessionImplementor session, Object obj) throws HibernateException {
    TransactionTemplate transactionTemplate = null;
    if (Bootstrap.hasAppContext()) {
        // We are running in Spring-managed server environment. Suspend the
        // existing Spring-managed transaction and work in a new one.
        transactionTemplate = new TransactionTemplate(
                (PlatformTransactionManager) Bootstrap.getBean("transactionManager"));
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    }//from   w  w w.j a v  a  2 s. c o  m
    if (maxLo < 1) {
        // keep the behavior consistent even for boundary usages
        int val = executeInNewTransaction(transactionTemplate, session);

        if (val == 0) {
            val = executeInNewTransaction(transactionTemplate, session);
        }
        Number num = IdentifierGeneratorFactory.createNumber(val, returnClass);
        if (log.isTraceEnabled()) {
            log.trace(this + " created seq: " + keyValue + " / " + num);
        }
        return num;
    } else if (lo > maxLo) {
        int hival = executeInNewTransaction(transactionTemplate, session);
        lo = (hival == 0) ? 1 : 0;
        hi = hival * (maxLo + 1);
        log.debug("new hi value: " + hival);
    }
    Number num = IdentifierGeneratorFactory.createNumber(hi + lo++, returnClass);
    if (log.isTraceEnabled()) {
        log.trace(this + " created seq: " + keyValue + " / " + num);
    }
    return num;
}