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:nl.strohalm.cyclos.http.JspTransactionFilter.java

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    final ExecutionResult result = (ExecutionResult) request
            .getAttribute(CyclosRequestProcessor.EXECUTION_RESULT_KEY);
    if (result != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURI()
                    + ": Not opening a new readonly transaction for JSP because CyclosRequestProcessor is managing transactions");
        }/* w  w  w. j  a va 2  s  .  c o m*/
        // The transaction is already being managed by CyclosRequestProcessor. Don't do anything here
        chain.doFilter(request, response);
    } else {
        // We need a readonly transaction for this JSP
        request.setAttribute(CyclosRequestProcessor.NO_TRANSACTION_KEY, true);
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(request.getRequestURI() + ": Opening a new readonly transaction for JSP");
            }
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(final TransactionStatus status) {
                    try {
                        chain.doFilter(request, response);
                    } catch (final Exception e) {
                        actionHelper.generateLog(request, config.getServletContext(), e);
                        throw new RuntimeException(e);
                    }
                }
            });
        } catch (final RuntimeException e) {
            ActionHelper.throwException(e.getCause());
        }
    }
}

From source file:nl.strohalm.cyclos.http.LifecycleListener.java

private void doLogout(final String sessionId) {
    transactionHelper.runInNewTransaction(new TransactionCallbackWithoutResult() {
        @Override/*w w  w .  ja v a 2s  .  c o m*/
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            try {
                accessService.logout(sessionId);
            } catch (final NotConnectedException e) {
                // Ok, just ignore
            } catch (final RuntimeException e) {
                LOG.warn("Error logging out member on session destroy", e);
                status.setRollbackOnly();
            }
        }
    });
}

From source file:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * Run a single initialization inside a transaction if it is required
 *//*from  w  ww. j a v a 2  s.  co  m*/
private void run(final LocalWebInitialization initialization) {
    LOG.debug(String.format("Running web initialization (%s)...", initialization.getName()));
    transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            try {
                initialization.initialize();
            } catch (final RuntimeException e) {
                LOG.error(String.format("Error running web initialization: %s", initialization.getName()), e);
                throw e;
            }
        }
    });
}

From source file:nl.strohalm.cyclos.services.access.AccessServiceImpl.java

private void updateSessionExpiration(final Long id, final Calendar newExpiration) {
    transactionHelper.runAsync(new TransactionCallbackWithoutResult() {
        @Override//from  w  w  w  .ja v a 2 s.c o m
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            sessionDao.updateExpiration(id, newExpiration);
        }
    });
}

From source file:nl.strohalm.cyclos.services.accounts.AccountServiceImpl.java

@Override
public void closeBalances(final Calendar time) {
    final Calendar day = DateHelper.truncate(time);

    // Process each batch in a new transaction
    final boolean[] hasMore = new boolean[1];
    hasMore[0] = true;//from  w w w  . j a va2 s.com
    while (hasMore[0]) {
        transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(final TransactionStatus txStatus) {
                CacheCleaner cacheCleaner = new CacheCleaner(fetchService);
                IteratorList<Account> accounts = accountDao.iterateUnclosedAccounts(day, CLOSE_BATCH_SIZE);
                hasMore[0] = accounts.hasNext();
                try {
                    for (Account account : accounts) {
                        closeBalance(account, day);
                        // Clear the cache to avoid having too much objects in memory
                        cacheCleaner.clearCache();
                    }
                } finally {
                    DataIteratorHelper.close(accounts);
                }
            }
        });
    }
}

From source file:nl.strohalm.cyclos.services.accounts.AccountStatusHandlerImpl.java

/**
 * Processes the next n pending account statuses. Warning: if passing more than 1, on high concurrent systems, it's likely to cause deadlocks, as
 * accounts are locked in the database.//from w  w  w  .  j a  v  a  2 s  .com
 * @return Returns whether something was actually processed - false if there were no pending records to process
 */
private boolean processQueue(final int count) throws InterruptedException {
    inProcess = true;
    final RunStatus status = transactionTemplate.execute(new TransactionCallback<RunStatus>() {
        public RunStatus doInTransaction(final TransactionStatus status) {
            return runInTransaction(status, count);
        }
    });
    CurrentTransactionData.cleanup();
    switch (status) {
    case RETRY:
        // Just retry the same pending account status after a small sleep
        queue.offer(count);
        break;
    case ERROR:
        errors++;
        if (errors <= MAX_ERROR_ATTEMPTS) {
            // Sleep 2sec, then 4, then 8, then 16...
            Thread.sleep((long) (Math.pow(2, errors) * 1000));
            // Ensure there will be another try for this status
            queue.offer(count);
        } else {
            // CRITICAL STATE!!!
            // We've not managed to resolve the error, and no more account status processing is done, which means
            // no more payments can be done! Kill the thread and raise an alert
            stopThread();
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(final TransactionStatus status) {
                    PendingAccountStatus pendingStatus = null;
                    Object[] arguments = {};
                    try {
                        pendingStatus = pendingAccountStatusDao.next(1).get(0);
                        final Transfer transfer = pendingStatus.getTransfer();
                        if (transfer != null) {
                            final LocalSettings localSettings = settingsService.getLocalSettings();
                            final UnitsConverter unitsConverter = localSettings
                                    .getUnitsConverter(transfer.getType().getFrom().getCurrency().getPattern());
                            final CalendarConverter dateConverter = localSettings.getDateConverter();
                            arguments = new Object[] { dateConverter.toString(pendingStatus.getDate()),
                                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName(),
                                    unitsConverter.toString(transfer.getAmount()) };
                        }
                    } catch (final Exception e) {
                        // Ok, leave null
                    }
                    alertService.create(SystemAlert.Alerts.ERROR_PROCESSING_ACCOUNT_STATUS, arguments);
                }
            });
        }
    }
    inProcess = false;
    return status != RunStatus.EMPTY;
}

From source file:nl.strohalm.cyclos.services.accounts.guarantees.GuaranteeServiceImpl.java

/**
 * Generates a new loan only if the guarantee' status is ACCEPTED and the begin period is now or before.
 * @param guarantee//  w  ww  .  ja  v a 2  s  .  c  o m
 * @param time the times used as the current time
 */
private void doGrantLoan(final Calendar time, final Guarantee guarantee,
        final boolean automaticLoanAuthorization) {
    if (guarantee.getStatus() != Guarantee.Status.ACCEPTED || guarantee.getValidity().getBegin().after(time)) {
        return;
    }

    transactionHelper.maybeRunInNewTransaction(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            performGrantLoan(guarantee, automaticLoanAuthorization);
        }
    });
}

From source file:nl.strohalm.cyclos.services.alerts.AlertServiceImpl.java

private void save(final Alert alert, final AlertType type) {
    if (alert.getDate() == null) {
        alert.setDate(Calendar.getInstance());
    }//w w  w. ja  v a 2  s .  co m

    // Only the application shutdown should be saved right away, as the database connection might be disposed right away
    if (SystemAlert.Alerts.APPLICATION_SHUTDOWN.equals(type)) {
        doSave(alert);
    } else {
        // The others are safe to run in the background
        CurrentTransactionData.addTransactionCommitListener(new TransactionEndListener() {
            @Override
            protected void onTransactionEnd(final boolean commit) {
                transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(final TransactionStatus status) {
                        doSave(alert);
                    }
                });
            }
        });
    }
}

From source file:nl.strohalm.cyclos.services.application.ApplicationServiceImpl.java

@Override
public synchronized void initialize() {
    if (initialized || initializing) {
        return;/*from  www  . j  a va2s .c o  m*/
    }
    initializing = true;
    try {
        // Store the startup time
        startupTime = System.currentTimeMillis();

        // Set AWT to headless mode. This way we can use XFree86 libs
        // on *nix systems without an X server running.
        setHeadlessMode();

        // The InitializingServices should be only initialized when scheduling is used on this cyclos instance.
        runScheduling = !Boolean.valueOf(cyclosProperties.getProperty("cyclos.disableScheduling", "false"));
        if (runScheduling) {
            // Run the initializations (beans of type InitializingService)
            Set<String> beanNames = applicationContext.getBeansOfType(InitializingService.class).keySet();
            taskRunner.runInitializations(beanNames);

            // Start both scheduling and polling tasks handlers
            schedulingHandler.start();
            pollingTasksHandler.start();
        }

        // Run the initializations
        Collection<LocalInitialization> initializations = applicationContext
                .getBeansOfType(LocalInitialization.class).values();
        runAll(initializations);

        if (runScheduling) {
            // Create a system alert
            transactionHelper.runAsync(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(final TransactionStatus status) {
                    // at this point, the resource bundle for translations is not loaded yet
                    // thus, we need to defer the creation of the event
                    deferEvent(SystemAlert.Alerts.APPLICATION_RESTARTED, instanceHandler.getId());
                }
            });
        }
        initialized = true;
        // add this object as a listener to the messageResolver, which will inform (notify) this
        // object when the translation resource bundles have been loaded, so that finally alerts can be created
        messageResolver.addMessageResourcesLoadedListener(this);
    } finally {
        initializing = false;
    }
}

From source file:nl.strohalm.cyclos.services.application.ApplicationServiceImpl.java

@Override
public void shutdown() {
    initialized = false;/*w w w . j a  va2  s . c om*/
    transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            alertService.create(SystemAlert.Alerts.APPLICATION_SHUTDOWN, instanceHandler.getId());
        }
    });
    applicationDao.shutdownDBIfNeeded();
}