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.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//from w w w  . j a  v a2 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 {/*w  w w.j a  va 2 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.kernel.SparseDataExporterImpl.java

/**
 * //w ww. j a va 2s  . c o m
 * @param sql
 *            result set has 3 columns. 1st column - integer - instance id.
 *            2nd column - word. 3rd column - word value.
 * @param instanceWordMap
 *            map of instance id to word-word value.
 * @param wordValueMap
 *            map of word to valid values for the word.
 * @return populate maps with results of query.
 */
protected void getNominalInstanceWords(final String sql, final String prepareScript,
        final String prepareScriptDelimiter, final SparseData sparseData, final Map<String, Object> params) {
    txTemplateNew.execute(new TransactionCallback<Object>() {

        // new PreparedStatementCreator() {
        // @Override

        // public PreparedStatement createPreparedStatement(
        // Connection conn) throws SQLException {
        // return conn.prepareStatement(sql,
        // ResultSet.TYPE_FORWARD_ONLY,
        // ResultSet.CONCUR_READ_ONLY);
        // }
        //
        // } @Override
        public Object doInTransaction(TransactionStatus txStatus) {
            prepare(prepareScript, prepareScriptDelimiter, params);
            namedJdbcTemplate.query(sql, params, new RowCallbackHandler() {

                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    long instanceId = rs.getLong(1);
                    String word = rs.getString(2);
                    String wordValue = rs.getString(3);
                    addNominalWordToInstance(sparseData, instanceId, word, wordValue);
                }
            });
            return null;
        }
    });
}

From source file:org.apache.ctakes.ytex.kernel.SparseDataExporterImpl.java

/**
 * //from  w w w  . j av a 2  s . c o m
 * @param sql
 *            result 1st column: instance id, 2nd column: word, 3rd column:
 *            numeric word value
 * @param instanceNumericWords
 *            map of instance id - [map word - word value] to be populated
 */
protected void getNumericInstanceWords(final String sql, final String prepareScript,
        final String prepareScriptDelimiter, final SparseData sparseData, final Map<String, Object> params) {
    txTemplateNew.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus txStatus) {
            prepare(prepareScript, prepareScriptDelimiter, params);
            namedJdbcTemplate.query(sql, params
            // new PreparedStatementCreator() {
            //
            // @Override
            // public PreparedStatement createPreparedStatement(
            // Connection conn) throws SQLException {
            // return conn.prepareStatement(sql,
            // ResultSet.TYPE_FORWARD_ONLY,
            // ResultSet.CONCUR_READ_ONLY);
            // }
            //
            // }
            , new RowCallbackHandler() {

                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    long instanceId = rs.getLong(1);
                    String word = rs.getString(2);
                    double wordValue = rs.getDouble(3);
                    addNumericWordToInstance(sparseData, instanceId, word, wordValue);
                }
            });
            return null;
        }

    });
}

From source file:org.apache.ctakes.ytex.uima.DBCollectionReader.java

protected void loadDocumentIds() {
    if (listDocumentIds == null) {
        listDocumentIds = txTemplate.execute(new TransactionCallback<List<Map<String, Object>>>() {

            @Override//from  ww  w .  ja  va  2s  .  c  o  m
            public List<Map<String, Object>> doInTransaction(TransactionStatus arg0) {
                return simpleJdbcTemplate.queryForList(queryGetDocumentKeys);
            }
        });
        i = 0;
    }
}

From source file:org.apache.ctakes.ytex.uima.DBCollectionReader.java

protected void getDocumentById(final JCas aCAS, final Map<String, Object> id) {
    Map<String, Object> idMapTmp = id;
    if (this.isKeyNameToLowerCase()) {
        idMapTmp = new HashMap<String, Object>();
        for (Map.Entry<String, Object> e : id.entrySet()) {
            idMapTmp.put(e.getKey().toLowerCase(), e.getValue());
        }//  w w w  . ja v a2s  . c o  m
    }
    final Map<String, Object> idQuery = idMapTmp;
    this.txTemplate.execute(new TransactionCallback<Object>() {

        @Override
        public Object doInTransaction(TransactionStatus arg0) {
            namedJdbcTemplate.query(queryGetDocument, idQuery, new RowCallbackHandler() {
                boolean bFirstRowRead = false;

                @Override
                public void processRow(ResultSet rs) throws SQLException {
                    if (!bFirstRowRead) {
                        LobHandler lobHandler = new DefaultLobHandler();
                        String clobText = lobHandler.getClobAsString(rs, 1);
                        aCAS.setDocumentText(clobText);
                        bFirstRowRead = true;
                    } else {
                        log.error("Multiple documents for document key: " + idQuery);
                    }
                }
            });
            return null;
        }
    });
}

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./* w w  w.j  av  a 2s. com*/
 * 
 * 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.ctakes.ytex.uima.mapper.DocumentMapperServiceImpl.java

public Integer saveDocument(final JCas jcas, final String analysisBatch, final boolean bStoreDocText,
        final boolean bStoreCAS, final boolean bInsertAnnotationContainmentLinks,
        final Set<String> setTypesToIgnore) {
    if (log.isTraceEnabled())
        log.trace("begin saveDocument");
    // communicate options to mappers using thread local variable
    final DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(
            TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    txDef.setIsolationLevel("orcl".equals(this.dbType) ? TransactionDefinition.ISOLATION_READ_COMMITTED
            : TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    final TransactionTemplate txTemplate = new TransactionTemplate(this.getTransactionManager(), txDef);
    final int documentId = txTemplate.execute(new TransactionCallback<Integer>() {

        @Override// w ww . j a  v a 2 s  .com
        public Integer doInTransaction(TransactionStatus arg0) {
            Document doc = createDocument(jcas, analysisBatch, bStoreDocText, bStoreCAS);
            sessionFactory.getCurrentSession().save(doc);
            // make sure the document has been saved
            getSessionFactory().getCurrentSession().flush();
            saveAnnotationsHib(jcas, bInsertAnnotationContainmentLinks, setTypesToIgnore, doc);
            extractAndSaveDocKey(jcas, doc);
            return doc.getDocumentID();
        }
    });
    if (log.isTraceEnabled())
        log.trace("end saveDocument");
    return documentId;
}

From source file:org.apache.ranger.biz.ServiceDBStore.java

@PostConstruct
public void initStore() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDefDBStore.initStore()");
    }//from   w  w w .  jav  a  2s.  com

    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  av  a 2 s .  c o  m
    /* 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();
}