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:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java

public void addPathsToSelectedFiles(final List<DataFile> selectedFiles)
        throws DataAccessMatrixQueries.DAMQueriesException {

    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(final TransactionStatus transactionStatus) {
            // create consolidated files for DataFileLevelTwoConsolidated
            // for other DataFiles do nothing
            for (final DataFile dataFile : selectedFiles) {
                if (dataFile instanceof DataFileLevelTwoConsolidated) {
                    try {
                        createConsolidatedFiles(dataFile);
                    } catch (IOException ie) {
                        throw new DataAccessException(ie.getMessage(), ie) {
                        };/*  w  w w .j a  va  2s  .  co m*/
                    }
                }
            }
            return null;

        }
    });
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

@Override
public FileData getPresentationFileData(final Long presentationId) {

    final Presentation presentation = transactionTemplate.execute(new TransactionCallback<Presentation>() {
        public Presentation doInTransaction(TransactionStatus status) {
            return presentationDao.getOneWithSlide(presentationId);
        }//from   w w  w.  j  av  a  2s.  co m
    });

    if (presentation == null) {
        return null;
    }

    FileData fileData = presentation.getPresentationFile();
    return fileData;
}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

public Transaction getTransaction(final String hash) {
    try {//  ww  w . j a  va  2s  . c  o  m
        log.trace("get transaction " + hash);
        Tx tx = txhandler.getTransaction(hash);
        if (tx == null) {
            return new TransactionTemplate(transactionManager).execute(new TransactionCallback<Transaction>() {
                @Override
                public Transaction doInTransaction(TransactionStatus status) {
                    status.setRollbackOnly();
                    Tx t;
                    try {
                        t = store.getTransaction(hash);
                        if (t != null) {
                            return toBCSAPITransaction(t);
                        }
                    } catch (ValidationException e) {
                    }
                    return null;
                }
            });
        } else {
            return toBCSAPITransaction(tx);
        }
    } finally {
        log.trace("get transaction returned " + hash);
    }
}

From source file:database.DataLoader.java

private void moveAuthorResume() throws Exception {
    final ResultSet set = getFromOldBase(
            "select a.id, f.path, f.name, f.id fileId, f.created from z_zauthor a, z_file f where a.resume = f.id");

    int countSuccess = 0;
    int countError = 0;
    while (set.next()) {
        boolean ok = false;
        initFtpClient();//w w  w .  j ava  2  s . c o  m
        try {
            final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

            ok = transactionTemplate.execute(new TransactionCallback<Boolean>() {

                @Override
                public Boolean doInTransaction(TransactionStatus ts) {
                    boolean result = false;
                    try {
                        Long authorId = set.getLong("id");
                        Long newAuthorId = getNewId(authorId, USERS);
                        Author author = authorDao.find(newAuthorId);
                        if (author != null) {
                            String path = set.getString("path");
                            String name = set.getString("name");
                            Long fileId = set.getLong("fileId");
                            Date created = getTimestampOrToday(set, "created");
                            //if (isRightFilePath(path)) {
                            if (!hasOldId(fileId, FILE)) {
                                String serverFileName = getServerFileName(path);
                                InputStream is = getFileFromFtp(serverFileName);
                                AuthorFile fileEnt = new AuthorFile();
                                fileEnt.setAuthor(author);
                                fileEnt.setRusname(name);
                                fileEnt.setUploadDate(created);
                                Long newFileId = fileService.saveNewFile(fileEnt, is);
                                saveLink(fileId, FILE, newFileId, AuthorFile.class);
                                result = true;
                            }
                            //}
                        } else {
                            messageList.add("   ? " + authorId);
                            ts.isRollbackOnly();
                        }
                    } catch (Exception e) {
                        ts.isRollbackOnly();
                        messageList.add("exception " + StringAdapter.getStackExeption(e));
                    }
                    return result;
                }
            });
        } finally {
            logoutFtpClient();
        }
        if (ok) {
            countSuccess++;
        } else {
            countError++;
        }
    }
    messageList.add("? ? - " + countSuccess);
    messageList.add("?  - " + countError);
}

From source file:com.bitsofproof.supernode.core.CachedBlockStore.java

@Override
public void storeBlock(final Blk b) throws ValidationException {
    try {//from  ww  w .j a  v a 2  s .c  o  m
        // have to lock before transaction starts and unlock after finished.
        // otherwise updates to transient vs. persistent structures are out of sync for a
        // concurrent tx. This does not apply to methods using MANDATORY transaction annotation
        // context since they must have been invoked within a transaction.
        lock.writeLock().lock();

        ValidationException e = new TransactionTemplate(transactionManager)
                .execute(new TransactionCallback<ValidationException>() {
                    @Override
                    public ValidationException doInTransaction(TransactionStatus status) {
                        try {
                            startBatch();
                            lockedStoreBlock(b);
                            endBatch();
                        } catch (ValidationException e) {
                            cancelBatch();
                            status.setRollbackOnly();
                            return e;
                        } catch (Exception e) {
                            cancelBatch();
                            status.setRollbackOnly();
                            return new ValidationException(e);
                        }
                        return null;
                    }
                });
        if (e != null) {
            throw e;
        }
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:dao.FlowsDAO.java

public static ObjectNode getPagedJobsByFlow(String applicationName, Long flowId, int page, int size) {
    ObjectNode result;//  ww w .j  a v a 2s .com
    List<Job> pagedJobs = new ArrayList<Job>();

    if (StringUtils.isBlank(applicationName) || (flowId <= 0)) {
        result = Json.newObject();
        result.put("count", 0);
        result.put("page", page);
        result.put("itemsPerPage", size);
        result.put("totalPages", 0);
        result.set("jobs", Json.toJson(""));
        return result;
    }

    String application = applicationName.replace(".", " ");

    Integer appID = getApplicationIDByName(application);
    if (appID != 0) {
        javax.sql.DataSource ds = getJdbcTemplate().getDataSource();
        DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);
        TransactionTemplate txTemplate = new TransactionTemplate(tm);
        final long azkabanFlowId = flowId;
        result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
            public ObjectNode doInTransaction(TransactionStatus status) {
                List<Map<String, Object>> rows = null;
                rows = getJdbcTemplate().queryForList(GET_PAGED_JOBS_BY_APP_ID_AND_FLOW_ID, appID,
                        azkabanFlowId, (page - 1) * size, size);
                long count = 0;
                String flowName = "";
                try {
                    count = getJdbcTemplate().queryForObject("SELECT FOUND_ROWS()", Long.class);
                } catch (EmptyResultDataAccessException e) {
                    Logger.error("Exception = " + e.getMessage());
                }
                for (Map row : rows) {
                    Job job = new Job();
                    job.id = (Long) row.get("job_id");
                    job.name = (String) row.get("job_name");
                    job.path = (String) row.get("job_path");
                    job.path = (String) row.get("job_path");
                    job.refFlowGroup = (String) row.get("flow_group");
                    if (StringUtils.isNotBlank(job.path)) {
                        int index = job.path.indexOf("/");
                        if (index != -1) {
                            job.path = job.path.substring(0, index);
                        }
                    }
                    job.type = (String) row.get("job_type");
                    Object created = row.get("created_time");
                    job.refFlowId = (Long) row.get("ref_flow_id");
                    if (created != null) {
                        job.created = DateFormat.format(created.toString());
                    }
                    Object modified = row.get("modified_time");
                    if (modified != null) {
                        job.modified = DateFormat.format(modified.toString());
                    }

                    if (StringUtils.isBlank(flowName)) {
                        flowName = (String) row.get("flow_name");
                    }
                    pagedJobs.add(job);
                }
                ObjectNode resultNode = Json.newObject();
                resultNode.put("count", count);
                resultNode.put("flow", flowName);
                resultNode.put("page", page);
                resultNode.put("itemsPerPage", size);
                resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
                resultNode.set("jobs", Json.toJson(pagedJobs));
                return resultNode;
            }
        });
        return result;
    }

    result = Json.newObject();
    result.put("count", 0);
    result.put("page", page);
    result.put("itemsPerPage", size);
    result.put("totalPages", 0);
    result.set("jobs", Json.toJson(""));
    return result;
}

From source file:dao.DashboardDAO.java

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

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

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

        public ObjectNode doInTransaction(TransactionStatus status) {
            final String datasetQuery;
            switch (option) {
            case 1:
                datasetQuery = GET_OWNERSHIP_CONFIRMED_DATASETS_FILTER_PLATFORM;
                break;
            case 2:
                datasetQuery = GET_OWNERSHIP_UNCONFIRMED_DATASETS_FILTER_PLATFORM;
                break;
            case 3:
                datasetQuery = GET_OWNERSHIP_DATASETS_FILTER_PLATFORM;
                break;
            default:
                datasetQuery = GET_OWNERSHIP_DATASETS_FILTER_PLATFORM;
            }/*from  w  w w. j a  va2s .  c o  m*/

            List<Map<String, Object>> rows = new ArrayList<>(size);
            long count = getPagedDashboardDatasets(managerId, datasetQuery, 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");
                String confirmedOwnerId = (String) row.get("confirmed_owner_id");
                if (StringUtils.isBlank(confirmedOwnerId) && option == 1) {
                    confirmedOwnerId = "<other team>";
                }
                dashboardDataset.confirmedOwnerId = confirmedOwnerId;
                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:org.geowebcache.diskquota.jdbc.JDBCQuotaStore.java

@SuppressWarnings("unchecked")
public Future<List<PageStats>> addHitsAndSetAccesTime(final Collection<PageStatsPayload> statsUpdates) {
    return executor.submit(new Callable<List<PageStats>>() {

        public List<PageStats> call() throws Exception {
            return (List<PageStats>) tt.execute(new TransactionCallback() {

                public Object doInTransaction(TransactionStatus status) {
                    List<PageStats> result = new ArrayList<PageStats>();
                    if (statsUpdates != null) {
                        // sort the payloads by page id as a deadlock avoidance measure, out
                        // of order updates may result in deadlock with the addHitsAndSetAccessTime method
                        List<PageStatsPayload> sorted = sortPayloads(statsUpdates);
                        for (PageStatsPayload payload : sorted) {
                            // verify the stats are referring to an existing tile set id
                            TileSet tset = payload.getTileSet();
                            if (tset == null) {
                                String tileSetId = payload.getPage().getTileSetId();
                                tset = getTileSetByIdInternal(tileSetId);
                                if (tset == null) {
                                    log.warn("Could not locate tileset with id " + tileSetId
                                            + ", skipping page stats update: " + payload);
                                }//from  w  w  w.  j av a2s  . c o m
                            } else {
                                getOrCreateTileSet(tset);
                            }

                            // update the stats
                            PageStats stats = upsertTilePageHitAccessTime(payload);
                            result.add(stats);
                        }
                    }

                    return result;
                }

                private PageStats upsertTilePageHitAccessTime(PageStatsPayload payload) {
                    TilePage page = payload.getPage();

                    if (log.isDebugEnabled()) {
                        log.info("Updating page " + page + " with payload " + payload);
                    }

                    int modified = 0;
                    int count = 0;
                    PageStats stats = null;
                    while (modified == 0 && count < maxLoops) {
                        try {
                            count++;
                            stats = getPageStats(page.getKey());
                            if (stats != null) {
                                // gather the old values, we'll use them for the optimistic locking
                                final BigInteger oldHits = stats.getNumHits();
                                final float oldFrequency = stats.getFrequencyOfUsePerMinute();
                                final int oldAccessTime = stats.getLastAccessTimeMinutes();
                                // update the page so that it computes the new stats
                                updatePageStats(payload, page, stats);

                                // update the record in the db
                                String update = dialect.updatePageStats(schema, "key", "newHits", "oldHits",
                                        "newFrequency", "oldFrequency", "newAccessTime", "oldAccessTime");
                                Map<String, Object> params = new HashMap<String, Object>();
                                params.put("key", page.getKey());
                                params.put("newHits", new BigDecimal(stats.getNumHits()));
                                params.put("oldHits", new BigDecimal(oldHits));
                                params.put("newFrequency", stats.getFrequencyOfUsePerMinute());
                                params.put("oldFrequency", oldFrequency);
                                params.put("newAccessTime", stats.getLastAccessTimeMinutes());
                                params.put("oldAccessTime", oldAccessTime);
                                modified = jt.update(update, params);
                            } else {
                                // create the new stats and insert it
                                stats = new PageStats(0);
                                updatePageStats(payload, page, stats);
                                modified = createNewPageStats(stats, page);
                            }
                        } catch (DeadlockLoserDataAccessException e) {
                            if (log.isDebugEnabled()) {
                                log.debug("Deadlock while updating page stats, will retry", e);
                            }
                        }
                    }

                    if (modified == 0) {
                        throw new ConcurrencyFailureException("Failed to create or update page stats for page "
                                + payload.getPage() + " after " + count + " attempts");
                    }

                    return stats;
                }

                private void updatePageStats(PageStatsPayload payload, TilePage page, PageStats stats) {
                    final int addedHits = payload.getNumHits();
                    final int lastAccessTimeMinutes = (int) (payload.getLastAccessTime() / 1000 / 60);
                    final int creationTimeMinutes = page.getCreationTimeMinutes();
                    stats.addHitsAndAccessTime(addedHits, lastAccessTimeMinutes, creationTimeMinutes);
                }

            });
        }
    });
}

From source file:org.wallride.service.ArticleService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
@CacheEvict(value = WallRideCacheConfiguration.ARTICLE_CACHE, allEntries = true)
public List<Article> bulkDeleteArticle(ArticleBulkDeleteRequest bulkDeleteRequest, BindingResult result) {
    List<Article> articles = new ArrayList<>();
    for (long id : bulkDeleteRequest.getIds()) {
        final ArticleDeleteRequest deleteRequest = new ArticleDeleteRequest.Builder().id(id)
                .language(bulkDeleteRequest.getLanguage()).build();

        final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
        r.setMessageCodesResolver(messageCodesResolver);

        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
        transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
        Article article = null;//w  ww .j  a v a  2 s .c  o  m
        try {
            article = transactionTemplate.execute(new TransactionCallback<Article>() {
                public Article doInTransaction(TransactionStatus status) {
                    try {
                        return deleteArticle(deleteRequest, r);
                    } catch (BindException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            articles.add(article);
        } catch (Exception e) {
            logger.debug("Errors: {}", r);
            result.addAllErrors(r);
        }
    }
    return articles;
}

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

/**
 * Creates a set of acts with non-parent/child relationships, and verifies
 * that deleting one act doesn't cascade to the rest, within transactions.
 *
 * @throws Exception for any error/*ww  w  . j a va 2 s. c om*/
 */
@Test
public void testPeerActRemovalInTxn() throws Exception {
    final Act act1 = createSimpleAct("act1", "IN_PROGRESS");
    final Act act2 = createSimpleAct("act2", "IN_PROGRESS");
    final Act act3 = createSimpleAct("act3", "IN_PROGRESS");

    // create a relationship from act1 -> act2
    final ActRelationship relAct1Act2 = addRelationship(act1, act2, "act1->act2");

    // create a relationship from act2 -> act3
    final ActRelationship relAct2Act3 = addRelationship(act2, act3, "act2->act3");

    // create a relationship from act1 -> act3
    final ActRelationship relAct1Act3 = addRelationship(act1, act3, "act1->act3");

    save(Arrays.asList(act1, act2, act3));

    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            remove(act1);
            assertNull(reload(act1));

            // reload act2 and verify that it no longer has a relationship
            // to act1, and can be saved again
            Act act2reloaded = reload(act2);
            Set<ActRelationship> relationships = act2reloaded.getActRelationships();
            assertFalse(relationships.contains(relAct1Act2));
            assertTrue(relationships.contains(relAct2Act3));
            act2reloaded.setStatus("POSTED");
            save(act2reloaded);

            // reload act3 and verify that it no longer has a relationship
            // to act1, and can be saved again
            Act act3reloaded = reload(act3);
            relationships = act3reloaded.getActRelationships();
            assertFalse(relationships.contains(relAct1Act3));
            act3reloaded.setStatus("POSTED");
            save(act3reloaded);
            return null;
        }
    });
    assertNull(reload(act1));
    assertNotNull(reload(act2));
    assertNotNull(reload(act3));

    template.execute(new TransactionCallback<Object>() {
        public Object doInTransaction(TransactionStatus status) {
            Act act3reloaded = reload(act3);
            remove(act3reloaded);
            assertNull(reload(act3reloaded));

            // reload act2 and verify that it no longer has a relationship
            // to act3
            Act act2reloaded = reload(act2);
            assertFalse(act2reloaded.getActRelationships().contains(relAct2Act3));
            assertEquals("POSTED", act2reloaded.getStatus());
            return null;
        }
    });

    assertNull(reload(act3));
    assertNotNull(reload(act2));
}