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.apereo.portal.jdbc.DatabaseMetaDataImpl.java

public void afterPropertiesSet() throws Exception {
    this.transactionTemplate = new TransactionTemplate(this.transactionManager);
    this.transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    this.transactionTemplate.setReadOnly(true);
    this.transactionTemplate.afterPropertiesSet();

    this.runDatabaseTests();
    if (LOG.isDebugEnabled())
        LOG.debug(this.toString());
}

From source file:org.axonframework.eventhandling.scheduling.quartz.QuartzTableMaker.java

@Transactional
@PostConstruct//from   w w  w. j  a v  a2s.  co m
public void createTables() {
    new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            executeCreateSQL();
        }
    });
}

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 w  w . j  a  v  a 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  w w. ja  v a2s .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.fcrepo.camel.FcrepoEndpoint.java

/**
 * Create a template for use in transactions
 *
 * @return a transaction template/* w  ww  . j  a v  a  2s.  c  o m*/
 */
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.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;/*w  w w  .  ja  v  a  2 s  .  co 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;
}

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  www. 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;
}

From source file:org.jasig.portal.events.aggr.PortalEventAggregationManagerImpl.java

@Autowired
public void setAggrEventsPlatformTransactionManager(
        @Qualifier("aggrEvents") PlatformTransactionManager transactionManager) {
    final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.afterPropertiesSet();
    this.aggrEventsTransactionOperations = transactionTemplate;
}

From source file:org.jasig.portal.layout.simple.RDBMUserLayoutStore.java

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

    final DefaultTransactionDefinition nextStructTransactionDefinition = new DefaultTransactionDefinition();
    nextStructTransactionDefinition/*from  www  .  j av a 2  s . c o  m*/
            .setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRES_NEW);
    this.nextStructTransactionOperations = new TransactionTemplate(platformTransactionManager,
            nextStructTransactionDefinition);
}

From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java

@Override
public List<EvaluatedSuccessIndicatorTO> getForPerson(final UUID personId, final ObjectStatus status)
        throws ObjectNotFoundException {

    // Elaborate transaction management workaround b/c we can't avoid opening a transaction, but any exception
    // that crosses a transactional boundary in the code will mark the transaction as rollback only, which is
    // fine except that if we just tag this method with @Transactional(readOnly=true), the transaction manager
    // will still attempt a commit if the exception doesn't exit all the way out of this method (which is
    // what we usually want in this specific case - we want to try to return as many indicators as we can). And
    // if you attempt to commit a transaction marked as rollback only, you get a
    // org.springframework.transaction.UnexpectedRollbackException
    TransactionTemplate transactionTemplate = new TransactionTemplate(platformTransactionManager);
    transactionTemplate.setReadOnly(true);
    final AtomicReference<List<EvaluatedSuccessIndicatorTO>> rsltHolder = new AtomicReference<>();
    final AtomicReference<ObjectNotFoundException> onfeHolder = new AtomicReference<>();
    try {//from   w  w w .j  av a 2  s.com
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus txnStatus) {
                try {
                    getForPersonInTransaction(personId, status, rsltHolder);
                } catch (ObjectNotFoundException e) {
                    onfeHolder.set(e);
                    throw new RuntimeException("Rolling back transaction", e);
                }
            }
        });
    } catch (UnexpectedRollbackException e) {
        // nothing to be done, totally normal. see comments above.
    } catch (RuntimeException e) {
        if (onfeHolder.get() == null) {
            throw e;
        } // otherwise it's just us, rolling back the transaction, nothing to be done, totally normal
    }

    if (onfeHolder.get() != null) {
        throw onfeHolder.get();
    }

    return rsltHolder.get();
}