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

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

Introduction

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

Prototype

@Override
    @Nullable
    public <T> T execute(TransactionCallback<T> action) throws TransactionException 

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//w ww. ja  va  2s.  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   ww w  .j ava  2s.  co  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.uima.mapper.DocumentMapperServiceImpl.java

/**
 * load the map of uima annotation class name to mapper class name from the
 * database./* w ww . j  a  v  a2  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.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/*from  w w w .ja  v  a 2s.c o  m*/
        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 a2 s .co  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 . jav a2 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();
}

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

public void executeAfterTransactionComplete(final Runnable task) {
    try {//from   w w  w  . j  a va 2s  .  c om
        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.bremersee.pagebuilder.example.service.PersonServiceImpl.java

@PostConstruct
public void init() {
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override//from  w ww .j a  va 2  s. c o m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            personRepository
                    .save(new Person("Heinrich", "Heine", new Address("Rue de Chanson", "Paris", "12345")));
            personRepository.save(
                    new Person("Virginia", "Woolf", new Address("Mrs Dalloway Street", "London", "1882")));
            personRepository
                    .save(new Person("Thomas", "Mann", new Address("Buddenbrooks Str. 3", "Lbeck", "23552")));
            personRepository.save(new Person("Malcomlm", "Lowry",
                    new Address("Under the Popocatpetl", "Quauhnhuac", "1947")));
            personRepository.save(new Person("Annete von", "Droste-Hlshoff",
                    new Address("Im Grase 8", "Gievenbeck", "1848")));
            personRepository.save(
                    new Person("Wilhelm", "Raabe", new Address("Sperlingsgasse 33", "Braunschweig", "38102")));
            personRepository.save(
                    new Person("Klaus", "Mann", new Address("Mephistopheles Linje 2", "Hamburg", "6789")));
            personRepository.save(new Person("Guillermo Cabrera", "Infante",
                    new Address("Nachtigallengasse 18", "Havanna", "1958")));
            personRepository
                    .save(new Person("James", "Joyce", new Address("Eccles Street No. 7", "Dublin", "1606")));
            personRepository
                    .save(new Person("Heinrich", "Mann", new Address("Unter dem Tan 66", "Lbeck", "23552")));
        }
    });
}

From source file:org.cleverbus.core.common.asynch.queue.MessagePollExecutorTest.java

@Before
public void prepareData() {
    // set failed limit
    setPrivateField(messagesPool, "partlyFailedInterval", 0);
    setPrivateField(messagesPool, "postponedInterval", 0);
    setPrivateField(messagePollExecutor, "targetURI", "mock:test");
    setPrivateField(messagePollExecutor, "postponedIntervalWhenFailed", 0);

    // firstly commit messages to DB (we can commit because we have embedded DB for tests only)
    TransactionTemplate txTemplate = new TransactionTemplate(jpaTransactionManager);
    txTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override//from w  ww  . j a va 2s .c o m
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            insertNewMessage("1234_4567", MsgStateEnum.POSTPONED, false);
            insertNewMessage("1234_4567_8", MsgStateEnum.PARTLY_FAILED, false, FUNNEL_VALUE);
            insertNewMessage("1234_4567_9", MsgStateEnum.PARTLY_FAILED, false, "somethingElse");
        }
    });
}

From source file:org.foxbpm.rest.service.api.model.ModelsResouce.java

@Post
public String deploy(Representation entity) {
    FileOutputStream fileOutputStream = null;
    final Map<String, InputStream> resourceMap = new HashMap<String, InputStream>();
    InputStream is = null;/*from  w  w  w.j  av  a 2  s. c  o  m*/
    try {
        File file = File.createTempFile(System.currentTimeMillis() + "flowres", ".zip");

        fileOutputStream = new FileOutputStream(file);
        DiskFileItemFactory factory = new DiskFileItemFactory();
        RestletFileUpload upload = new RestletFileUpload(factory);
        List<FileItem> items = null;
        try {
            items = upload.parseRepresentation(entity);
        } catch (FileUploadException e) {
            throw new FoxBPMException("??");
        }
        FileItem fileItem = items.get(0);
        fileItem.write(file);

        String sysTemp = System.getProperty("java.io.tmpdir");
        final File targetDir = new File(sysTemp + File.separator + "ModelsTempFile");
        targetDir.mkdirs();
        FileUtil.unZip(file.getPath(), targetDir.getPath());

        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(
                DBUtils.getDataSource());
        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    ModelService modelService = FoxBpmUtil.getProcessEngine().getModelService();
                    for (File tmpFile : targetDir.listFiles()) {
                        if (tmpFile.isDirectory()) {
                            DeploymentBuilder deploymentBuilder = modelService.createDeployment();
                            String fileName = tmpFile.getName();
                            if (fileName.indexOf(SEP) == -1) {
                                throw new FoxBPMException("??");
                            }
                            //????  insert-processExpens-1?  insert??processExpens?key,1?
                            String operation = fileName.substring(0, fileName.indexOf(SEP));
                            String processKey = fileName.substring(fileName.indexOf(SEP) + 1,
                                    fileName.lastIndexOf(SEP));
                            int version = Integer.parseInt(fileName.substring(fileName.lastIndexOf(SEP) + 1));
                            File[] files = tmpFile.listFiles();
                            for (File t : files) {
                                InputStream input = new FileInputStream(t);
                                //map?
                                resourceMap.put(t.getName(), input);
                                deploymentBuilder.addInputStream(t.getName(), input, version);
                            }
                            if (PREFIX_ADD.equals(operation)) {
                                deploymentBuilder.deploy();
                            } else if (PREFIX_UPDATE.equals(operation)) {
                                ProcessDefinition processDefinition = null;
                                processDefinition = modelService.getProcessDefinition(processKey, version);
                                if (processDefinition != null) {
                                    String deploymentId = processDefinition.getDeploymentId();
                                    deploymentBuilder.updateDeploymentId(deploymentId);
                                }
                                deploymentBuilder.deploy();
                            } else if (PREFIX_DELETE.equals(operation)) {
                                ProcessDefinition processDefinitionNew = modelService
                                        .getProcessDefinition(processKey, version);
                                if (processDefinitionNew != null) {
                                    String deploymentId = processDefinitionNew.getDeploymentId();
                                    modelService.deleteDeployment(deploymentId);
                                } else {
                                    log.warn("??key:" + processKey + "version:" + version
                                            + "??");
                                }
                            } else if ("NotModify".equals(operation)) {
                                log.debug(processKey + "????");
                            } else {
                                throw new FoxBPMException("??" + operation);
                            }
                        }
                    }
                } catch (Exception ex) {
                    if (ex instanceof FoxBPMException) {
                        throw (FoxBPMException) ex;
                    } else {
                        throw new FoxBPMException("?", ex);
                    }
                }
            }
        });
        setStatus(Status.SUCCESS_CREATED);
    } catch (Exception e) {
        if (e instanceof FoxBPMException) {
            throw (FoxBPMException) e;
        }
        throw new FoxBPMException(e.getMessage(), e);
    } finally {
        if (fileOutputStream != null) {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                log.error("?", e);
            }
        }
        for (String name : resourceMap.keySet()) {
            InputStream isTmp = resourceMap.get(name);
            if (isTmp != null) {
                try {
                    isTmp.close();
                } catch (IOException e) {
                    log.error("?", e);
                }
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return null;
}