org.axonframework.common.Assert.state()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(124)

本文整理了Java中org.axonframework.common.Assert.state()方法的一些代码示例,展示了Assert.state()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Assert.state()方法的具体详情如下:
包路径:org.axonframework.common.Assert
类名称:Assert
方法名:state

Assert.state介绍

[英]Asserts that the value of state is true. If not, an IllegalStateException is thrown.
[中]断言state的值为true。如果不是,则抛出IllegalStateException。

代码示例

代码示例来源:origin: AxonFramework/AxonFramework

public Aggregate<T> getAggregate() {
  Assert.state(!rolledBack, () -> "The state of this aggregate cannot be retrieved because it " +
      "has been modified in a Unit of Work that was rolled back");
  return aggregate;
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
   * Updates the builder function for this component.
   *
   * @param builderFunction The new builder function for the component
   * @throws IllegalStateException when the component has already been retrieved using {@link #get()}.
   */
  public void update(Function<Configuration, ? extends B> builderFunction) {
    Assert.state(instance == null, () -> "Cannot change " + name + ": it is already in use");
    this.builderFunction = builderFunction;
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

private void ensureInitialized() {
    Assert.state(config != null, () -> "Configuration is not initialized yet");
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Returns the Repository instance for Aggregate with given {@code typeIdentifier} used by the
 * CommandHandlerInvoker that is running on the current thread.
 * <p>
 * Calling this method from any other thread will return {@code null}.
 *
 * @param type The type of aggregate
 * @param <T>  The type of aggregate
 * @return the repository instance for aggregate of given type
 */
@SuppressWarnings("unchecked")
public static <T> DisruptorRepository<T> getRepository(Class<?> type) {
  final CommandHandlerInvoker invoker = CURRENT_INVOKER.get();
  Assert.state(invoker != null,
         () -> "The repositories of a DisruptorCommandBus are only available " + "in the invoker thread");
  return invoker.repositories.get(type);
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public Aggregate<T> newInstance(Callable<T> factoryMethod) throws Exception {
  Assert.state(storedAggregate == null,
         () -> "Creating an Aggregate while one is already stored. Test fixtures do not allow multiple instances to be stored.");
  storedAggregate = AnnotatedAggregate.initialize(factoryMethod,
                          aggregateModel,
                          eventBus,
                          repositoryProvider,
                          true);
  return storedAggregate;
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
protected void prepareForCommit(LockAwareAggregate<T, A> aggregate) {
  Assert.state(aggregate.isLockHeld(), () -> "An aggregate is being used for which a lock is no longer held");
  super.prepareForCommit(aggregate);
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Initializes current unit of work with interceptor chain.
 *
 * @param interceptorChain the interceptor chain
 */
public static void initialize(InterceptorChain interceptorChain) {
  Assert.state(CurrentUnitOfWork.isStarted(),
         () -> "An active Unit of Work is required for injecting interceptor chain");
  CurrentUnitOfWork.get().resources().put(INTERCEPTOR_CHAIN_EMITTER_KEY, interceptorChain);
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public void commit() {
  if (logger.isDebugEnabled()) {
    logger.debug("Committing Unit Of Work");
  }
  Assert.state(phase() == Phase.STARTED, () -> String.format("The UnitOfWork is in an incompatible phase: %s", phase()));
  Assert.state(isCurrent(), () -> "The UnitOfWork is not the current Unit of Work");
  try {
    if (isRoot()) {
      commitAsRoot();
    } else {
      commitAsNested();
    }
  } finally {
    CurrentUnitOfWork.clear(this);
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Initialize conflict resolution in the context of the current Unit of Work dealing with a command on an event
 * sourced aggregate.
 *
 * @param conflictResolver conflict resolver able to detect conflicts
 */
public static void initialize(ConflictResolver conflictResolver) {
  Assert.state(CurrentUnitOfWork.isStarted(), () -> "An active Unit of Work is required for conflict resolution");
  CurrentUnitOfWork.get().getOrComputeResource(CONFLICT_RESOLUTION_KEY, key -> conflictResolver);
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Set the execution result of processing the current {@link #getMessage() Message}. In case this context has a
 * previously set ExecutionResult, setting a new result is only allowed if the new result is an exception result.
 * <p/>
 * In case the previously set result is also an exception result, the exception in the new execution result is
 * added to the original exception as a suppressed exception.
 *
 * @param executionResult the ExecutionResult of the currently handled Message
 */
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
public void setExecutionResult(ExecutionResult executionResult) {
  Assert.state(this.executionResult == null || executionResult.isExceptionResult(),
         () -> String.format("Cannot change execution result [%s] to [%s] for message [%s].",
          message, this.executionResult, executionResult));
  if (this.executionResult != null && this.executionResult.isExceptionResult()) {
    this.executionResult.getExceptionResult().addSuppressed(executionResult.getExceptionResult());
  } else {
    this.executionResult = executionResult;
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public void cancelSchedule(ScheduleToken scheduleToken) {
  if (!(scheduleToken instanceof QuartzScheduleToken)) {
    throw new IllegalArgumentException("The given ScheduleToken was not provided by this scheduler.");
  }
  Assert.state(initialized, () -> "Scheduler is not yet initialized");
  QuartzScheduleToken reference = (QuartzScheduleToken) scheduleToken;
  try {
    if (!scheduler.deleteJob(jobKey(reference.getJobIdentifier(), reference.getGroupIdentifier()))) {
      logger.warn("The job belonging to this token could not be deleted.");
    }
  } catch (SchedulerException e) {
    throw new SchedulingException("An error occurred while cancelling a timer for a saga", e);
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public void rollback(Throwable cause) {
  if (logger.isDebugEnabled()) {
    logger.debug("Rolling back Unit Of Work.", cause);
  }
  Assert.state(isActive() && phase().isBefore(Phase.ROLLBACK),
         () -> String.format("The UnitOfWork is in an incompatible phase: %s", phase()));
  Assert.state(isCurrent(), () -> "The UnitOfWork is not the current Unit of Work");
  try {
    setRollbackCause(cause);
    changePhase(Phase.ROLLBACK);
    if (isRoot()) {
      changePhase(Phase.CLEANUP, Phase.CLOSED);
    }
  } finally {
    CurrentUnitOfWork.clear(this);
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
protected void addHandler(Phase phase, Consumer<UnitOfWork<T>> handler) {
  Assert.state(!phase.isBefore(phase()), () -> "Cannot register a listener for phase: " + phase
      + " because the Unit of Work is already in a later phase: " + phase());
  processingContext.addHandler(phase, handler);
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public void publish(List<? extends EventMessage<?>> events) {
  Stream<MessageMonitor.MonitorCallback> ingested = events.stream().map(messageMonitor::onMessageIngested);
  if (CurrentUnitOfWork.isStarted()) {
    UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get();
    Assert.state(!unitOfWork.phase().isAfter(PREPARE_COMMIT),
           () -> "It is not allowed to publish events when the current Unit of Work has already been " +
               "committed. Please start a new Unit of Work before publishing events.");
    Assert.state(!unitOfWork.root().phase().isAfter(PREPARE_COMMIT),
           () -> "It is not allowed to publish events when the root Unit of Work has already been " +
               "committed.");
    unitOfWork.afterCommit(u -> ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess));
    unitOfWork.onRollback(uow -> ingested.forEach(
        message -> message.reportFailure(uow.getExecutionResult().getExceptionResult())
    ));
    eventsQueue(unitOfWork).addAll(events);
  } else {
    try {
      prepareCommit(intercept(events));
      commit(events);
      afterCommit(events);
      ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess);
    } catch (Exception e) {
      ingested.forEach(m -> m.reportFailure(e));
      throw e;
    }
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public ScheduleToken schedule(Instant triggerDateTime, Object event) {
  Assert.state(initialized, () -> "Scheduler is not yet initialized");
  EventMessage eventMessage = GenericEventMessage.asEventMessage(event);
  String jobIdentifier = JOB_NAME_PREFIX + eventMessage.getIdentifier();
  QuartzScheduleToken tr = new QuartzScheduleToken(jobIdentifier, groupIdentifier);
  try {
    JobDetail jobDetail = buildJobDetail(eventMessage, new JobKey(jobIdentifier, groupIdentifier));
    scheduler.scheduleJob(jobDetail, buildTrigger(triggerDateTime, jobDetail.getKey()));
  } catch (SchedulerException e) {
    throw new SchedulingException("An error occurred while setting a timer for a saga", e);
  }
  return tr;
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
public void start() {
  if (logger.isDebugEnabled()) {
    logger.debug("Starting Unit Of Work");
  }
  Assert.state(Phase.NOT_STARTED.equals(phase()), () -> "UnitOfWork is already started");
  rolledBack = false;
  onRollback(u -> rolledBack = true);
  CurrentUnitOfWork.ifStarted(parent -> {
    // we're nesting.
    this.parentUnitOfWork = parent;
    root().onCleanup(r -> changePhase(Phase.CLEANUP, Phase.CLOSED));
  });
  changePhase(Phase.STARTED);
  CurrentUnitOfWork.set(this);
}

代码示例来源:origin: AxonFramework/AxonFramework

@Override
@SuppressWarnings("unchecked")
public <C, R> void dispatch(CommandMessage<C> command, CommandCallback<? super C, ? super R> callback) {
  Assert.state(started, () -> "CommandBus has been shut down. It is not accepting any Commands");
  CommandMessage<? extends C> commandToDispatch = command;
  for (MessageDispatchInterceptor<? super CommandMessage<?>> interceptor : dispatchInterceptors) {
    commandToDispatch = (CommandMessage) interceptor.handle(commandToDispatch);
  }
  MessageMonitor.MonitorCallback monitorCallback = messageMonitor.onMessageIngested(commandToDispatch);
  try {
    doDispatch(commandToDispatch, new MonitorAwareCallback(callback, monitorCallback));
  } catch (Exception e) {
    monitorCallback.reportFailure(e);
    callback.onResult(commandToDispatch, asCommandResultMessage(e));
  }
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Creates an {@link EventMessage} with given {@code payload} and {@code metaData}.
 *
 * @param payload  payload of the resulting message
 * @param metaData metadata of the resulting message
 * @param <P>      the payload type
 * @return the resulting message
 */
protected <P> EventMessage<P> createMessage(P payload, MetaData metaData) {
  if (lastKnownSequence != null) {
    long seq = lastKnownSequence + 1;
    String id = identifierAsString();
    if (id == null) {
      Assert.state(seq == 0,
             () -> "The aggregate identifier has not been set. It must be set at the latest when applying the creation event");
      return new LazyIdentifierDomainEventMessage<>(type(), seq, payload, metaData);
    }
    return new GenericDomainEventMessage<>(type(), identifierAsString(), seq, payload, metaData);
  }
  return new GenericEventMessage<>(payload, metaData);
}

代码示例来源:origin: AxonFramework/AxonFramework

/**
 * Resets tokens to the given {@code startPosition}. This effectively causes a replay of events since that position.
 * <p>
 * Note that the new token must represent a position that is <em>before</em> the current position of the processor.
 * <p>
 * Before attempting to reset the tokens, the caller must stop this processor, as well as any instances of the
 * same logical processor that may be running in the cluster. Failure to do so will cause the reset to fail,
 * as a processor can only reset the tokens if it is able to claim them all.
 *
 * @param startPosition The token representing the position to reset the processor to.
 */
public void resetTokens(TrackingToken startPosition) {
  Assert.state(supportsReset(), () -> "The handlers assigned to this Processor do not support a reset");
  Assert.state(!isRunning() && activeProcessorThreads() == 0,
         () -> "TrackingProcessor must be shut down before triggering a reset");
  transactionManager.executeInTransaction(() -> {
    int[] segments = tokenStore.fetchSegments(getName());
    TrackingToken[] tokens = new TrackingToken[segments.length];
    for (int i = 0; i < segments.length; i++) {
      tokens[i] = tokenStore.fetchToken(getName(), segments[i]);
    }
    // we now have all tokens, hurray
    eventHandlerInvoker().performReset();
    for (int i = 0; i < tokens.length; i++) {
      tokenStore.storeToken(ReplayToken.createReplayToken(tokens[i], startPosition), getName(), segments[i]);
    }
  });
}

代码示例来源:origin: AxonFramework/AxonFramework

start();
Assert.state(phase() == Phase.STARTED, () -> String.format("The UnitOfWork has an incompatible phase: %s", phase()));
R result;
ResultMessage<R> resultMessage;

相关文章