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:com.hmsinc.epicenter.tools.geocoder.FacilityGeocoder.java

/**
 * @param args//ww w . j  ava  2  s  .c  o m
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {

    if (args.length == 5) {

        System.setProperty("db.driver", args[0]);
        System.setProperty("db.url", args[1]);
        System.setProperty("db.type", args[2]);
        System.setProperty("db.user", args[3]);
        System.setProperty("db.password", args[4]);

        appContext = new ClassPathXmlApplicationContext(CONTEXT_FILES);

        final ProviderRepository providerRepository = (ProviderRepository) appContext
                .getBean("providerRepository");
        Validate.notNull(providerRepository);

        final Geocoder geocoder = (Geocoder) appContext.getBean("geocoder");
        Validate.notNull(geocoder);

        final PlatformTransactionManager tm = (PlatformTransactionManager) appContext
                .getBean("transactionManager");
        Validate.notNull(tm);

        final TransactionTemplate template = new TransactionTemplate(tm);

        List<Facility> facilities = (List<Facility>) template.execute(new TransactionCallback() {

            /*
             * (non-Javadoc)
             * 
             * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus)
             */
            public List<Facility> doInTransaction(TransactionStatus status) {
                return providerRepository.getList(Facility.class);
            }

        });

        for (final Facility facility : facilities) {
            if (facility.getGeometry() == null && facility.getAddress1() != null && facility.getCity() != null
                    && facility.getState() != null && facility.getZipcode() != null) {
                template.execute(new TransactionCallbackWithoutResult() {

                    /*
                     * (non-Javadoc)
                     * 
                     * @see org.springframework.transaction.support.TransactionCallbackWithoutResult#doInTransactionWithoutResult(org.springframework.transaction.TransactionStatus)
                     */
                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {

                        System.out.println(facility.toString());
                        final Geometry geom = geocoder.geocode(facility.getAddress1(), facility.getCity(),
                                facility.getState(), facility.getZipcode());
                        if (geom != null) {
                            facility.setGeometry(geom);
                            providerRepository.update(facility);
                        }
                    }
                });

            }

        }

    } else {
        usage();
    }

}

From source file:com.vladmihalcea.CleanDbUtil.java

public static void cleanStore(final TransactionTemplate transactionTemplate,
        final EntityManager entityManager) {
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override/*  w  ww.  j  a  v a  2 s.co  m*/
        public Void doInTransaction(TransactionStatus transactionStatus) {
            entityManager.createQuery("delete from SubVersion where id > 0").executeUpdate();
            entityManager.createQuery("delete from Version where id > 0").executeUpdate();
            entityManager.createQuery("delete from Image where id > 0").executeUpdate();
            entityManager.createQuery("delete from WarehouseProductInfo where id > 0").executeUpdate();
            entityManager.createQuery("delete from Product where id > 0").executeUpdate();
            entityManager.createQuery("delete from Company where id > 0").executeUpdate();
            entityManager.flush();
            return null;
        }
    });
}

From source file:py.una.pol.karaku.test.util.DatabaseUtils.java

/**
 * Ejecuta el DDL pasado, una vez por valor en el parmetro params.
 *
 * <p>/*w ww. j av a  2 s .com*/
 * Ejemplo de uso: Supongamos que deseamos crear una lista de secuencias,
 * entonces utilizamos el siguiente cdigo:
 *
 * <pre>
 * String[] secuencias = new String[] { &quot;seq1&quot;, &quot;seq2&quot;, &quot;seq3&quot; };
 * DatabaseUtils.executeDDL(&quot;Create sequence %d&quot;, context, secuencias);
 * </pre>
 *
 * Lo mismo ejecuta los siguientes comandos:
 *
 * <pre>
 * Create sequence seq1;
 * Create sequence seq2;
 * Create sequence seq3;
 * </pre>
 *
 * <h1>No se debe ejecutar este mtodo dentro de una transaccin, pues el
 * mismo la comitea</h1>
 *
 * @param testContext
 * @param sequences
 */
public static void executeDDL(final String ddl, ApplicationContext testContext, final String[] params) {

    final HibernateTransactionManager tm = getTransactionManager(testContext);
    final TransactionTemplate tt = new TransactionTemplate(tm);
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {

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

                SQLQuery sql = tm.getSessionFactory().getCurrentSession().createSQLQuery(String.format(ddl, s));
                sql.executeUpdate();
            }

        }
    });
}

From source file:dao.SchemaHistoryDAO.java

public static ObjectNode getPagedSchemaDataset(String name, Long datasetId, int page, int size) {
    ObjectNode result = Json.newObject();

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {

            List<SchemaDataset> pagedScripts = null;
            if (StringUtils.isNotBlank(name)) {
                if (datasetId != null && datasetId > 0) {
                    pagedScripts = getJdbcTemplate().query(GET_SPECIFIED_SCHEMA_DATASET_WITH_FILTER,
                            new SchemaDatasetRowMapper(), datasetId, "%" + name + "%", (page - 1) * size, size);

                } else {
                    pagedScripts = getJdbcTemplate().query(GET_PAGED_SCHEMA_DATASET_WITH_FILTER,
                            new SchemaDatasetRowMapper(), "%" + name + "%", (page - 1) * size, size);
                }/* w  w w .  jav  a 2s .c  o  m*/
            } else {
                if (datasetId != null && datasetId > 0) {
                    pagedScripts = getJdbcTemplate().query(GET_SPECIFIED_SCHEMA_DATASET,
                            new SchemaDatasetRowMapper(), datasetId, (page - 1) * size, size);
                } else {
                    pagedScripts = getJdbcTemplate().query(GET_PAGED_SCHEMA_DATASET,
                            new SchemaDatasetRowMapper(), (page - 1) * size, size);
                }
            }

            long count = 0;
            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("datasets", Json.toJson(pagedScripts));

            return resultNode;
        }
    });

    return result;
}

From source file:org.openvpms.component.business.service.archetype.rule.ActSimpleRules.java

/**
 * Creates and saves a new act in a new transaction.
 * On return the supplied act will have a new unsaved relationship to the
 * new act.//from ww  w. j  av a2s  .  co m
 *
 * @param act     the act
 * @param service the archetype service
 * @param manager the transaction manager
 * @see ArchetypeRuleServiceTestCase#testTransactionIsolation
 */
public static void insertNewActInIsolation(Act act, final IArchetypeService service,
        PlatformTransactionManager manager) {
    final Act related = (Act) service.create("act.simple");

    TransactionTemplate template = new TransactionTemplate(manager);
    template.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);

    // save the new act in a new transaction, suspending any current
    // transaction
    template.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            service.save(related);
            return null;
        }
    });

    ActRelationship relationship = (ActRelationship) service.create("actRelationship.simple");
    relationship.setName("a simple relationship");
    relationship.setSource(related.getObjectReference());
    relationship.setTarget(act.getObjectReference());

    related.addActRelationship(relationship);
    act.addActRelationship(relationship);
}

From source file:dao.MetricsDAO.java

public static ObjectNode getPagedMetrics(String dashboardName, String group, Integer page, Integer size,
        String user) {/*from   w ww.j a v a 2  s .  c om*/
    Integer userId = UserDAO.getUserIDByUserName(user);

    final JdbcTemplate jdbcTemplate = getJdbcTemplate();
    javax.sql.DataSource ds = jdbcTemplate.getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);

    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    ObjectNode result;
    final Integer id = userId;
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            List<Map<String, Object>> rows;
            if (StringUtils.isBlank(dashboardName)) {
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS, id, (page - 1) * size, size);
            } else if (StringUtils.isBlank(group)) {
                String dbName;
                if (dashboardName.equals("[Other]")) {
                    dbName = null;
                } else {
                    dbName = dashboardName;
                }
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_NAME, id, dbName, dbName,
                        (page - 1) * size, size);
            } else {
                String dbName;
                if (dashboardName.equals("[Other]")) {
                    dbName = null;
                } else {
                    dbName = dashboardName;
                }
                String grp;
                if (group.equals("[Other]")) {
                    grp = null;
                } else {
                    grp = group;
                }
                rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_AND_GROUP, id, dbName,
                        dbName, grp, grp, (page - 1) * size, size);
            }

            List<Metric> pagedMetrics = new ArrayList<>();
            for (Map row : rows) {
                Metric metric = new Metric();
                metric.id = (int) row.get("metric_id");
                metric.name = (String) row.get("metric_name");
                metric.description = (String) row.get("metric_description");
                metric.refID = (String) row.get("metric_ref_id");
                metric.refIDType = (String) row.get("metric_ref_id_type");
                metric.dashboardName = (String) row.get("dashboard_name");
                metric.category = (String) row.get("metric_category");
                metric.group = (String) row.get("metric_group");
                metric.watchId = (Long) row.get("watch_id");
                pagedMetrics.add(metric);
            }
            long count = 0;
            try {
                count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("metrics", Json.toJson(pagedMetrics));

            return resultNode;
        }
    });

    return result;
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedProjects(int page, int size) {
    ObjectNode result;/*from  w w w.  j  a  v  a 2s  .  c o  m*/

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {
            ObjectNode resultNode = Json.newObject();
            long count = 0;
            List<Flow> pagedFlows = new ArrayList<Flow>();
            List<Map<String, Object>> rows = null;
            rows = getJdbcTemplate().queryForList(GET_PAGED_FLOWS, (page - 1) * size, size);

            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }
            for (Map row : rows) {
                Flow flow = new Flow();
                flow.id = (Long) row.get("flow_id");
                flow.level = (Integer) row.get("flow_level");
                flow.appId = (Integer) row.get("app_id");
                flow.group = (String) row.get("flow_group");
                flow.name = (String) row.get("flow_name");
                flow.path = (String) row.get("flow_path");
                flow.appCode = (String) row.get("app_code");
                if (StringUtils.isNotBlank(flow.path)) {
                    int index = flow.path.indexOf(":");
                    if (index != -1) {
                        flow.path = flow.path.substring(0, index);
                    }
                }
                Object created = row.get("created_time");
                if (created != null) {
                    flow.created = created.toString();
                }
                Object modified = row.get("modified_time");
                if (modified != null) {
                    flow.modified = row.get("modified_time").toString();
                }

                int jobCount = 0;

                if (flow.id != null && flow.id != 0) {
                    try {
                        jobCount = getJdbcTemplate().queryForObject(GET_JOB_COUNT_BY_APP_ID_AND_FLOW_ID,
                                new Object[] { flow.appId, flow.id }, Integer.class);
                        flow.jobCount = jobCount;
                    } catch (EmptyResultDataAccessException e) {
                        Logger.error("Exception = " + e.getMessage());
                    }
                }
                pagedFlows.add(flow);
            }
            resultNode.set("flows", Json.toJson(pagedFlows));
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));

            return resultNode;
        }
    });
    return result;
}

From source file:net.collegeman.grails.e3db.DB.java

public static Object withTransaction(final Closure closure) {
    TransactionTemplate transactionTemplate = new Template().getTransactionTemplate();
    if (transactionTemplate != null) {
        return transactionTemplate.execute(new TransactionCallback() {
            public Object doInTransaction(TransactionStatus transaction) {
                return closure.call();
            }//from   w  ww  .j  a  v  a  2  s.c  om
        });
    } else {
        return closure.call();
    }
}

From source file:dao.DashboardDAO.java

public static ObjectNode getPagedConfidentialDatasetsByManagerId(String managerId, String platform, int page,
        int size) {

    DataSourceTransactionManager tm = new DataSourceTransactionManager(getJdbcTemplate().getDataSource());
    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    return txTemplate.execute(new TransactionCallback<ObjectNode>() {

        public ObjectNode doInTransaction(TransactionStatus status) {
            List<Map<String, Object>> rows = new ArrayList<>(size);
            long count = getPagedDashboardDatasets(managerId, GET_CONFIDENTIAL_DATASETS_FILTER_PLATFORM,
                    platform, null, page, size, rows);

            List<DashboardDataset> datasets = new ArrayList<>();
            for (Map row : rows) {
                DashboardDataset dashboardDataset = new DashboardDataset();
                dashboardDataset.datasetId = (Long) row.get("dataset_id");
                dashboardDataset.datasetName = (String) row.get("name");
                dashboardDataset.ownerId = (String) row.get("owner_id");
                if (dashboardDataset.datasetId != null && dashboardDataset.datasetId > 0) {
                    dashboardDataset.fields = getJdbcTemplate().queryForList(
                            GET_CONFIDENTIAL_FIELDS_BY_DATASET_ID, String.class, dashboardDataset.datasetId);
                }//from  w  w  w. j a  v  a 2s  .c o m
                datasets.add(dashboardDataset);
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("status", "ok");
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("datasets", Json.toJson(datasets));
            return resultNode;
        }
    });
}

From source file:dao.DashboardDAO.java

public static ObjectNode getPagedComplianceDatasetsByManagerId(String managerId, String platform, String option,
        int page, int size) {

    DataSourceTransactionManager tm = new DataSourceTransactionManager(getJdbcTemplate().getDataSource());
    TransactionTemplate txTemplate = new TransactionTemplate(tm);

    return txTemplate.execute(new TransactionCallback<ObjectNode>() {

        public ObjectNode doInTransaction(TransactionStatus status) {
            long count;
            List<Map<String, Object>> rows = new ArrayList<>(size);
            if (StringUtils.isNotBlank(option) && !(option.equalsIgnoreCase(ALL_DATASETS))) {
                count = getPagedDashboardDatasets(managerId, GET_DATASETS_WITH_COMPLIANCE_FILTER_PLATFORM,
                        platform, option, page, size, rows);
            } else {
                count = getPagedDashboardDatasets(managerId, GET_ALL_DATASETS_BY_ID_FILTER_PLATFORM, platform,
                        null, page, size, rows);
            }//from  ww w .  j  ava  2  s  .  c om

            List<DashboardDataset> datasets = new ArrayList<>();
            for (Map row : rows) {
                DashboardDataset dashboardDataset = new DashboardDataset();
                dashboardDataset.datasetId = (Long) row.get("dataset_id");
                dashboardDataset.datasetName = (String) row.get("name");
                dashboardDataset.ownerId = (String) row.get("owner_id");
                if (dashboardDataset.datasetId != null && dashboardDataset.datasetId > 0) {
                    dashboardDataset.fields = getJdbcTemplate().queryForList(
                            GET_COMPLIANCE_FIELDS_BY_DATASET_ID, String.class, dashboardDataset.datasetId);
                }
                datasets.add(dashboardDataset);
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.put("status", "ok");
            resultNode.put("count", count);
            resultNode.put("page", page);
            resultNode.put("itemsPerPage", size);
            resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
            resultNode.set("datasets", Json.toJson(datasets));
            return resultNode;
        }
    });
}