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.services.application.ApplicationServiceImpl.java

/**
 * Run all given local initializations in its own transaction
 *//*  w w w.  j a v a  2 s. co m*/
private void runAll(final Collection<LocalInitialization> initializations) {
    for (final LocalInitialization initialization : initializations) {
        LOG.debug(String.format("Running initialization (%s)...", initialization.getName()));
        transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(final TransactionStatus status) {
                initialization.initialize();
            }
        });
    }
}

From source file:nl.strohalm.cyclos.services.customization.TranslationMessageServiceImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    getCache().addListener(new CacheAdapter() {
        @Override/*  w w w  .  j  a  v a2 s  .com*/
        public void onCacheCleared(final Cache cache) {
            transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(final TransactionStatus status) {
                    notifyListeners(exportAsProperties());
                }
            });
        }
    });
}

From source file:nl.strohalm.cyclos.services.elements.MessageServiceImpl.java

/**
 * This methods runs a new transaction for handling the sms status, charging, etc... Then, the log is always persisted in another transaction
 * (with a {@link TransactionEndListener}). So, even if the sending fails, the log is persisted
 *//*from   w  w  w .j  a va 2s . c o m*/
@Override
public SmsLog sendSms(final SendSmsDTO params) {
    final MutableObject result = new MutableObject();
    transactionHelper.runInNewTransaction(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            // The returned log is transient...
            SmsLog log;
            try {
                log = doSendSms(params);
            } catch (LockingException e) {
                throw e;
            } catch (Exception e) {
                LOG.error("Unknown error sending sms", e);
                log = newSmsLog(params, ErrorType.SEND_ERROR, false);
            }
            if (log.getErrorType() != null) {
                status.setRollbackOnly();
            }
            // ... we can only actually persist it after this transaction ends, because we don't know if it will be committed
            final SmsLog toSave = log;
            CurrentTransactionData.addTransactionEndListener(new TransactionEndListener() {
                @Override
                protected void onTransactionEnd(final boolean commit) {
                    transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
                        @Override
                        protected void doInTransactionWithoutResult(final TransactionStatus status) {
                            result.setValue(smsLogService.save(toSave));
                        }
                    });
                }
            });
        }
    });
    return (SmsLog) result.getValue();
}

From source file:nl.strohalm.cyclos.services.stats.tests.TestDatabaseForStats.java

public static void main(final String[] args) throws Exception {

    final StopWatch sw = new StopWatch();
    sw.start();/* w  w  w .j  ava  2  s .  c  om*/
    APPLICATION_CONTEXT = new CustomApplicationContext(FILES, TestDatabaseForStats.class);
    System.out.printf("Total startup time: %.3f\n", sw.getTime() / 1000D);

    final TransactionTemplate template = bean("transactionTemplate");

    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            try {
                TestDatabaseForStats.doInTransaction();
            } catch (final ValidationException e) {
                System.out.println("Validation failed.");
                final Collection<ValidationError> generalErrors = e.getGeneralErrors();
                if (generalErrors != null && !generalErrors.isEmpty()) {
                    System.out.println("General errors:");
                    for (final ValidationError error : generalErrors) {
                        System.out.println(error.getKey());
                    }
                }
                final Map<String, Collection<ValidationError>> errorsByProperty = e.getErrorsByProperty();
                if (errorsByProperty != null && !errorsByProperty.isEmpty()) {
                    for (final Map.Entry<String, Collection<ValidationError>> entry : errorsByProperty
                            .entrySet()) {
                        final String name = entry.getKey();
                        final Collection<ValidationError> errors = entry.getValue();
                        if (errors != null && !errors.isEmpty()) {
                            System.out.println("Property errors for '" + name + "':");
                            for (final ValidationError error : errors) {
                                System.out.println(error.getKey());
                            }
                        }
                    }
                }
            } catch (final Exception e) {
                status.setRollbackOnly();
                e.printStackTrace();
            }
        }
    });

    updateGroupChangeLog(groupChanges);

    System.out.println("FINISHED");
    System.exit(0);
}

From source file:nl.strohalm.cyclos.services.transactions.ScheduledPaymentServiceImpl.java

@Override
public void cancelScheduledPaymentsAndNotify(final Member member,
        final Collection<MemberAccountType> accountTypes) {
    List<ScheduledPayment> scheduledPayments = scheduledPaymentDao.getUnrelatedPendingPayments(member,
            accountTypes);// w  w w.  j a v a  2  s .co m
    final Set<Member> membersToNotify = new HashSet<Member>();
    final Set<MemberAccountType> removedAccounts = new HashSet<MemberAccountType>();

    // this flag is true if the member was not removed and at least on of the incoming payment should notify the receiver (in this case the
    // member)
    // or is from an invoice or there is at least one outgoing payment (the member is the payer)
    final MutableBoolean notifyMember = new MutableBoolean(false);
    for (ScheduledPayment scheduledPayment : scheduledPayments) {
        cancel(scheduledPayment);

        boolean incoming = member.equals(scheduledPayment.getToOwner());
        if (incoming) { // member is the receiver then notify the payer
            if (scheduledPayment.getFromOwner() instanceof Member) { // there is not notification for incoming system payments
                Member payer = (Member) scheduledPayment.getFromOwner();
                membersToNotify.add(payer);
                if (!member.getGroup().isRemoved() && !notifyMember.booleanValue()) {
                    notifyMember
                            .setValue(scheduledPayment.isShowToReceiver() || isFromInvoice(scheduledPayment));
                }
                removedAccounts.add((MemberAccountType) scheduledPayment.getTo().getType());
            }
        } else { // outgoing (member is the payer)
            if (scheduledPayment.getToOwner() instanceof Member) { // there is not notification for outgoing system payments
                if (scheduledPayment.isShowToReceiver() || isFromInvoice(scheduledPayment)) {
                    Member receiver = (Member) scheduledPayment.getToOwner();
                    membersToNotify.add(receiver);
                }
                removedAccounts.add((MemberAccountType) scheduledPayment.getFrom().getType());
            }
            if (!member.getGroup().isRemoved()) {
                notifyMember.setValue(true);
            }
        }
    }

    if (!scheduledPayments.isEmpty()) {
        CurrentTransactionData.addTransactionCommitListener(new TransactionCommitListener() {
            @Override
            public void onTransactionCommit() {
                transactionHelper.runInCurrentThread(new TransactionCallbackWithoutResult() {
                    @Override
                    protected void doInTransactionWithoutResult(final TransactionStatus status) {
                        memberNotificationHandler.scheduledPaymentsCancelledNotification(member,
                                notifyMember.booleanValue(), membersToNotify, removedAccounts);
                    }
                });
            }
        });
    }
}

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

private void createAlert(final SystemAlert.Alerts type, final Class<? extends Indexable> entityType) {
    transactionHelper.runInNewTransaction(new TransactionCallbackWithoutResult() {
        @Override// w  w w.  j  av  a2s.  c om
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            alertService.create(type, resolveAlertArguments(entityType));
        }
    });
}

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

protected void doRunInitialization(final String beanName) {
    final InitializingService service = applicationContext.getBean(beanName, InitializingService.class);
    getTransactionHelper().runInCurrentThread(new TransactionCallbackWithoutResult() {
        @Override/*w  w  w.  j  a  v  a  2s.c o m*/
        protected void doInTransactionWithoutResult(final TransactionStatus status) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Running initialization for bean " + beanName);
                }
                LoggedUser.runAsSystem(Executors.callable(new Runnable() {
                    @Override
                    public void run() {
                        service.initializeService();
                    }
                }));
            } catch (RuntimeException e) {
                LOG.error("Error running initialization for bean " + beanName, e);
                throw e;
            }
        }
    });
}

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

protected void doRunScheduledTask(final String taskName, final Calendar time) {
    final ScheduledTask task = getSchedulingHandler().getTask(taskName);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Running scheduled task " + taskName + " with base time " + FormatObject.formatObject(time));
    }//from w ww  . j  a  v a  2 s  . com
    if (task.shouldRunInTransaction()) {
        getTransactionHelper().runInCurrentThread(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(final TransactionStatus status) {
                if (!doRunScheduledTask(task, time)) {
                    status.setRollbackOnly();
                }
            }
        });
    } else {
        doRunScheduledTask(task, time);
    }
}

From source file:org.apache.camel.bam.ProcessBuilder.java

public Processor createActivityProcessor(ActivityBuilder activityBuilder) {
    notNull(jpaTemplate, "jpaTemplate");
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            processRules.setProcessDefinition(getProcessDefinition());
        }/*from   w  w  w. j  ava 2 s .  c  om*/
    });
    return new JpaBamProcessor(getTransactionTemplate(), getJpaTemplate(),
            activityBuilder.getCorrelationExpression(), activityBuilder.getActivityRules(), getEntityType());
}

From source file:org.apache.camel.bam.processor.ActivityMonitorEngine.java

public void run() {
    LOG.debug("Starting to poll for timeout events");

    while (!isStopped()) {
        try {/*from   w  ww.  java2 s. c  o  m*/
            long now = System.currentTimeMillis();
            long nextPoll = now + windowMillis;
            final Date timeNow = new Date(now);

            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    Map<String, Object> params = new HashMap<String, Object>(1);
                    params.put("timeNow", timeNow);

                    List<ActivityState> list = CastUtils.cast(template.findByNamedParams("select x from "
                            + QueryUtils.getTypeName(ActivityState.class) + " x where x.timeOverdue < :timeNow",
                            params));
                    for (ActivityState activityState : list) {
                        fireExpiredEvent(activityState);
                    }
                }
            });

            long timeToSleep = nextPoll - System.currentTimeMillis();
            if (timeToSleep > 0) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Sleeping for " + timeToSleep + " millis");
                }
                try {
                    Thread.sleep(timeToSleep);
                } catch (InterruptedException e) {
                    LOG.debug("Caught: " + e, e);
                }
            }
        } catch (Exception e) {
            LOG.error("Caught: " + e, e);
        }
    }
}