/**
  * Connects this member to the cluster using the given <code>loadFactor</code>. The <code>
  * loadFactor</code> defines the (approximate) relative load that this member will receive.
  *
  * <p>A good default value is 100, which will give this member 100 nodes on the distributed hash
  * ring. Giving all members (proportionally) lower values will result in a less evenly distributed
  * hash.
  *
  * @param loadFactor The load factor for this node.
  * @throws ConnectionFailedException when an error occurs while connecting
  */
 public synchronized void connect(int loadFactor) throws ConnectionFailedException {
   this.currentLoadFactor = loadFactor;
   Assert.isTrue(loadFactor >= 0, "Load Factor must be a positive integer value.");
   Assert.isTrue(
       channel.getReceiver() == null || channel.getReceiver() == messageReceiver,
       "The given channel already has a receiver configured. "
           + "Has the channel been reused with other Connectors?");
   try {
     channel.setReceiver(messageReceiver);
     if (channel.isConnected() && !clusterName.equals(channel.getClusterName())) {
       throw new AxonConfigurationException(
           "The Channel that has been configured with this JGroupsConnector "
               + "is already connected to another cluster.");
     } else if (channel.isConnected()) {
       // we need to fetch state now that we have attached our MessageReceiver
       channel.getState(null, 10000);
     } else {
       // we need to connect. This will automatically fetch state as well.
       channel.connect(clusterName, null, 10000);
     }
     updateMembership();
   } catch (Exception e) {
     joinedCondition.markJoined(false);
     channel.disconnect();
     throw new ConnectionFailedException("Failed to connect to JGroupsConnectorFactoryBean", e);
   }
 }
 /**
  * Initializes the QuartzEventScheduler. Makes the configured {@link EventBus} available to the
  * Quartz Scheduler.
  *
  * @throws SchedulerException if an error occurs preparing the Quartz Scheduler for use.
  */
 @PostConstruct
 public void initialize() throws SchedulerException {
   Assert.notNull(scheduler, () -> "A Scheduler must be provided.");
   Assert.notNull(eventBus, () -> "An EventBus must be provided.");
   Assert.notNull(jobDataBinder, () -> "An EventJobDataBinder must be provided.");
   scheduler.getContext().put(FireEventJob.EVENT_BUS_KEY, eventBus);
   scheduler.getContext().put(FireEventJob.TRANSACTION_MANAGER_KEY, transactionManager);
   scheduler.getContext().put(FireEventJob.EVENT_JOB_DATA_BINDER_KEY, jobDataBinder);
   initialized = true;
 }
  /**
   * Initialize the SimpleEventScheduler using the given <code>executorService</code> as trigger and
   * execution mechanism, and publishes events to the given <code>eventBus</code>. The <code>
   * eventTriggerCallback</code> is invoked just before and after publication of a scheduled event.
   *
   * @param executorService The backing ScheduledExecutorService
   * @param eventBus The Event Bus on which Events are to be published
   * @param eventTriggerCallback To notify when an event is published
   */
  public SimpleEventScheduler(
      ScheduledExecutorService executorService,
      EventBus eventBus,
      EventTriggerCallback eventTriggerCallback) {
    Assert.notNull(executorService, "The ScheduledExecutorService may not be null");
    Assert.notNull(eventBus, "The EventBus may not be null");

    this.executorService = executorService;
    this.eventBus = eventBus;
    this.eventTriggerCallback = eventTriggerCallback;
  }
  /**
   * Initialize the SimpleEventScheduler using the given <code>executorService</code> as trigger and
   * execution mechanism, and publishes events to the given <code>eventBus</code>. The <code>
   * eventTriggerCallback</code> is invoked just before and after publication of a scheduled event.
   *
   * @param executorService The backing ScheduledExecutorService
   * @param eventBus The Event Bus on which Events are to be published
   * @param unitOfWorkFactory The factory that creates the Unit of Work to manage transactions
   */
  public SimpleEventScheduler(
      ScheduledExecutorService executorService,
      EventBus eventBus,
      UnitOfWorkFactory unitOfWorkFactory) {
    Assert.notNull(executorService, "The ScheduledExecutorService may not be null");
    Assert.notNull(eventBus, "The EventBus may not be null");

    this.executorService = executorService;
    this.eventBus = eventBus;
    this.unitOfWorkFactory = unitOfWorkFactory;
  }
 @Override
 public Object invoke(Object target, Message message)
     throws InvocationTargetException, IllegalAccessException {
   Assert.isTrue(
       method.getDeclaringClass().isInstance(target),
       "Given target is not an instance of the method's owner.");
   Assert.notNull(message, "Event may not be null");
   Object[] parameterValues = new Object[getParameterValueResolvers().length];
   for (int i = 0; i < parameterValues.length; i++) {
     parameterValues[i] = getParameterValueResolvers()[i].resolveParameterValue(message);
   }
   return method.invoke(target, parameterValues);
 }
Exemple #6
0
 /**
  * Checks that the given name is unique within the given business unit. If the name is not unique,
  * an IllegalArgumentExcption is raised and processing terminates.
  *
  * @param locationId The identifier of the location to check.
  * @param name The location name to check for uniqueness.
  * @param businessUnitId The business unit within which to check.
  */
 private void checkUniqueName(LocationId locationId, String name, BusinessUnitId businessUnitId) {
   Assert.notNull(locationRepository, "null repository");
   boolean isUnique = locationRepository.checkUniqueName(locationId, name, businessUnitId);
   if (!isUnique) {
     throw new IllegalArgumentException("duplicate name within the business unit");
   }
 }
 /**
  * {@inheritDoc}
  *
  * <p>This implementation is aware of a special type of <code>DomainEvents</code>: the <code>
  * AggregateSnapshot</code>, which is a snapshot event, containing the actual aggregate inside.
  *
  * <p><code>AggregateSnapshot</code> events are used to initialize the aggregate with the correct
  * version ({@link #getVersion()}).
  *
  * @throws IllegalStateException if this aggregate was already initialized.
  */
 @Override
 public void initializeState(DomainEventStream domainEventStream) {
   Assert.state(getUncommittedEventCount() == 0, "Aggregate is already initialized");
   long lastSequenceNumber = -1;
   while (domainEventStream.hasNext()) {
     DomainEventMessage event = domainEventStream.next();
     lastSequenceNumber = event.getSequenceNumber();
     handleRecursively(event);
   }
   initializeEventStream(lastSequenceNumber);
 }
 /**
  * Returns a new {@link GapAwareTrackingToken} instance based on the given {@code index} and
  * collection of {@code gaps}.
  *
  * @param index the highest global sequence number of events up until (and including) this
  *     tracking token
  * @param gaps global sequence numbers of events that have not been seen yet even though these
  *     sequence numbers are smaller than the current index. These missing sequence numbers may be
  *     filled in later when those events get committed to the store or may never be filled in if
  *     those events never get committed.
  * @return a new tracking token from given index and gaps
  */
 public static GapAwareTrackingToken newInstance(long index, Collection<Long> gaps) {
   if (gaps.isEmpty()) {
     return new GapAwareTrackingToken(index, Collections.emptySortedSet());
   }
   SortedSet<Long> gapSet = new TreeSet<>(gaps);
   Assert.isTrue(
       gapSet.last() < index,
       () ->
           String.format(
               "Gap indices [%s] should all be smaller than head index [%d]", gaps, index));
   return new GapAwareTrackingToken(index, gapSet);
 }
 /**
  * Initialize the AbstractCommandGateway with given <code>commandBus</code>, <code>retryScheduler
  * </code> and <code>commandDispatchInterceptors</code>.
  *
  * @param commandBus The command bus on which to dispatch events
  * @param retryScheduler The scheduler capable of performing retries of failed commands. May be
  *     <code>null</code> when to prevent retries.
  * @param commandDispatchInterceptors The interceptors to invoke when dispatching a command
  */
 protected AbstractCommandGateway(
     CommandBus commandBus,
     RetryScheduler retryScheduler,
     List<CommandDispatchInterceptor> commandDispatchInterceptors) {
   Assert.notNull(commandBus, "commandBus may not be null");
   this.commandBus = commandBus;
   if (commandDispatchInterceptors != null && !commandDispatchInterceptors.isEmpty()) {
     this.dispatchInterceptors =
         new ArrayList<CommandDispatchInterceptor>(commandDispatchInterceptors);
   } else {
     this.dispatchInterceptors = Collections.emptyList();
   }
   this.retryScheduler = retryScheduler;
 }
 @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;
 }
  @Override
  public void cancelSchedule(ScheduleToken scheduleToken) {
    if (!QuartzScheduleToken.class.isInstance(scheduleToken)) {
      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);
    }
  }
  /**
   * Initializes a Saga Repository with a <code>JavaSerializer</code>.
   *
   * @param entityManagerProvider The EntityManagerProvider providing the EntityManager instance for
   *     this repository
   */
  public JpaSagaStore(EntityManagerProvider entityManagerProvider) {
    Assert.notNull(entityManagerProvider, "entityManagerProvider may not be null");
    this.entityManagerProvider = entityManagerProvider;

    serializer = new JavaSerializer();

    EntityManager entityManager = this.entityManagerProvider.getEntityManager();
    EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
    entityManagerFactory.addNamedQuery(
        LOAD_SAGA_NAMED_QUERY, entityManager.createQuery(LOAD_SAGA_QUERY));
    entityManagerFactory.addNamedQuery(
        DELETE_ASSOCIATION_NAMED_QUERY, entityManager.createQuery(DELETE_ASSOCIATION_QUERY));
    entityManagerFactory.addNamedQuery(
        FIND_ASSOCIATION_IDS_NAMED_QUERY, entityManager.createQuery(FIND_ASSOCIATION_IDS_QUERY));
    entityManagerFactory.addNamedQuery(
        DELETE_ASSOCIATIONS_NAMED_QUERY, entityManager.createQuery(DELETE_ASSOCIATIONS_QUERY));
    entityManagerFactory.addNamedQuery(
        FIND_ASSOCIATIONS_NAMED_QUERY, entityManager.createQuery(FIND_ASSOCIATIONS_QUERY));
    entityManagerFactory.addNamedQuery(
        DELETE_SAGA_NAMED_QUERY, entityManager.createQuery(DELETE_SAGA_QUERY));
    entityManagerFactory.addNamedQuery(
        UPDATE_SAGA_NAMED_QUERY, entityManager.createQuery(UPDATE_SAGA_QUERY));
  }
 /**
  * Sets the interface that describes the gateway instance to describe. If no interface is
  * provided, it defaults to {@link CommandGateway}.
  *
  * @param gatewayInterface The interface describing the gateway
  * @throws IllegalArgumentException if the given <code>gatewayInterface</code> is <code>null
  *     </code> or not an interface.
  */
 public void setGatewayInterface(Class<T> gatewayInterface) {
   Assert.notNull(gatewayInterface, "The given gateway interface may not be null");
   Assert.isTrue(
       gatewayInterface.isInterface(), "The given gateway interface must be an interface");
   this.gatewayInterface = gatewayInterface;
 }
 /**
  * Initialize the writer to write the object structure to the given <code>root</code> DBObject.
  *
  * <p>Note that the given <code>root</code> DBObject must not contain any data yet.
  *
  * @param root The root DBObject to which the serialized structure will be added. Must not contain
  *     any data.
  */
 public DBObjectHierarchicalStreamWriter(DBObject root) {
   Assert.isTrue(root.keySet().isEmpty(), "The given root object must be empty.");
   this.root = root;
 }
 /**
  * Initializes a <code>ClusteringEventBus</code> with the given <code>clusterSelector</code> and a
  * <code>terminal</code>.
  *
  * @param clusterSelector The Cluster Selector that chooses the cluster for each of the subscribed
  *     event listeners
  * @param terminal The terminal responsible for publishing incoming events to each of the clusters
  */
 public ClusteringEventBus(ClusterSelector clusterSelector, EventBusTerminal terminal) {
   Assert.notNull(clusterSelector, "clusterSelector may not be null");
   Assert.notNull(terminal, "terminal may not be null");
   this.clusterSelector = clusterSelector;
   this.terminal = terminal;
 }