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.works.common.data.layer.datasource.InitializingDataSourceFactoryBean.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;//from  w w  w. j  a v a 2  s .  co m
    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;
        }

    });

}

From source file:com.formkiq.core.service.AssetServiceS3Default.java

@Transactional
@Override/* ww  w.  j ava 2s.com*/
public void afterPropertiesSet() throws Exception {
    TransactionTemplate tmpl = new TransactionTemplate(this.txManager);
    tmpl.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            reloadProperties();
        }
    });
}

From source file:py.una.pol.karaku.test.cucumber.DatabasePopulatorCucumberExecutionListener.java

/**
 * @param testContext/*  w w  w .  j  a  v  a2 s .  co m*/
 * @param file
 * @param slsce
 */
private void executeSQL(TestContext testContext, String file, SingleLineSqlCommandExtractor slsce) {

    BufferedReader br;
    ClassPathResource cpr = getClassPathResource(file, testContext);
    br = _getBr(cpr);
    // File f = new File(scriptPath);
    // FileReader fr = new FileReader(file);

    final String[] commands = slsce.extractCommands(br);
    if (commands == null) {
        return;
    }
    final HibernateTransactionManager tm = getTransactionManager(testContext);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {

            for (String s : commands) {
                if (StringUtils.isInvalid(s)) {
                    continue;
                }

                SQLQuery sql = tm.getSessionFactory().getCurrentSession().createSQLQuery(s.trim());
                sql.executeUpdate();
            }

        }
    });

}

From source file:fi.hsl.parkandride.back.LockDaoTest.java

private <T> Future<T> runTxInOtherThread(TransactionCallback<T> transactionCallback) {
    return Executors.newSingleThreadExecutor().submit(() -> {
        TransactionTemplate txTemplate = new TransactionTemplate(transactionManager);
        txTemplate.setTimeout(1);/*  w w w .  j a v  a 2s .  co m*/
        return txTemplate.execute(transactionCallback);
    });
}

From source file:fr.mycellar.interfaces.facades.stack.StackServiceFacadeImpl.java

@Override
public synchronized void onThrowable(final Throwable throwable) {
    // The transaction must be inside the lock. So we must use a transaction
    // template and not the Transactional annotation.
    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    transactionTemplate.setReadOnly(false);
    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override// w ww . j a  v a2 s  . c  om
        public Object doInTransaction(TransactionStatus status) {
            stackService.onThrowable(throwable);
            return null;
        }
    });
}

From source file:net.solarnetwork.node.dao.jdbc.JdbcSettingDao.java

@Override
public void storeSetting(final String key, final String type, final String value) {
    TransactionTemplate tt = getTransactionTemplate();
    if (tt != null) {
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override//from w  ww . j  a  va 2 s  .com
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                storeSettingInternal(key, type, value, 0);
            }
        });
    } else {
        storeSettingInternal(key, type, value, 0);
    }
}

From source file:org.opennms.ng.dao.support.UpsertTemplate.java

/**
 * After creating the UpsertTemplate call this method to attempt the upsert.
 *///from  ww  w  .  j  a  v a  2s. c  o m
public T execute() {
    TransactionTemplate template = new TransactionTemplate(m_transactionManager);
    template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    return template.execute(new TransactionCallback<T>() {

        @Override
        public T doInTransaction(TransactionStatus status) {
            return doUpsert();
        }
    });

}

From source file:net.solarnetwork.node.dao.jdbc.JdbcSettingDao.java

@Override
public void storeSetting(final Setting setting) {
    TransactionTemplate tt = getTransactionTemplate();
    if (tt != null) {
        tt.execute(new TransactionCallbackWithoutResult() {

            @Override//w  w  w  .j  a v a  2s . com
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                storeSettingInternal(setting.getKey(), setting.getType(), setting.getValue(),
                        SettingFlag.maskForSet(setting.getFlags()));
            }
        });
    } else {
        storeSettingInternal(setting.getKey(), setting.getType(), setting.getValue(),
                SettingFlag.maskForSet(setting.getFlags()));
    }
}

From source file:com.formkiq.core.equifax.service.EquifaxServiceImpl.java

/**
 * Save Equifax Response./*w  w  w  .  j a va 2  s.c  om*/
 * @param cc {@link EquifaxCreditCheck}
 */
private void saveResponse(final EquifaxCreditCheck cc) {

    TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager);

    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            EquifaxServiceImpl.this.em
                    .createNativeQuery("insert into equifax_credit_checks"
                            + "(equifax_credit_check_id, url, request, response, "
                            + "request_type,requester, inserted_date) "
                            + "values (:id,:url,:req,:resp,:type,:requester,:date)")
                    .setParameter("id", UUID.fromString(cc.getCreditcheckid())).setParameter("url", cc.getUrl())
                    .setParameter("req", cc.getRequest()).setParameter("resp", cc.getResponse())
                    .setParameter("type", cc.getRequesttype().name())
                    .setParameter("requester", cc.getRequester()).setParameter("date", new Date())
                    .executeUpdate();
        }
    });
}

From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.java

private int doPerformReindexingPassForResources(final Integer theCount, TransactionTemplate txTemplate) {
    return txTemplate.execute(new TransactionCallback<Integer>() {
        @SuppressWarnings("unchecked")
        @Override/*from w ww.j  a v a2  s.c om*/
        public Integer doInTransaction(TransactionStatus theStatus) {
            TypedQuery<ResourceTable> q = myEntityManager.createQuery(
                    "SELECT t FROM " + ResourceTable.class.getSimpleName() + " t WHERE t.myIndexStatus IS null",
                    ResourceTable.class);

            int maxResult = 500;
            if (theCount != null) {
                maxResult = Math.min(theCount, 2000);
            }

            q.setMaxResults(maxResult);
            List<ResourceTable> resources = q.getResultList();
            if (resources.isEmpty()) {
                return 0;
            }

            ourLog.info("Indexing {} resources", resources.size());

            int count = 0;
            long start = System.currentTimeMillis();

            for (ResourceTable resourceTable : resources) {
                try {
                    /*
                     * This part is because from HAPI 1.5 - 1.6 we changed the format of forced ID to be "type/id" instead of just "id"
                     */
                    ForcedId forcedId = resourceTable.getForcedId();
                    if (forcedId != null) {
                        if (isBlank(forcedId.getResourceType())) {
                            ourLog.info("Updating resource {} forcedId type to {}", forcedId.getForcedId(),
                                    resourceTable.getResourceType());
                            forcedId.setResourceType(resourceTable.getResourceType());
                            myForcedIdDao.save(forcedId);
                        }
                    }

                    final IBaseResource resource = toResource(resourceTable, false);

                    @SuppressWarnings("rawtypes")
                    final IFhirResourceDao dao = getDao(resource.getClass());

                    dao.reindex(resource, resourceTable);
                } catch (Exception e) {
                    ourLog.error("Failed to index resource {}: {}",
                            new Object[] { resourceTable.getIdDt(), e.toString(), e });
                    throw new ReindexFailureException(resourceTable.getId());
                }
                count++;
            }

            long delay = System.currentTimeMillis() - start;
            long avg = (delay / resources.size());
            ourLog.info("Indexed {} / {} resources in {}ms - Avg {}ms / resource",
                    new Object[] { count, resources.size(), delay, avg });

            return resources.size();
        }
    });
}