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

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

Introduction

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

Prototype

public TransactionTemplate(PlatformTransactionManager transactionManager) 

Source Link

Document

Construct a new TransactionTemplate using the given transaction manager.

Usage

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

public void setTransactionManager(PlatformTransactionManager transactionManager) {
    this.transactionManager = transactionManager;
    txTemplate = new TransactionTemplate(this.transactionManager);
    txTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
}

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  ww . j  a  v a  2  s.  c  o 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 {//from  w ww. j  a v a2 s.c  o  m
        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 {/*w w  w .  j av a 2 s. co  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.DBCollectionReader.java

protected void initDB(String dbDriver, String dbURL) throws ResourceInitializationException {
    if (dbURL != null && dbURL.length() > 0) {
        try {/*from   www  .  ja  v a 2 s  .  com*/

            if (dbDriver == null || dbDriver.length() == 0) {
                dbDriver = ApplicationContextHolder.getYtexProperties().getProperty("db.driver");
            }
            dataSource = new SimpleDriverDataSource((Driver) Class.forName(dbDriver).newInstance(), dbURL);
            txTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
        } catch (InstantiationException e) {
            throw new ResourceInitializationException(e);
        } catch (IllegalAccessException e) {
            throw new ResourceInitializationException(e);
        } catch (ClassNotFoundException e) {
            throw new ResourceInitializationException(e);
        }
    } else {
        txTemplate = (TransactionTemplate) ApplicationContextHolder.getApplicationContext()
                .getBean("txTemplate");
        dataSource = (DataSource) ApplicationContextHolder.getApplicationContext()
                .getBean("collectionReaderDataSource");
    }
    simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
    namedJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}

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.//from www  .  j  a  v a 2  s .c o  m
 * 
 * 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.biz.ServiceDBStore.java

@PostConstruct
public void initStore() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDefDBStore.initStore()");
    }/*from   w w w.j  a v a  2  s  . c o  m*/

    if (!legacyServiceDefsInitDone) {
        synchronized (ServiceDBStore.class) {
            if (!legacyServiceDefsInitDone) {

                if (!RangerConfiguration.getInstance().addAdminResources()) {
                    LOG.error("Could not add ranger-admin resources to RangerConfiguration.");
                }

                TransactionTemplate txTemplate = new TransactionTemplate(txManager);

                final ServiceDBStore dbStore = this;
                predicateUtil = new ServicePredicateUtil(dbStore);

                try {
                    txTemplate.execute(new TransactionCallback<Object>() {
                        @Override
                        public Object doInTransaction(TransactionStatus status) {
                            EmbeddedServiceDefsUtil.instance().init(dbStore);
                            getServiceUpgraded();
                            createGenericUsers();
                            return null;
                        }
                    });
                } catch (Throwable ex) {
                    LOG.fatal("ServiceDefDBStore.initStore(): Failed to update DB: " + ex);
                }

                legacyServiceDefsInitDone = true;
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== ServiceDefDBStore.initStore()");
    }
}

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") + "}");
    }/* w w  w.  j a v  a2 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 w  w  w . j  av  a2  s .c  o m*/
        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.apereo.portal.i18n.RDBMLocaleStore.java

@Autowired
public void setPlatformTransactionManager(
        @Qualifier(BasePortalJpaDao.PERSISTENCE_UNIT_NAME) PlatformTransactionManager platformTransactionManager) {
    this.transactionOperations = new TransactionTemplate(platformTransactionManager);
}