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:com.wavemaker.runtime.data.salesforce.SalesforceDataServiceManager.java

private Object runInTx(Task task, Map<String, Class<?>> types, boolean named, Object... input) {
    TransactionTemplate txTemplate = new TransactionTemplate(this.txMgr);
    boolean rollbackOnly = task instanceof DefaultRollback && !isTxRunning();
    RunInTx tx = new RunInTx(rollbackOnly, types, named, input);
    if (txLogger.isInfoEnabled()) {
        if (isTxRunning()) {
            txLogger.info("tx is running executing \"" + task.getName() + "\" in current tx");
        } else {// w  w  w.j  a  v a  2s. c  o  m
            txLogger.info("no tx running, wrapping execution of \"" + task.getName() + "\" in tx");
            if (rollbackOnly) {
                txLogger.info("rollback enabled for \"" + task.getName() + "\"");
            }
        }
    }

    Object rtn = txTemplate.execute(tx);
    if (txLogger.isInfoEnabled()) {
        if (isTxRunning()) {
            txLogger.info("tx is running after execution of \"" + task.getName() + "\"");
        } else {
            txLogger.info("tx is not running after execution of \"" + task.getName() + "\"");
        }
    }

    return rtn;
}

From source file:app.web.AbstractCrudController.java

@RequestMapping(value = { "/create", "/edit" }, method = RequestMethod.POST)
public String sendForm(@Valid final T form, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        Class<T> clazz = getTypeClass();
        return clazz.getSimpleName().toLowerCase() + "/form"; // stay on the same view so we can display the validation errors
    }/*w w w. j  ava  2s  .c o  m*/
    if (form.isPersistent()) {
        new TransactionTemplate(transactionManager).execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                form.update();
            }
        });
    } else {
        form.save(); // no need for a transaction?
    }
    // FIXME: find out why the item must be called "form"
    return "redirect:.";
}

From source file:org.nebula.service.processor.RegisterProcessor.java

private PersistenceResult persistInTransaction(final RegisterRequest request, final Registration registration) {
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    Object o = template.execute(new TransactionCallback() {
        @Override//from  ww w  .  ja  v  a 2  s.  c o m
        public Object doInTransaction(TransactionStatus status) {

            PersistenceResult result = null;
            try {
                boolean inserted = false;
                try {
                    registrationMapper.insertRegistration(registration);
                    getLogger().info("inserted Registration id:" + registration.getId());
                    inserted = true;

                    result = new PersistenceResult(true, registration);
                } catch (DuplicateKeyException e) {
                    getLogger().info("Duplicated registration: " + toJson(registration));

                    Registration old = registrationMapper.find(registration);
                    registration.setId(old.getId());
                    registrationMapper.update(registration);

                    result = new PersistenceResult(false, registration);
                }

                // workflow registration?timer
                if (request.getNodeType() == RegisterRequest.NodeType.WORKFLOW) {
                    persistTimer(request, registration);
                }
            } catch (Exception e) {
                status.setRollbackOnly();
                throw new RuntimeException("Persisted registration failure." + toJson(registration), e);
            }
            return result;
        }
    });

    return (PersistenceResult) o;
}

From source file:org.openxdata.server.service.impl.SchedulerServiceImpl.java

@Override
public void start() {
    if (scheduler == null)
        return;/*from ww w . ja v  a  2 s . c  om*/

    /* 
     * Use programatic transaction management because
     * this method is called by spring via reflection.
     * 
     * AOP based transaction management does not work in
     * conjunction with reflection.
     * 
     * @see http://www.eclipse.org/aspectj/doc/released/faq.php#q:reflectiveCalls
     * 
     */
    this.transactionTemplate = new TransactionTemplate(transactionManager);
    this.transactionTemplate.setReadOnly(true);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                List<TaskDef> taskDefs = taskDAO.getTasks();

                if (taskDefs != null) {
                    for (TaskDef taskDef : taskDefs) {
                        scheduleTask(taskDef);
                    }
                }

                scheduler.start();
                log.info("Started Scheduling Service");
            } catch (SchedulerException ex) {
                status.setRollbackOnly();
                throw new UnexpectedException(ex);
            }
        }
    });
}

From source file:org.statefulj.demo.ddd.account.domain.impl.AccountServiceImpl.java

@PostConstruct
private void init() {
    TransactionTemplate tt = new TransactionTemplate(transactionManager);
    tt.execute(new TransactionCallback<Object>() {

        @Override// w  w  w . ja va2  s  . c  om
        public Object doInTransaction(TransactionStatus status) {
            return entityManager.createNativeQuery("CREATE SEQUENCE account_sequence AS BIGINT START WITH 1")
                    .executeUpdate();
        }

    });
}

From source file:org.activiti.engine.impl.cfg.spring.ProcessEngineFactoryBean.java

public ProcessEngine getObject() throws Exception {

    processEngineConfiguration.setLocalTransactions(transactionManager == null);

    if (transactionManager != null) {
        DefaultCommandExecutor commandExecutor = (DefaultCommandExecutor) processEngineConfiguration
                .getCommandExecutor();/*w  w  w  .  ja va2  s .  co m*/
        commandExecutor.addCommandInterceptor(new CommandInterceptor() {

            public <T> T invoke(final CommandExecutor next, final Command<T> command) {
                // TODO: Add transaction attributes
                @SuppressWarnings("unchecked")
                T result = (T) new TransactionTemplate(transactionManager).execute(new TransactionCallback() {

                    public Object doInTransaction(TransactionStatus status) {
                        return next.execute(command);
                    }
                });
                return result;
            }
        });
        processEngineConfiguration.setCommandExecutor(commandExecutor);
    }

    processEngine = (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine();
    refreshProcessResources(processEngine.getRepositoryService(), processResources);
    return processEngine;

}

From source file:org.openremote.beehive.configuration.www.DevicesAPI.java

@POST
public Response createDevice(final DeviceDTOIn deviceDTO) {
    if (account.getDeviceByName(deviceDTO.getName()) != null) {
        return Response.status(Response.Status.CONFLICT)
                .entity(new ErrorDTO(409, "A device with the same name already exists")).build();
    }//from  w  w  w.ja v  a2s  .  c o  m

    return Response.ok(new DeviceDTOOut(
            new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Device>() {
                @Override
                public Device doInTransaction(TransactionStatus transactionStatus) {
                    Device newDevice = new Device();
                    newDevice.setName(deviceDTO.getName());
                    newDevice.setModel(deviceDTO.getModel());
                    newDevice.setVendor(deviceDTO.getVendor());
                    account.addDevice(newDevice);
                    deviceRepository.save(newDevice);
                    return newDevice;
                }
            }))).build();
}

From source file:com.springsource.open.jms.SynchronousMessageTriggerAndPartialRollbackTests.java

@Test(expected = SynchedLocalTransactionFailedException.class)
@DirtiesContext//  w  ww.ja v  a2 s.co m
public void testReceiveMessageUpdateDatabase() throws Throwable {

    /*
     * We can't actually test this using @Transactional because the
     * exception we expect is going to come on commit, which happens in the
     * test framework in that case, outside this method. So we have to use a
     * TransactionTemplate.
     */

    new TransactionTemplate(transactionManager).execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {

            try {
                doReceiveAndInsert();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            return null;

        }

    });

}

From source file:org.works.common.data.layer.datasource.InitializingDataSourceFactoryBean.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;/*from  www.j  ava  2 s .  c om*/
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}