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

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

Introduction

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

Prototype

TransactionCallbackWithoutResult

Source Link

Usage

From source file:com.hs.mail.imap.mailbox.DefaultMailboxManager.java

public void deleteMessage(final long uid) {
    if (fdCache != null) {
        fdCache.remove(uid);//from  w ww.j av a  2 s .c  o  m
    }
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                MessageDao dao = DaoFactory.getMessageDao();
                PhysMessage pm = dao.getDanglingMessageID(uid);
                dao.deleteMessage(uid);
                if (pm != null) {
                    deletePhysicalMessage(pm);
                }
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }
        }
    });
}

From source file:com.thoughtworks.go.server.service.ScheduleServiceIntegrationTest.java

private void saveRev(final Pipeline pipeline) {
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*w w  w. ja v a 2s.c  o  m*/
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            materialRepository.save(pipeline.getBuildCause().getMaterialRevisions());
            pipelineService.save(pipeline);
        }
    });
}

From source file:database.DataLoader.java

private void moveBranches() throws SQLException, ClassNotFoundException, Exception {
    try {//from w  w w  .j av  a 2  s .  co  m
        final String tableName = BRANCH;
        final ResultSet branchSet = getFromOldBase(getSelectAll(tableName));
        while (branchSet.next()) {
            TransactionTemplate temp = new TransactionTemplate(transactionManager);
            temp.execute(new TransactionCallbackWithoutResult() {

                @Override
                protected void doInTransactionWithoutResult(TransactionStatus ts) {
                    Long oldId = 0L;
                    try {
                        oldId = branchSet.getLong("id");
                        String name = branchSet.getString("name");
                        String letter = branchSet.getString("letter");
                        boolean canUseFreeAuthors = branchSet.getBoolean("can_use_free_authors");
                        Branch branch = new Branch();
                        branch.setAbbrevation(letter);
                        branch.setFreeAuthors(canUseFreeAuthors);
                        branch.setName(name);
                        saveObjectAndLink(branch, oldId, tableName);
                    } catch (Exception e) {
                        ts.setRollbackOnly();
                        String message = "branch: " + oldId + " " + StringAdapter.getStackExeption(e);
                        addErrorMessage(message);
                    }
                }
            });

        }
    } catch (Throwable th) {
        log.warn("moveBranches " + StringAdapter.getStackExeption(th));
    }
}

From source file:com.hs.mail.imap.mailbox.DefaultMailboxManager.java

public void copyMessage(final long uid, final long mailboxID) {
    getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            try {
                MessageDao dao = DaoFactory.getMessageDao();
                dao.copyMessage(uid, mailboxID);
            } catch (DataAccessException ex) {
                status.setRollbackOnly();
                throw ex;
            }// w  ww . ja  va  2s  .c  o m
        }
    });
}

From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStore.java

public void addToQuotaAndTileCounts(final TileSet tileSet, final Quota quotaDiff,
        final Collection<PageStatsPayload> tileCountDiffs) throws InterruptedException {
    tt.execute(new TransactionCallbackWithoutResult() {

        @Override//from ww  w  .j  av a2s. c  om
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            getOrCreateTileSet(tileSet);
            updateQuotas(tileSet, quotaDiff);

            if (tileCountDiffs != 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(tileCountDiffs);
                for (PageStatsPayload payload : sorted) {
                    upsertTilePageFillFactor(payload);
                }
            }
        }

        private void updateQuotas(final TileSet tileSet, final Quota quotaDiff) {
            if (log.isDebugEnabled()) {
                log.info("Applying quota diff " + quotaDiff.getBytes() + " on tileset " + tileSet);
            }

            String updateQuota = dialect.getUpdateQuotaStatement(schema, "tileSetId", "bytes");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("tileSetId", tileSet.getId());
            params.put("bytes", new BigDecimal(quotaDiff.getBytes()));
            jt.update(updateQuota, params);
            params.put("tileSetId", GLOBAL_QUOTA_NAME);
            jt.update(updateQuota, params);
        }

        private void upsertTilePageFillFactor(PageStatsPayload payload) {
            if (log.isDebugEnabled()) {
                log.info("Applying page stats payload " + payload);
            }

            // see http://en.wikipedia.org/wiki/Merge_(SQL)
            // Even the Merge command that some databases support is prone to race conditions
            // under concurrent load, but we don't want to lose data and it's difficult to
            // tell apart the race conditions from other failures, so we use tolerant commands
            // and loop over them.
            // Loop conditions: we find the page stats, but they are deleted before we can
            // update
            // them, we don't find the page stats, but they are inserted before we can do so, in
            // both cases we re-start from zero
            TilePage page = payload.getPage();
            final byte level = page.getZoomLevel();
            final BigInteger tilesPerPage = calculator.getTilesPerPage(tileSet, level);

            int modified = 0;
            int count = 0;
            while (modified == 0 && count < maxLoops) {
                try {
                    count++;
                    PageStats stats = getPageStats(page.getKey());
                    if (stats != null) {
                        float oldFillFactor = stats.getFillFactor();
                        stats.addTiles(payload.getNumTiles(), tilesPerPage);
                        // if no change, bail out early
                        if (oldFillFactor == stats.getFillFactor()) {
                            return;
                        }

                        // update the record in the db
                        modified = updatePageFillFactor(page, stats, oldFillFactor);
                    } else {
                        // create the stats and update the fill factor
                        stats = new PageStats(0);
                        stats.addTiles(payload.getNumTiles(), tilesPerPage);

                        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");
            }
        }

    });
}

From source file:edu.wisc.jmeter.dao.JdbcMonitorDao.java

@Override
public void storeHostStatus(HostStatus hostStatus) {
    hostStatus.setLastUpdated(new Date());

    final Map<String, Object> params = new LinkedHashMap<String, Object>();
    params.put("hostName", hostStatus.getHost());
    params.put("status", hostStatus.getStatus().toString());
    params.put("failureCount", hostStatus.getFailureCount());
    params.put("messageCount", hostStatus.getMessageCount());
    params.put("lastNotification", hostStatus.getLastMessageSent());
    params.put("lastUpdated", hostStatus.getLastUpdated());

    this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        @Override/*from   ww  w .j a  v  a  2 s .c o m*/
        protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
            jdbcTemplate.update("UPDATE MONITOR_HOST_STATUS " + "SET " + "STATUS = :status, "
                    + "FAILURE_COUNT = :failureCount, " + "MESSAGE_COUNT = :messageCount, "
                    + "LAST_NOTIFICATION = :lastNotification," + "LAST_UPDATED =  :lastUpdated "
                    + "WHERE HOST_NAME = :hostName", params);
        }
    });
}

From source file:org.jspresso.hrsample.backend.JspressoModelTest.java

/**
 * Tests fix for bug #920.//from  w  ww.  j a v a  2s  .  co m
 */
@Test
public void testRemovedEntityIsClean() {
    final HibernateBackendController hbc = (HibernateBackendController) getBackendController();
    final City c = hbc.getEntityFactory().createEntityInstance(City.class);
    c.setName("Remove");
    c.setZip("00000");

    assertTrue(!c.isPersistent());
    assertTrue(hbc.isDirty(c));

    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            hbc.registerForUpdate(hbc.cloneInUnitOfWork(c));
        }
    });

    assertTrue(c.isPersistent());
    assertTrue(!hbc.isDirty(c));

    hbc.getTransactionTemplate().execute(new TransactionCallbackWithoutResult() {

        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            City c1 = hbc.cloneInUnitOfWork(c);
            try {
                hbc.cleanRelationshipsOnDeletion(c1, false);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });

    assertTrue("Entity is still considered persistent after deletion", !c.isPersistent());
    assertTrue("Entity is still considered dirty, although we can't do much with it", !hbc.isDirty(c));
}

From source file:ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.java

private void processReindexing() {
    if (System.currentTimeMillis() < myNextReindexPass) {
        return;/*from  ww  w  .  j av  a  2  s. c o  m*/
    }

    TransactionTemplate tt = new TransactionTemplate(myTransactionMgr);
    tt.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus theArg0) {
            int maxResult = 1000;
            Page<TermConcept> resources = myConceptDao
                    .findResourcesRequiringReindexing(new PageRequest(0, maxResult));
            if (resources.hasContent() == false) {
                myNextReindexPass = System.currentTimeMillis() + DateUtils.MILLIS_PER_MINUTE;
                return;
            }

            ourLog.info("Indexing {} / {} concepts", resources.getContent().size(),
                    resources.getTotalElements());

            int count = 0;
            StopWatch stopwatch = new StopWatch();

            for (TermConcept resourceTable : resources) {
                saveConcept(resourceTable);
                count++;
            }

            ourLog.info("Indexed {} / {} concepts in {}ms - Avg {}ms / resource",
                    new Object[] { count, resources.getContent().size(), stopwatch.getMillis(),
                            stopwatch.getMillisPerOperation(count) });
        }
    });

}

From source file:org.openvpms.archetype.rules.finance.account.CustomerAccountRules.java

/**
 * Reverses an act.//  ww w. j a  v  a 2s . com
 * <p/>
 * If the act to be reversed is an invoice, charge items and medication acts will be unlinked from patient history.
 * Reminders and investigations will be retained.
 *
 * @param act       the act to reverse
 * @param startTime the start time of the reversal
 * @param notes     notes indicating the reason for the reversal, to set the 'notes' node if the act has one.
 *                  May be {@code null}
 * @param reference the reference. If {@code null}, the act identifier will be used
 * @param hide      if {@code true}, hide the reversal iff the act being reversed isn't already hidden
 * @return the reversal of {@code act}
 * @throws ArchetypeServiceException for any archetype service error
 */
public FinancialAct reverse(final FinancialAct act, Date startTime, String notes, String reference,
        boolean hide) {
    final ActBean original = new ActBean(act, service);
    if (!original.getValues("reversal").isEmpty()) {
        throw new IllegalStateException("Act=" + act.getId() + " has already been reversed");
    }
    IMObjectCopier copier = new IMObjectCopier(new CustomerActReversalHandler(act));
    final List<IMObject> objects = copier.apply(act);
    FinancialAct reversal = (FinancialAct) objects.get(0);
    ActBean bean = new ActBean(reversal, service);
    bean.setValue("reference", !StringUtils.isEmpty(reference) ? reference : act.getId());
    bean.setValue("notes", notes);
    reversal.setStatus(FinancialActStatus.POSTED);
    reversal.setActivityStartTime(startTime);

    original.addNodeRelationship("reversal", reversal);

    if (hide && !original.getBoolean("hide")) {
        bean.setValue("hide", hide);
        original.setValue("hide", hide);
    }

    // This smells. The original acts needs to be saved without using the rule based archetype service, to avoid
    // triggering rules. The other acts need to be saved with rules enabled, in order to update the balance.
    // TODO
    TransactionTemplate template = new TransactionTemplate(transactionManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            List<IMObject> noRules = new ArrayList<IMObject>();
            noRules.add(act);

            if (TypeHelper.isA(act, CustomerAccountArchetypes.INVOICE)) {
                removeInvoiceFromPatientHistory(act, noRules);
            }
            service.save(noRules);
            ruleService.save(objects);
        }
    });
    return reversal;
}