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:ru.apertum.qsystem.client.forms.FAdmin.java

@Action
    public void saveConfiguration() {
        saveNet();/* w  w  w  . j  a v a2 s  .  co m*/
        final Exception res;
        try {
            res = (Exception) Spring.getInstance().getTt().execute(new TransactionCallback() {

                @Override
                public Exception doInTransaction(TransactionStatus status) {
                    try {
                        //? ? ?
                        Spring.getInstance().getHt().saveOrUpdate(ServerProps.getInstance().getProps());
                        //?  
                        Spring.getInstance().getHt().saveOrUpdate(ServerProps.getInstance().getStandards());

                        // ?  ???
                        QScheduleList.getInstance().save();
                        // ?   ??
                        QBreaksList.getInstance().save();
                        // ?  ?
                        QCalendarList.getInstance().save();
                        // ? ?
                        QServiceTree.getInstance().save();
                        // ? 
                        QUserList.getInstance().save();
                        // ? 
                        QInfoTree.getInstance().save();
                        // ? 
                        QResponseList.getInstance().save();
                        // ?   ? ? 
                        QResultList.getInstance().save();
                        QLog.l().logger().debug(" .");
                    } catch (Exception ex) {
                        QLog.l().logger().error("  ? \n" + ex.toString() + "\n"
                                + Arrays.toString(ex.getStackTrace()));
                        status.setRollbackOnly();
                        return ex;
                    }
                    return null;
                }
            });
        } catch (RuntimeException ex) {
            throw new ClientException(
                    " ?  ?   (JDBC).        ?.\n("
                            + ex.toString() + ")");
        }
        if (res == null) {
            JOptionPane.showMessageDialog(this, getLocaleMessage("admin.save.title"),
                    getLocaleMessage("admin.save.caption"), JOptionPane.INFORMATION_MESSAGE);
        } else {
            throw new ClientException(
                    " ?  ?   (JDBC).        ?.\n["
                            + res.getLocalizedMessage() + "]\n(" + res.toString() + ")\nSQL: ");
        }
    }

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

@Override
protected void execute(final HttpServletRequest request, final HttpServletResponse servletResponse,
        final FilterChain chain) throws IOException, ServletException {

    // As the CXF servlet manually flushes the response before we have the time to end the transaction, we must use a custom response, which never
    // flushes the buffer until we really want it
    final HttpServletResponse response;
    if (RequestHelper.isWebService(request)) {
        response = new ForcedBufferResponse(servletResponse);
    } else {// w w  w. ja  v  a  2 s  .  c  o m
        response = servletResponse;
    }

    // Can't use a primitive because it must be final
    final MutableBoolean commit = new MutableBoolean(false);

    // Execute the filter in a transaction
    Throwable error;
    try {
        error = transactionTemplate.execute(new TransactionCallback<Throwable>() {
            public Throwable doInTransaction(final TransactionStatus status) {
                final Throwable result = runInTransaction(status, request, response, chain);
                // When no rollback, set the commit flag
                if (!status.isRollbackOnly()) {
                    commit.set();
                }
                return result;
            }
        });
    } catch (final Exception e) {
        LOG.error("Error executing transaction", e);
        error = e;
    }

    try {
        // If there was a commit, notify the TransactionCommitListeners
        if (commit.isSet()) {
            notifyTransactionCommitListeners(request);
        }

        // The resulting error was not silenced (i.e, by the BaseAction's try / catch. Log and rethrow
        if (error != null) {
            ActionHelper.generateLog(request, config.getServletContext(), error);
            if (error instanceof RuntimeException) {
                throw (RuntimeException) error;
            } else if (error instanceof ServletException) {
                throw (ServletException) error;
            } else if (error instanceof IOException) {
                throw (IOException) error;
            } else {
                throw new RuntimeException(error);
            }
        }

        // Flush the response if it's a web service
        if (response instanceof ForcedBufferResponse) {
            ((ForcedBufferResponse) response).doFlushBuffer();
        }
    } finally {
        // Ensure that if any data was placed on the CurrentTransactionData, it is released
        CurrentTransactionData.cleanup();

    }
}

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

@Override
public boolean notifyPermissionDeniedException() {
    if (!LoggedUser.hasUser()) {
        return false;
    }/*from   www  . j a  v a2  s.com*/

    return transactionHelper.runInNewTransaction(new TransactionCallback<Boolean>() {
        @Override
        public Boolean doInTransaction(final TransactionStatus status) {
            final User user = fetchService.fetch(LoggedUser.user(),
                    RelationshipHelper.nested(User.Relationships.ELEMENT, Element.Relationships.GROUP));

            // Already blocked
            if (isBlocked(user.getPasswordBlockedUntil())) {
                return true;
            }

            // Check if maxTries has been reached
            final BasicGroupSettings basicSettings = user.getElement().getGroup().getBasicSettings();
            final int maxTries = basicSettings.getMaxPasswordWrongTries();
            if (maxTries > 0) {
                permissionDeniedTraceDao.record(user);
                int tries = permissionDeniedTraceDao.count(wrongAttemptsLimit(), user);
                if (tries == maxTries) {
                    // Send an alert
                    if (user instanceof AdminUser) {
                        alertService.create(SystemAlert.Alerts.ADMIN_LOGIN_BLOCKED_BY_PERMISSION_DENIEDS,
                                user.getUsername(), tries, LoggedUser.remoteAddress());
                    } else if (user instanceof MemberUser) {
                        alertService.create(((MemberUser) user).getMember(),
                                MemberAlert.Alerts.LOGIN_BLOCKED_BY_PERMISSION_DENIEDS, tries,
                                LoggedUser.remoteAddress());
                    }
                    // Block the user and clear any previous traces
                    final Calendar mayLoginAt = basicSettings.getDeactivationAfterMaxPasswordTries()
                            .add(Calendar.getInstance());
                    user.setPasswordBlockedUntil(mayLoginAt);
                    permissionDeniedTraceDao.clear(user);
                    return true;
                }
            }
            return false;
        }
    });
}

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   ww w . j a v  a2  s  .co m
 * @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.alerts.ErrorLogServiceImpl.java

@Override
public Future<ErrorLogEntry> insert(final Throwable t, final String path, final Map<String, ?> parameters) {
    if (t == null) {
        throw new ValidationException("exception", new RequiredError());
    }/*  ww  w  .  jav  a2 s. co m*/
    if (StringUtils.isEmpty(path)) {
        throw new ValidationException("path", new RequiredError());
    }
    return transactionHelper.runAsync(new TransactionCallback<ErrorLogEntry>() {
        @Override
        public ErrorLogEntry doInTransaction(final TransactionStatus status) {
            return doInsert(t, path, parameters);
        }
    });
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

private void add(final Class<? extends Indexable> entityType, final Long id) {
    IndexWriter writer = null;//from  w  ww  . j av  a2  s.  co m
    try {
        writer = getWriter(entityType);
        final Analyzer analyzer = getAnalyzer();
        Document document = readonlyTransactionTemplate.execute(new TransactionCallback<Document>() {
            @Override
            public Document doInTransaction(final TransactionStatus status) {
                try {
                    Session session = getSession();
                    Indexable entity = (Indexable) session.load(entityType, id);
                    DocumentMapper documentMapper = indexHandler.getDocumentMapper(entityType);
                    if (entityType.equals(Member.class)) {
                        rebuildMemberAds(id, analyzer, session);
                    }
                    if (entityType.equals(Administrator.class) || entityType.equals(Member.class)) {
                        rebuildMemberRecords(id, analyzer, session);
                    }
                    return documentMapper.map(entity);
                } catch (ObjectNotFoundException e) {
                    return null;
                } catch (EntityNotFoundException e) {
                    return null;
                }
            }
        });
        if (document != null) {
            writer.updateDocument(new Term("id", document.get("id")), document, analyzer);
            commit(entityType, writer);
        }
    } catch (CorruptIndexException e) {
        handleIndexCorrupted(entityType);
    } catch (Exception e) {
        LOG.warn("Error adding entity to search index: " + ClassHelper.getClassName(entityType) + "#" + id, e);
        rollback(entityType, writer);
    }
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

private void initialRebuild() {
    IndexOperation operation = readonlyTransactionTemplate.execute(new TransactionCallback<IndexOperation>() {
        @Override/*from   w  ww.j ava 2s.  co  m*/
        public IndexOperation doInTransaction(final TransactionStatus status) {
            return indexOperationDao.last();
        }
    });
    rebuildAll(operation);
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

/**
 * Recreates an index. If the force parameter is false, execute only if the index is corrupt or missing
 *//*w  w w . j  a  v  a  2 s .  co m*/
private void rebuild(final Class<? extends Indexable> entityType, final boolean force,
        final boolean createAlert) {
    boolean execute = true;
    // When not forced, run only
    if (!force) {
        final IndexStatus status = indexHandler.getIndexStatus(entityType);
        execute = status != IndexStatus.CORRUPT && status != IndexStatus.MISSING;
    }
    if (!execute) {
        return;
    }

    if (createAlert) {
        // Create the alert for index rebuilding
        createAlert(SystemAlert.Alerts.INDEX_REBUILD_START, entityType);
    }

    IndexWriter indexWriter = cachedWriters.get(entityType);
    if (indexWriter != null) {
        try {
            indexWriter.close();
        } catch (final Exception e) {
            // Silently ignore
        }
        cachedWriters.remove(entityType);
    }
    // Remove all files and recreate the directory
    final File dir = indexHandler.getIndexDir(entityType);
    try {
        FileUtils.deleteDirectory(dir);
    } catch (final IOException e) {
        // Silently ignore
    }
    dir.mkdirs();

    final DocumentMapper documentMapper = indexHandler.getDocumentMapper(entityType);
    final IndexWriter writer = getWriter(entityType);

    // Now, we should add all entities to the index
    boolean success = readonlyTransactionTemplate.execute(new TransactionCallback<Boolean>() {
        @Override
        public Boolean doInTransaction(final TransactionStatus status) {
            Session session = getSession();
            ScrollableResults scroll = session.createQuery(resolveHql(entityType))
                    .scroll(ScrollMode.FORWARD_ONLY);

            try {
                int index = 0;
                while (scroll.next()) {
                    Indexable entity = (Indexable) scroll.get(0);
                    Document document = documentMapper.map(entity);
                    try {
                        writer.addDocument(document);
                    } catch (CorruptIndexException e) {
                        handleIndexCorrupted(entityType);
                        return false;
                    } catch (IOException e) {
                        LOG.error("Error while adding document to index after rebuilding "
                                + ClassHelper.getClassName(entityType), e);
                        return false;
                    }
                    // Every batch, clear the session and commit the writer
                    if (++index % 30 == 0) {
                        session.clear();
                        commit(entityType, writer);
                    }
                }
                return true;
            } finally {
                scroll.close();
            }
        }
    });

    // Finish the writer operation
    try {
        if (success) {
            commit(entityType, writer);
        } else {
            rollback(entityType, writer);
        }
    } finally {
        if (createAlert) {
            // Create the alert for index rebuilding
            createAlert(SystemAlert.Alerts.INDEX_REBUILD_END, entityType);
        }
    }
}

From source file:nl.strohalm.cyclos.utils.lucene.IndexOperationRunner.java

private void runNextOperations() {
    boolean hasMore = true;
    while (hasMore) {
        IndexOperation operation = readonlyTransactionTemplate
                .execute(new TransactionCallback<IndexOperation>() {
                    @Override//from ww  w . j  a va2s  .c  om
                    public IndexOperation doInTransaction(final TransactionStatus txStatus) {
                        IndexOperation operation = indexOperationDao.next(lastOperationTime, lastOperationId);
                        if (operation == null) {
                            return null;
                        }
                        // If the last event was before 24 hours ago (tolerance period for missed events), we will just rebuild all indexes
                        if ((System.currentTimeMillis() - operation.getDate().getTimeInMillis())
                                % DateUtils.MILLIS_PER_HOUR < 24) {
                            rebuildAll(operation);
                            IndexOperation indexOperation = new IndexOperation();
                            indexOperation.setOperationType(OperationType.REBUILD);
                            return indexOperation;
                        }
                        // "Normal" flow: execute the index operation
                        try {
                            long startTime = System.currentTimeMillis();
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Running index operation: " + operation);
                            }
                            runOperation(operation);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Finished index operation: " + operation + " in "
                                        + DateHelper.secondsSince(startTime) + "s");
                            }
                        } catch (RuntimeException e) {
                            LOG.warn("Error running index operation " + operation, e);
                            throw e;
                        } finally {
                            // Write the properties to disk, so, when the server restarts, we know exactly where to resume
                            persistStatus(operation.getDate(), operation.getId());
                        }
                        return operation;
                    }
                });
        // Notify registered listeners
        if (operation != null) {
            for (IndexOperationListener listener : indexOperationListeners) {
                listener.onComplete(operation);
            }
        }
        hasMore = operation != null;
    }
}

From source file:nl.strohalm.cyclos.utils.tasks.TaskRunnerImpl.java

protected boolean doRunPollingTask(final String key, final Callable<Boolean> task) {
    return getTransactionHelper().runInCurrentThread(new TransactionCallback<Boolean>() {
        @Override/*from  w ww  . j ava2s  .co  m*/
        public Boolean doInTransaction(final TransactionStatus status) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Running polling task " + key);
                }
                return LoggedUser.runAsSystem(task);
            } catch (RuntimeException e) {
                LOG.error("Error running polling task" + key, e);
                return false;
            }
        }
    });
}