private UnitOfWork<?> startAndGetUnitOfWork() { return DefaultUnitOfWork.startAndGet(null); }
/** * Starts a new DefaultUnitOfWork instance, registering it a CurrentUnitOfWork. This methods returns the started * UnitOfWork instance. * <p> * Note that this Unit Of Work type is not meant to be shared among different Threads. A single DefaultUnitOfWork * instance should be used exclusively by the Thread that created it. * * @param message the message that will be processed in the context of the unit of work * @return the started UnitOfWork instance */ public static <T extends Message<?>> DefaultUnitOfWork<T> startAndGet(T message) { DefaultUnitOfWork<T> uow = new DefaultUnitOfWork<>(message); uow.start(); return uow; }
@Override public <R> ResultMessage<R> executeWithResult(Callable<R> task, RollbackConfiguration rollbackConfiguration) { if (phase() == Phase.NOT_STARTED) { start(); Assert.state(phase() == Phase.STARTED, () -> String.format("The UnitOfWork has an incompatible phase: %s", phase())); R result; ResultMessage<R> resultMessage; resultMessage = asResultMessage(e); if (rollbackConfiguration.rollBackOn(e)) { rollback(e); return resultMessage; setExecutionResult(new ExecutionResult(resultMessage)); try { commit(); } catch (Exception e) { resultMessage = asResultMessage(e);
@Override public ResultValidator<T> expectState(Consumer<T> aggregateStateValidator) { DefaultUnitOfWork<Message<?>> uow = DefaultUnitOfWork.startAndGet(null); try { state.get().execute(aggregateStateValidator); } finally { uow.rollback(); } return this; }
ScopeDescriptor deadlineScope = deadlineScope(serializer, jobData); DefaultUnitOfWork<DeadlineMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(deadlineMessage); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, return null; }); ResultMessage<?> resultMessage = unitOfWork.executeWithResult(chain::proceed); if (resultMessage.isExceptional()) { logger.error("Exception occurred during processing a deadline job [{}]",
/** * Handles the given {@code event} in the scope of a Unit of Work. If handling the event results in an exception * the exception will be wrapped in a {@link FixtureExecutionException}. * * @param event The event message to handle */ protected void handleInSaga(EventMessage<?> event) { ensureSagaResourcesInitialized(); ResultMessage<?> resultMessage = DefaultUnitOfWork.startAndGet(event).executeWithResult(() -> { sagaManager.handle(event, Segment.ROOT_SEGMENT); return null; }); if (resultMessage.isExceptional()) { Throwable e = resultMessage.exceptionResult(); if (Error.class.isAssignableFrom(e.getClass())) { throw (Error) e; } throw new FixtureExecutionException("Exception occurred while handling an event", e); } }
@Override public void execute(JobExecutionContext context) throws JobExecutionException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting a deadline job"); } JobDetail jobDetail = context.getJobDetail(); JobDataMap jobData = jobDetail.getJobDataMap(); try { SchedulerContext schedulerContext = context.getScheduler().getContext(); Serializer serializer = (Serializer) schedulerContext.get(JOB_DATA_SERIALIZER); TransactionManager transactionManager = (TransactionManager) schedulerContext.get(TRANSACTION_MANAGER_KEY); ScopeAwareProvider scopeAwareComponents = (ScopeAwareProvider) schedulerContext.get(SCOPE_AWARE_RESOLVER); DeadlineMessage<?> deadlineMessage = deadlineMessage(serializer, jobData); ScopeDescriptor deadlineScope = deadlineScope(serializer, jobData); DefaultUnitOfWork<DeadlineMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(deadlineMessage); unitOfWork.attachTransaction(transactionManager); unitOfWork.execute(() -> executeScheduledDeadline(scopeAwareComponents, deadlineMessage, deadlineScope)); if (LOGGER.isInfoEnabled()) { LOGGER.info("Job successfully executed. Deadline message [{}] processed.", deadlineMessage.getPayloadType().getSimpleName()); } } catch (Exception e) { LOGGER.error("Exception occurred during processing a deadline job [{}]", jobDetail.getDescription(), e); throw new JobExecutionException(e); } }
@SuppressWarnings("unchecked") @Override public void run() { EventMessage<?> eventMessage = createMessage(); if (logger.isDebugEnabled()) { logger.debug("Triggered the publication of event [{}]", eventMessage.getPayloadType().getSimpleName()); } try { UnitOfWork<EventMessage<?>> unitOfWork = new DefaultUnitOfWork<>(null); unitOfWork.attachTransaction(transactionManager); unitOfWork.execute(() -> eventBus.publish(eventMessage)); } finally { tokens.remove(tokenId); } }
@Override public TestExecutor<T> givenState(Supplier<T> aggregate) { clearGivenWhenState(); DefaultUnitOfWork.startAndGet(null).execute(() -> { if (repository == null) { registerRepository(new InMemoryRepository<>(aggregateType, eventStore, getRepositoryProvider())); } try { repository.newInstance(aggregate::get); } catch (Exception e) { throw new FixtureExecutionException( "An exception occurred while trying to initialize repository with given aggregate (using 'givenState')", e); } }); return this; }
@Override protected void setRollbackCause(Throwable cause) { setExecutionResult(new ExecutionResult(new GenericResultMessage<>(cause))); }
ScopeDescriptor deadlineScope = deadlineScope(serializer, jobData); DefaultUnitOfWork<DeadlineMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(deadlineMessage); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, return null; }); ResultMessage<?> resultMessage = unitOfWork.executeWithResult(chain::proceed); if (resultMessage.isExceptional()) { logger.error("Exception occurred during processing a deadline job [{}]",
private DeadlineMessage<?> consumeDeadline(DeadlineConsumer deadlineConsumer, ScheduledDeadlineInfo scheduledDeadlineInfo) { DefaultUnitOfWork<? extends DeadlineMessage<?>> uow = DefaultUnitOfWork.startAndGet(scheduledDeadlineInfo.deadlineMessage()); InterceptorChain chain = new DefaultInterceptorChain<>(uow, handlerInterceptors, deadlineMessage -> { deadlineConsumer.consume(scheduledDeadlineInfo.getDeadlineScope(), deadlineMessage); return deadlineMessage; }); ResultMessage<?> resultMessage = uow.executeWithResult(chain::proceed); if (resultMessage.isExceptional()) { Throwable e = resultMessage.exceptionResult(); throw new FixtureExecutionException("Exception occurred while handling the deadline", e); } return (DeadlineMessage<?>) resultMessage.getPayload(); } }
protected void executeStorageJob(EventMessage<?>... events) { UnitOfWork<?> unitOfWork = new DefaultUnitOfWork<>(null); unitOfWork.execute(() -> storeEvents(events)); }
@Override protected void setRollbackCause(Throwable cause) { setExecutionResult(new ExecutionResult(cause)); }
@Override public <R> R executeWithResult(Callable<R> task, RollbackConfiguration rollbackConfiguration) throws Exception { if (phase() == Phase.NOT_STARTED) { start(); } Assert.state(phase() == Phase.STARTED, () -> String.format("The UnitOfWork has an incompatible phase: %s", phase())); R result; try { result = task.call(); } catch (Error | Exception e) { if (rollbackConfiguration.rollBackOn(e)) { rollback(e); } else { setExecutionResult(new ExecutionResult(e)); commit(); } throw e; } setExecutionResult(new ExecutionResult(result)); commit(); return result; }
/** * Performs the actual handling logic. * * @param command The actual command to handle * @param handler The handler that must be invoked for this command * @param callback The callback to notify of the result * @param <C> The type of payload of the command * @param <R> The type of result expected from the command handler */ @SuppressWarnings({"unchecked"}) protected <C, R> void handle(CommandMessage<C> command, MessageHandler<? super CommandMessage<?>> handler, CommandCallback<? super C, ? super R> callback) { if (logger.isDebugEnabled()) { logger.debug("Handling command [{}]", command.getCommandName()); } UnitOfWork<CommandMessage<?>> unitOfWork = DefaultUnitOfWork.startAndGet(command); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, handlerInterceptors, handler); CommandResultMessage<R> resultMessage = asCommandResultMessage(unitOfWork.executeWithResult(chain::proceed, rollbackConfiguration)); callback.onResult(command, resultMessage); }
/** * Starts a new DefaultUnitOfWork instance, registering it a CurrentUnitOfWork. This methods returns the started * UnitOfWork instance. * <p> * Note that this Unit Of Work type is not meant to be shared among different Threads. A single DefaultUnitOfWork * instance should be used exclusively by the Thread that created it. * * @param message the message that will be processed in the context of the unit of work * @return the started UnitOfWork instance */ public static <T extends Message<?>> DefaultUnitOfWork<T> startAndGet(T message) { DefaultUnitOfWork<T> uow = new DefaultUnitOfWork<>(message); uow.start(); return uow; }
@Override public void run() { if (logger.isDebugEnabled()) { logger.debug("Triggered deadline"); } try { Instant triggerInstant = GenericEventMessage.clock.instant(); UnitOfWork<DeadlineMessage<?>> unitOfWork = new DefaultUnitOfWork<>( new GenericDeadlineMessage<>(deadlineName, deadlineMessage, () -> triggerInstant)); unitOfWork.attachTransaction(transactionManager); InterceptorChain chain = new DefaultInterceptorChain<>(unitOfWork, handlerInterceptors(), deadlineMessage -> { executeScheduledDeadline(deadlineMessage, deadlineScope); return null; }); ResultMessage<?> resultMessage = unitOfWork.executeWithResult(chain::proceed); if (resultMessage.isExceptional()) { Throwable e = resultMessage.exceptionResult(); throw new DeadlineException(format("An error occurred while triggering the deadline %s %s", deadlineName, deadlineId), e); } } finally { scheduledTasks.remove(new DeadlineId(deadlineName, deadlineId)); } }