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.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java

/**
 * Tests sanity check on linked components. See bug #846.
 *///  ww w. ja  v a2  s  . c  o  m
@Test(expected = BackendException.class)
public void testSanityChecksOnComponents() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    final TransactionTemplate tt = hbc.getTransactionTemplate();

    Employee emp = tt.execute(new TransactionCallback<Employee>() {

        /**
         * {@inheritDoc}
         */
        @Override
        public Employee doInTransaction(TransactionStatus status) {
            DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class);
            return (Employee) empCrit.getExecutableCriteria(hbc.getHibernateSession()).list().iterator().next();
        }
    });
    // From here, any modification on employee should result in an exception
    // since this instance of employee is not merged in session.
    // The exception should also occur on component (contact) properties
    // modification.
    emp.getContact().setAddress("test");
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Resets Database.//from   w  w  w .  ja va  2s. c  o  m
 * @param tables {@link String}
 */
protected void truncateTables(final String... tables) {

    TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager);
    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus arg0) {

            EntityManager em = AbstractIntegrationTest.this.entityManager;
            truncateTables(em, Arrays.asList(tables));
            return null;
        }
    });
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Resets Database./*from   w w w .j  ava2 s.  c  om*/
 */
protected void truncateDatabase() {

    TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager);
    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus arg0) {

            EntityManager em = AbstractIntegrationTest.this.entityManager;
            truncateDatabase(em);
            migrateSystemProperties(em);
            return null;
        }
    });
}

From source file:dao.DatasetsDAO.java

public static ObjectNode getPagedDatasetComments(String userName, int id, 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<DatasetComment> pagedComments = getJdbcTemplate().query(GET_COMMENTS_BY_DATASET_ID,
                    new DatasetCommentRowMapper(), id, (page - 1) * size, size);

            long count = 0;
            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }/*from   www. j av a 2s  .  c o m*/

            if (pagedComments != null) {
                for (DatasetComment dc : pagedComments) {
                    if (StringUtils.isNotBlank(userName) && userName.equalsIgnoreCase(dc.authorUserName)) {
                        dc.isAuthor = true;
                    }
                }
            }

            ObjectNode resultNode = Json.newObject();
            resultNode.set("comments", Json.toJson(pagedComments));
            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:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java

@Test
public void test_stack() {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(1L);//from ww w. jav  a2s. c o m
    dbMediaSource.setDriver("com.mysql.jdbc.Driver");
    dbMediaSource.setUsername("otter");
    dbMediaSource.setPassword("otter");
    dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.MYSQL);

    DbDataMedia dataMedia = new DbDataMedia();
    dataMedia.setSource(dbMediaSource);
    dataMedia.setId(1L);
    dataMedia.setName("ljhtable1");
    dataMedia.setNamespace("otter");

    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);

    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();

    // ??
    int minute = 5;
    int nextId = 1;
    final int thread = 10;
    final int batch = 50;
    final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)";

    final CountDownLatch latch = new CountDownLatch(thread);
    ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    for (int sec = 0; sec < minute * 60; sec++) {
        // 
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < thread; i++) {
            final int start = nextId + i * batch;
            executor.submit(new Runnable() {

                public void run() {
                    try {
                        transactionTemplate.execute(new TransactionCallback() {

                            public Object doInTransaction(TransactionStatus status) {
                                JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
                                return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

                                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                                        int id = start + idx;
                                        StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id);
                                        StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null,
                                                RandomStringUtils.randomAlphabetic(1000));
                                        // RandomStringUtils.randomAlphabetic()
                                        long time = new Date().getTime();
                                        StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP,
                                                new Timestamp(time));
                                        StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP,
                                                new Timestamp(time));
                                    }

                                    public int getBatchSize() {
                                        return batch;
                                    }
                                });
                            }
                        });
                    } finally {
                        latch.countDown();
                    }
                }
            });

        }

        long endTime = System.currentTimeMillis();
        try {
            latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (latch.getCount() != 0) {
            System.out.println("perf is not enough!");
            System.exit(-1);
        }
        endTime = System.currentTimeMillis();
        System.out.println("Time cost : " + (System.currentTimeMillis() - startTime));
        try {
            TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        nextId = nextId + thread * batch;
    }
    executor.shutdown();
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Save Client./* w  w  w  .ja v a2 s .c o m*/
 * @param clientid {@link String}
 * @param clientsecret {@link String}
 * @return {@link String}
 */
protected String saveClient(final String clientid, final String clientsecret) {

    TransactionTemplate transactionTemplate = new TransactionTemplate(this.getPlatformTransactionManager());
    return (String) transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(final TransactionStatus arg0) {

            List<OAuthGrantTypes> grantTypes = Arrays.asList(OAuthGrantTypes.AUTHORIZATION_CODE,
                    OAuthGrantTypes.PASSWORD, OAuthGrantTypes.REFRESH_TOKEN);

            AbstractIntegrationTest.this.oauthservice.save(clientid, clientid, clientsecret, grantTypes, false);
            return null;
        }
    });
}

From source file:dao.DatasetsDAO.java

public static Object createFolderAction(final String name, final String path, final String children,
        final Long datasetId, final boolean flag, final Long bindId) {
    TransactionTemplate transactionTemplate = getTransactionTemplate();
    Object object = transactionTemplate.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            int res = 0;
            try {
                // insert the record and get the folder id.
                KeyHolder keyHolder = new GeneratedKeyHolder();
                getJdbcTemplate().update(new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                        PreparedStatement ps = getJdbcTemplate().getDataSource().getConnection()
                                .prepareStatement(CREATE_LOGIC_DATASET_FOLDER,
                                        new String[] { "title", "path" });
                        ps.setString(1, name);
                        ps.setString(2, path);
                        return ps;
                    }//ww  w .ja  v  a2s.c om
                }, keyHolder);
                res = keyHolder.getKey().intValue();
                if (res <= 0)
                    throw new Exception();

                String childrenList = children + (children.length() == 0 ? children : ",") + res;
                int row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_CHILDREN, childrenList, datasetId);
                if (row <= 0)
                    throw new Exception();

                if (!flag) {
                    row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_DATASETID, bindId, 0, res);
                    if (row <= 0)
                        throw new Exception();
                }
            } catch (Exception e) {
                status.setRollbackOnly();
                e.printStackTrace();
            }
            return res;
        }
    });
    return object;
}

From source file:com.formkiq.web.AbstractIntegrationTest.java

/**
 * Setup System./*from  ww  w. j a va 2 s.c  om*/
 * @return {@link Pair}
 */
@SuppressWarnings("unchecked")
private Pair<String, String> setupSystem() {
    TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager);

    Pair<String, String> client = (Pair<String, String>) transactionTemplate.execute(setupSystemTransaction());
    return client;
}

From source file:dao.DatasetsDAO.java

public static ObjectNode getPagedDatasetColumnComments(String userName, int datasetId, int columnId, 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) {

            ObjectNode resultNode = Json.newObject();
            long count = 0;
            int start = (page - 1) * size;
            int end = start + size;
            List<DatasetColumnComment> pagedComments = new ArrayList<DatasetColumnComment>();
            List<Map<String, Object>> rows = null;

            rows = getJdbcTemplate().queryForList(GET_COLUMN_COMMENTS_BY_DATASETID_AND_COLUMNID, datasetId,
                    columnId, start, end);
            for (Map row : rows) {
                Long id = (Long) row.get("id");
                String author = (String) row.get("author");
                String authorEmail = (String) row.get("authorEmail");
                String authorUsername = (String) row.get("authorUsername");
                String text = (String) row.get("text");
                String created = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
                        .format((Timestamp) row.get("created"));
                String modified = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
                        .format((Timestamp) row.get("modified"));
                Long columnId = (Long) row.get("field_id");
                boolean isDefault = (Boolean) row.get("is_default");

                DatasetColumnComment datasetColumnComment = new DatasetColumnComment();
                datasetColumnComment.id = id;
                datasetColumnComment.author = author;
                datasetColumnComment.authorEmail = authorEmail;
                datasetColumnComment.authorUsername = authorUsername;
                datasetColumnComment.text = text;
                datasetColumnComment.created = created;
                datasetColumnComment.modified = modified;
                datasetColumnComment.columnId = columnId;
                datasetColumnComment.isDefault = isDefault;
                pagedComments.add(datasetColumnComment);
            }/*  w ww.j a v  a 2s.  co m*/

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

            if (pagedComments != null) {
                for (DatasetColumnComment dc : pagedComments) {
                    if (StringUtils.isNotBlank(userName) && userName.equalsIgnoreCase(dc.authorUsername)) {
                        dc.isAuthor = true;
                    }
                }
            }

            resultNode.set("comments", Json.toJson(pagedComments));
            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;
}