Example usage for org.springframework.transaction.support TransactionCallback TransactionCallback

List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback

Introduction

In this page you can find the example usage for org.springframework.transaction.support TransactionCallback TransactionCallback.

Prototype

TransactionCallback

Source Link

Usage

From source file:com.vladmihalcea.HibernateBagDuplicateTest.java

protected Long cleanAndSaveParent() {
    return transactionTemplate.execute(new TransactionCallback<Long>() {
        @Override//from  www .ja v a2 s . c  o  m
        public Long doInTransaction(TransactionStatus transactionStatus) {
            entityManager.createQuery("delete from Child where id > 0").executeUpdate();
            entityManager.createQuery("delete from Parent where id > 0").executeUpdate();
            assertTrue(entityManager.createQuery("from Parent").getResultList().isEmpty());
            Parent parent = new Parent();
            entityManager.persist(parent);
            entityManager.flush();
            return parent.getId();
        }
    });
}

From source file:com.vladmihalcea.HibernateEqualsHashCodeTest.java

@Test
public void testChildObjects() {

    final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() {
        @Override/*  w w  w .ja  v a  2  s .  c om*/
        public Long doInTransaction(TransactionStatus transactionStatus) {

            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);

            Product product = new Product("tvCode");
            product.setName("TV");
            product.setCompany(company);

            Image frontImage = new Image();
            frontImage.setName("front image");
            frontImage.setIndex(0);

            Image sideImage = new Image();
            sideImage.setName("side image");
            sideImage.setIndex(1);

            product.addImage(frontImage);
            product.addImage(sideImage);

            WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
            warehouseProductInfo.setQuantity(101);
            product.addWarehouse(warehouseProductInfo);

            entityManager.persist(product);
            return product.getId();
        }
    });

    Product product = transactionTemplate.execute(new TransactionCallback<Product>() {
        @Override
        public Product doInTransaction(TransactionStatus transactionStatus) {
            return entityManager
                    .createQuery("select p " + "from Product p " + "left join fetch p.images i "
                            + "where p.id = :productId", Product.class)
                    .setParameter("productId", productId).getSingleResult();
        }
    });
    Image frontImage = new Image();
    frontImage.setName("front image");
    frontImage.setProduct(product);
    frontImage.setIndex(0);
    assertTrue(product.getImages().contains(frontImage));

    List<Image> images = transactionTemplate.execute(new TransactionCallback<List<Image>>() {
        @Override
        public List<Image> doInTransaction(TransactionStatus transactionStatus) {
            return entityManager.createQuery("select i from Image i ", Image.class).getResultList();
        }
    });
    try {
        assertTrue(new HashSet<Image>(images).contains(frontImage));
        fail("Should have thrown LazyInitializationException!");
    } catch (LazyInitializationException expected) {

    }

}

From source file:se.inera.intyg.intygstjanst.web.integration.test.CertificateResource.java

@DELETE
@Path("/")
@Produces(MediaType.APPLICATION_JSON)/*from  w w  w  .  ja v a 2  s  .com*/
public Response deleteAllCertificates() {
    return transactionTemplate.execute(new TransactionCallback<Response>() {
        public Response doInTransaction(TransactionStatus status) {
            try {
                @SuppressWarnings("unchecked")
                List<Certificate> certificates = entityManager.createQuery("SELECT c FROM Certificate c")
                        .getResultList();
                for (Certificate certificate : certificates) {
                    if (certificate.getOriginalCertificate() != null) {
                        entityManager.remove(certificate.getOriginalCertificate());
                    }
                    entityManager.remove(certificate);
                }

                // Also delete any SjukfallCertificates
                List<SjukfallCertificate> sjukfallCertificates = entityManager
                        .createQuery("SELECT c FROM SjukfallCertificate c", SjukfallCertificate.class)
                        .getResultList();
                for (SjukfallCertificate sjukfallCert : sjukfallCertificates) {
                    entityManager.remove(sjukfallCert);
                }

                return Response.ok().build();
            } catch (Throwable t) {
                status.setRollbackOnly();
                LOGGER.warn("delete all certificates failed: " + t.getMessage());
                return Response.serverError().build();
            }
        }
    });
}

From source file:com.github.ferstl.spring.jdbc.oracle.DatabaseConfiguration.java

private void initDatabase(final JdbcTemplate jdbcTemplate) {
    TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager());
    trxTemplate.execute(new TransactionCallback<int[]>() {

        @Override// w w  w  .j a v a  2s  . c  o  m
        public int[] doInTransaction(TransactionStatus status) {
            List<Object[]> batchArgs = new ArrayList<>(NUMBER_OF_ROWS);
            for (int i = 0; i < NUMBER_OF_ROWS; i++) {
                int value = i + 1;
                batchArgs.add(new Object[] { String.format("Value_%05d", value), value });
            }
            return jdbcTemplate.batchUpdate(INSERT_SQL, batchArgs);
        }
    });
}

From source file:jp.go.aist.six.util.core.persist.castor.CastorDatastore.java

public <K, T extends Persistable<K>> T sync(final Class<T> type, final T object) {
    T p_object = _executeTx("sync", type, object, new TransactionCallback<T>() {
        public T doInTransaction(final TransactionStatus status) {
            return getDao(type).sync(object);
        }/*ww w  . j  av a  2  s  .  c om*/
    });

    return p_object;
}

From source file:org.pentaho.custom.authentication.provider.userroledao.hibernate.UserRoleDaoTransactionDecorator.java

@SuppressWarnings("unchecked")
public List<IRole> getRoles() throws UncategorizedUserRoleDaoException {
    return (List<IRole>) transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            return userRoleDao.getRoles();
        }//from ww  w.j  a  va2  s.c  o m
    });
}

From source file:org.ambraproject.user.EnsureUserAccountInterceptor.java

/**
 * Check for a user matching the SSO ticket, if one exists.  Forwards to new profile page if no matching user exists.
 * <p/>//from   w  ww .j ava  2  s.co m
 * The work flow is as such:
 * <p/>
 * 1. Check if there is a ticket from CAS
 * If not, then we do nothing.
 * If there is, then we:
 * 2. Check if a user object is in the session.
 * a. If not, look up the user in the database, and put it in the session.
 * i.  if the user is not in the database, this must be a new profile.  forward to profile creation page.
 * 3. Update the database to ensure that the email address on file for this user matches the one from CAS
 * TODO: this next step may be deprecated
 * 4. Check if the user object in the session has a display name
 * a. If not, the user is an old account.  forward to the update profile page
 *
 * @param actionInvocation
 * @return
 * @throws Exception
 */
public String intercept(final ActionInvocation actionInvocation) throws Exception {
    log.debug("ensure user account interceptor called");

    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();

    //STEP 1: check if there is an auth id from cas
    final String authId = (String) session.get(AUTH_KEY);
    if (authId == null) {
        //No auth id, nothing to do here
        if (log.isDebugEnabled()) {
            log.debug("no single sign on user key");
            log.debug("ticket is: " + session.get(SINGLE_SIGNON_RECEIPT));
        }
        return actionInvocation.invoke();
    } else {
        //STEP 2: check if there's a user object in the session
        UserProfile ambraUser = (UserProfile) session.get(AMBRA_USER_KEY);
        if (ambraUser == null) {
            //No user object, so we must just be returning from CAS.  Look up the user in the db, and record their login
            final HttpServletRequest request = ServletActionContext.getRequest();
            ambraUser = (UserProfile) new TransactionTemplate(transactionManager)
                    .execute(new TransactionCallback() {
                        @Override
                        public Object doInTransaction(TransactionStatus transactionStatus) {
                            return userService.login(authId, new UserLogin(request.getRequestedSessionId(), //session id
                                    request.getRemoteAddr(), //ip
                                    request.getHeader("user-agent") //user-agent
                            ));
                        }
                    });
            if (ambraUser == null) {
                //No matching user in the database. redirect to the profile creation page
                log.debug("This is a new user with auth id: {}", authId);
                return ReturnCode.NEW_PROFILE;
            }
            //put the user in the session
            session.put(AMBRA_USER_KEY, ambraUser);
        }

        //STEP 3: make sure that ambra's email address matches the one from CAS
        String emailFromCAS = (String) session.get(SINGLE_SIGNON_EMAIL_KEY);
        if (emailFromCAS == null) {
            emailFromCAS = userService.fetchUserEmailFromCas(authId);
            session.put(SINGLE_SIGNON_EMAIL_KEY, emailFromCAS);
        }
        if (ambraUser.getEmail() == null || (!ambraUser.getEmail().equals(emailFromCAS))) {
            userService.updateEmail(ambraUser.getID(), emailFromCAS);
        }

        //STEP 4: Check if the user has a display name  (this is only relevant for old users)
        if (!StringUtils.hasText(ambraUser.getDisplayName())) {
            return ReturnCode.UPDATE_PROFILE;
        }
        //continue with the action invocation
        return actionInvocation.invoke();
    }
}

From source file:dao.ScriptFinderDAO.java

public static ObjectNode getPagedScripts(JsonNode filterOpt, int page, int size) {
    ObjectNode result = Json.newObject();

    javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
    DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
    TransactionTemplate txTemplate = new TransactionTemplate(tm);
    String scriptName = null;// w  w  w.ja v a 2  s.c o  m
    String scriptPath = null;
    String scriptType = null;
    String chainName = null;
    String jobName = null;
    String committerName = null;
    String committerEmail = null;
    if (filterOpt != null && (filterOpt.isContainerNode())) {
        if (filterOpt.has("scriptName")) {
            scriptName = filterOpt.get("scriptName").asText();
        }
        if (filterOpt.has("scriptPath")) {
            scriptPath = filterOpt.get("scriptPath").asText();
        }
        if (filterOpt.has("scriptType")) {
            scriptType = filterOpt.get("scriptType").asText();
        }
        if (filterOpt.has("chainName")) {
            chainName = filterOpt.get("chainName").asText();
        }
        if (filterOpt.has("jobName")) {
            jobName = filterOpt.get("jobName").asText();
        }
        if (filterOpt.has("committerName")) {
            committerName = filterOpt.get("committerName").asText();
        }
        if (filterOpt.has("committerEmail")) {
            committerEmail = filterOpt.get("committerEmail").asText();
        }
    }

    final String finalScriptName = scriptName;
    final String finalScriptPath = scriptPath;
    final String finalScriptType = scriptType;
    final String finalChainName = chainName;
    final String finalJobName = jobName;
    final String finalCommitterName = committerName;
    result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
        public ObjectNode doInTransaction(TransactionStatus status) {

            List<Map<String, Object>> rows = null;
            String whereClause = "";
            boolean needAnd = false;
            Map<String, Object> params = new HashMap<String, Object>();
            if (StringUtils.isNotBlank(finalScriptName)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " script_name like :scriptname ";
                needAnd = true;
                params.put("scriptname", "%" + finalScriptName + "%");
            }
            if (StringUtils.isNotBlank(finalScriptPath)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " script_path like :scriptpath ";
                needAnd = true;
                params.put("scriptpath", "%" + finalScriptPath + "%");
            }
            if (StringUtils.isNotBlank(finalScriptType)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " script_type like :scripttype ";
                needAnd = true;
                params.put("scripttype", "%" + finalScriptType + "%");
            }
            if (StringUtils.isNotBlank(finalChainName)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " chain_name like :chainname ";
                needAnd = true;
                params.put("chainname", "%" + finalChainName + "%");
            }
            if (StringUtils.isNotBlank(finalJobName)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " job_name like :jobname ";
                needAnd = true;
                params.put("jobname", "%" + finalJobName + "%");
            }
            if (StringUtils.isNotBlank(finalCommitterName)) {
                if (StringUtils.isBlank(whereClause)) {
                    whereClause = " WHERE ";
                }
                if (needAnd) {
                    whereClause += " AND ";
                }
                whereClause += " ( committer_ldap like :committername or committer_name like :committername )";
                needAnd = true;
                params.put("committername", "%" + finalCommitterName + "%");
            }
            String query = GET_PAGED_SCRIPTS.replace("$WHERE_CLAUSE", whereClause);
            params.put("index", (page - 1) * size);
            params.put("size", size);
            NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
                    getJdbcTemplate().getDataSource());
            rows = namedParameterJdbcTemplate.queryForList(query, params);
            long count = 0;
            try {
                count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
            } catch (EmptyResultDataAccessException e) {
                Logger.error("Exception = " + e.getMessage());
            }

            List<ScriptInfo> pagedScripts = new ArrayList<ScriptInfo>();
            for (Map row : rows) {
                int applicationID = (Integer) row.get(ScriptInfoRowMapper.APPLICATION_ID_COLUMN);
                int jobID = (Integer) row.get(ScriptInfoRowMapper.JOB_ID_COLUMN);
                String scriptUrl = (String) row.get(ScriptInfoRowMapper.SCRIPT_URL_COLUMN);
                String scriptPath = (String) row.get(ScriptInfoRowMapper.SCRIPT_PATH_COLUMN);
                String scriptType = (String) row.get(ScriptInfoRowMapper.SCRIPT_TYPE_COLUMN);
                String chainName = (String) row.get(ScriptInfoRowMapper.CHAIN_NAME_COLUMN);
                String jobName = (String) row.get(ScriptInfoRowMapper.JOB_NAME_COLUMN);
                String scriptName = (String) row.get(ScriptInfoRowMapper.SCRIPT_NAME_COLUMN);
                String committerName = (String) row.get(ScriptInfoRowMapper.COMMITTER_NAMES_COLUMN);
                String committerEmail = (String) row.get(ScriptInfoRowMapper.COMMITTER_EMAILS_COLUMN);
                ScriptInfo scriptInfo = new ScriptInfo();
                scriptInfo.applicationID = applicationID;
                scriptInfo.jobID = jobID;
                scriptInfo.scriptUrl = scriptUrl;
                scriptInfo.scriptPath = scriptPath;
                scriptInfo.scriptType = scriptType;
                scriptInfo.scriptName = scriptName;
                scriptInfo.chainName = chainName;
                scriptInfo.jobName = jobName;
                scriptInfo.committerName = committerName;
                scriptInfo.committerEmail = committerEmail;
                pagedScripts.add(scriptInfo);
            }

            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("scripts", Json.toJson(pagedScripts));

            return resultNode;
        }
    });

    return result;
}

From source file:com.hs.mail.imap.user.DefaultUserManager.java

public long addUser(final User user) {
    return (Long) getTransactionTemplate().execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus status) {
            try {
                return DaoFactory.getUserDao().addUser(user);
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }//from   w  ww  .  j  a  v a2  s  .  co  m
        }
    });
}