io.vlingo.actors.Stage Java Examples

The following examples show how to use io.vlingo.actors.Stage. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 6 votes vote down vote up
public static Server startWithAgent(
        final Stage stage,
        final Resources resources,
        final Filters filters,
        final int port,
        final int dispatcherPoolSize,
        final String severMailboxTypeName) {

  final Server server = stage.actorFor(
          Server.class,
          Definition.has(
                  ServerActor.class,
                  new ServerWithAgentInstantiator(resources, filters, port, dispatcherPoolSize),
                  severMailboxTypeName,
                  ServerActor.ServerName),
          stage.world().addressFactory().withHighId(),
          stage.world().defaultLogger());

  server.startUp();

  return server;
}
 
Example #2
Source File: Calculation.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
static Completes<CalculationState> calculate(final Stage stage,
                                             final Operation operation,
                                             final Integer anOperand,
                                             final Integer anotherOperand) {

    final Completes<Set<CalculationState>> calculations =
            CalculationQueryProvider.instance().queries().allCalculations();

    return calculations.andThenTo(existingCalculations -> {
        final Address address =
                stage.addressFactory().uniqueWith(generateName());

        final Definition definition =
                Definition.has(CalculationEntity.class, Definition.parameters(CalculationId.from(address.idString())));

        final Calculation calculation = stage.actorFor(Calculation.class, definition, address);

        return calculation.calculate(operation, anOperand, anotherOperand, existingCalculations);
    });
}
 
Example #3
Source File: Order.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
static Completes<OrderState> register(final ApplicationRegistry registry,
                                      final ProductId productId,
                                      final Integer quantity,
                                      final Site site) {

    final Stage stage = registry.retrieveStage();

    final MessagingClient messagingClient = registry.retrieveMessagingClient();

    final Address address = stage.addressFactory().uniqueWith(generateName());

    final OrderId orderId = OrderId.from(address.idString());

    final Order order =
            stage.actorFor(Order.class,
                    Definition.has(OrderEntity.class, Definition.parameters(orderId)), address);

    final DomainEventNotifier notifier =
            stage.actorFor(DomainEventNotifier.class,
                    Definition.has(DomainEventNotifierActor.class, Definition.parameters(messagingClient)));

    return order.register(productId, quantity, site).andThen(newOrder -> {
        notifier.notify(new OrderWasRegistered(productId, quantity, site));
        return newOrder;
    });
}
 
Example #4
Source File: Client.java    From vlingo-http with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Answer the {@code Configuration} with defaults except for the
 * {@code addressOfHost}, {@code consumerOfUnknownResponses},
 * {@code writeBufferSize}, and {@code readBufferSize}.
 * @param stage the Stage to host the Client
 * @param addressOfHost the Address of the host server
 * @param consumerOfUnknownResponses the ResponseConsumer of responses that cannot be associated with a given consumer
 * @param writeBufferSize the int size of the write buffer
 * @param readBufferSize the int size of the read buffer
 * @return Configuration
 */
public static Configuration defaultedExceptFor(
        final Stage stage,
        final Address addressOfHost,
        final ResponseConsumer consumerOfUnknownResponses,
        final int writeBufferSize,
        final int readBufferSize) {
  return has(
          stage,
          addressOfHost,
          consumerOfUnknownResponses,
          false,
          10,
          writeBufferSize,
          10,
          readBufferSize);
}
 
Example #5
Source File: Client.java    From vlingo-http with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Answer the {@code Configuration} with the given options.
 * @param stage the Stage to host the Client
 * @param addressOfHost the Address of the host server
 * @param consumerOfUnknownResponses the ResponseConsumer of responses that cannot be associated with a given consumer
 * @param keepAlive the boolean indicating whether or not the connection is kept alive over multiple requests-responses
 * @param probeInterval the long number of milliseconds between each consumer channel probe
 * @param writeBufferSize the int size of the ByteBuffer used for writes/sends
 * @param readBufferPoolSize the int number of read buffers in the pool
 * @param readBufferSize the int size of the ByteBuffer used for reads/receives
 * @return Configuration
 */
public static Configuration has(
        final Stage stage,
        final Address addressOfHost,
        final ResponseConsumer consumerOfUnknownResponses,
        final boolean keepAlive,
        final long probeInterval,
        final int writeBufferSize,
        final int readBufferPoolSize,
        final int readBufferSize) {
  return new Configuration(
          stage,
          addressOfHost,
          consumerOfUnknownResponses,
          keepAlive,
          probeInterval,
          writeBufferSize,
          readBufferPoolSize,
          readBufferSize,
          false);
}
 
Example #6
Source File: Client.java    From vlingo-http with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Answer the {@code Configuration} with the given options and that requires a secure channel.
 * @param stage the Stage to host the Client
 * @param addressOfHost the Address of the host server
 * @param consumerOfUnknownResponses the ResponseConsumer of responses that cannot be associated with a given consumer
 * @param keepAlive the boolean indicating whether or not the connection is kept alive over multiple requests-responses
 * @param probeInterval the long number of milliseconds between each consumer channel probe
 * @param writeBufferSize the int size of the ByteBuffer used for writes/sends
 * @param readBufferPoolSize the int number of read buffers in the pool
 * @param readBufferSize the int size of the ByteBuffer used for reads/receives
 * @return Configuration
 */
public static Configuration secure(
        final Stage stage,
        final Address addressOfHost,
        final ResponseConsumer consumerOfUnknownResponses,
        final boolean keepAlive,
        final long probeInterval,
        final int writeBufferSize,
        final int readBufferPoolSize,
        final int readBufferSize) {
  return new Configuration(
          stage,
          addressOfHost,
          consumerOfUnknownResponses,
          keepAlive,
          probeInterval,
          writeBufferSize,
          readBufferPoolSize,
          readBufferSize,
          true);
}
 
Example #7
Source File: Client.java    From vlingo-http with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructs my default state with the given options.
 * @param stage the Stage to host the Client
 * @param addressOfHost the Address of the host server
 * @param consumerOfUnknownResponses the ResponseConsumer of responses that cannot be associated with a given consumer
 * @param keepAlive the boolean indicating whether or not the connection is kept alive over multiple requests-responses
 * @param probeInterval the long number of milliseconds between each consumer channel probe
 * @param writeBufferSize the int size of the ByteBuffer used for writes/sends
 * @param readBufferPoolSize the int number of read buffers in the pool
 * @param readBufferSize the int size of the ByteBuffer used for reads/receives
 * @param secure the boolean indicating whether the connection should be secure
 */
public Configuration(
        final Stage stage,
        final Address addressOfHost,
        final ResponseConsumer consumerOfUnknownResponses,
        final boolean keepAlive,
        final long probeInterval,
        final int writeBufferSize,
        final int readBufferPoolSize,
        final int readBufferSize,
        final boolean secure) {

  this.stage = stage;
  this.addressOfHost = addressOfHost;
  this.consumerOfUnknownResponses = consumerOfUnknownResponses;
  this.keepAlive = keepAlive;
  this.probeInterval = probeInterval;
  this.writeBufferSize = writeBufferSize;
  this.readBufferPoolSize = readBufferPoolSize;
  this.readBufferSize = readBufferSize;
  this.secure = secure;
}
 
Example #8
Source File: ProjectionDispatcherProvider.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
public static ProjectionDispatcherProvider using(final Stage stage) {

    if (instance == null) {
      final List<ProjectToDescription> descriptions =
              Arrays.asList(
            		  new ProjectToDescription(
            				  CartSummaryProjectionActor.class,
            				  CreatedForUser.class.getName(),
            				  ProductQuantityChangeEvent.class.getName(),
            				  AllItemsRemovedEvent.class.getName()));

      final Protocols dispatcherProtocols =
              stage.actorFor(
                      new Class<?>[]{Dispatcher.class, ProjectionDispatcher.class},
                      Definition.has(TextProjectionDispatcherActor.class, Definition.parameters(descriptions)));

      final Protocols.Two<Dispatcher, ProjectionDispatcher> dispatchers = Protocols.two(dispatcherProtocols);
      final Dispatcher storeDispatcher = dispatchers._1;
      final ProjectionDispatcher projectionDispatcher = dispatchers._2;

      instance = new ProjectionDispatcherProvider(storeDispatcher, projectionDispatcher);
    }
    return instance;
  }
 
Example #9
Source File: Product.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
static Tuple2<ProductId, Product> defineWith(
        final Stage stage,
        final Tenant tenant,
        final ProductOwner productOwner,
        final String name,
        final String description,
        final boolean hasDiscussion) {

    assert (tenant != null && tenant.id != null);
    assert (productOwner != null && productOwner.id != null);
    assert (name != null);
    assert (description != null);

    Address address = stage.addressFactory().unique();
    final ProductId productId = ProductId.fromExisting(address.idString());
    final Definition definition = Definition.has(ProductEntity.class, Definition.parameters(tenant, productId), productId.id);
    final Product product = stage.actorFor(Product.class, definition);
    product.define(productOwner, name, description, hasDiscussion);
    return Tuple2.from(productId, product);
}
 
Example #10
Source File: ProjectionDispatcherProvider.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
public static ProjectionDispatcherProvider using(final Stage stage) {
  if (instance != null) return instance;

  final List<ProjectToDescription> descriptions =
          Arrays.asList(
                  new ProjectToDescription(UserProjectionActor.class, "User:new", "User:contact", "User:name"),
                  new ProjectToDescription(PrivateTokenSynchronizerActor.class, "User:new"),
                  new ProjectToDescription(ProfileProjectionActor.class, "Profile:new", "Profile:twitter", "Profile:linkedIn", "Profile:website"));

  final Protocols dispatcherProtocols =
          stage.actorFor(
                  new Class<?>[] { Dispatcher.class, ProjectionDispatcher.class },
                  Definition.has(TextProjectionDispatcherActor.class, Definition.parameters(descriptions)));

  final Protocols.Two<Dispatcher, ProjectionDispatcher> dispatchers = Protocols.two(dispatcherProtocols);

  instance = new ProjectionDispatcherProvider(dispatchers._1, dispatchers._2);

  return instance;
}
 
Example #11
Source File: CommandModelStoreProvider.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static CommandModelStoreProvider using(final Stage stage, final StatefulTypeRegistry registry, final Dispatcher dispatcher) {
  if (instance != null) return instance;
  
  final StateAdapterProvider stateAdapterProvider = new StateAdapterProvider(stage.world());
  stateAdapterProvider.registerAdapter(UserState.class, new UserStateAdapter());
  stateAdapterProvider.registerAdapter(ProfileState.class, new ProfileStateAdapter());
  stateAdapterProvider.registerAdapter(UserData.class, new UserDataStateAdapter());
  stateAdapterProvider.registerAdapter(ProfileData.class, new ProfileDataStateAdapter());
  new EntryAdapterProvider(stage.world()); // future

  final Protocols storeProtocols =
          stage.actorFor(
                  new Class<?>[] { StateStore.class, DispatcherControl.class },
                  Definition.has(InMemoryStateStoreActor.class, Definition.parameters(Arrays.asList(dispatcher))));

  final Protocols.Two<StateStore, DispatcherControl> storeWithControl = Protocols.two(storeProtocols);

  instance = new CommandModelStoreProvider(registry, storeWithControl._1, storeWithControl._2);

  return instance;
}
 
Example #12
Source File: QueryModelStoreProvider.java    From vlingo-examples with Mozilla Public License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static QueryModelStoreProvider using(final Stage stage, final StatefulTypeRegistry registry) {
  if (instance != null) return instance;

  final StateAdapterProvider stateAdapterProvider = new StateAdapterProvider(stage.world());
  stateAdapterProvider.registerAdapter(UserData.class, new UserDataStateAdapter());
  stateAdapterProvider.registerAdapter(ProfileData.class, new ProfileDataStateAdapter());
  new EntryAdapterProvider(stage.world()); // future

  final Dispatcher noop = new Dispatcher() {
    public void controlWith(final DispatcherControl control) { }
    public void dispatch(Dispatchable d) { }
  };

  final StateStore store = stage.actorFor(StateStore.class, InMemoryStateStoreActor.class, Arrays.asList(noop));

  final Queries queries = stage.actorFor(Queries.class, QueriesActor.class, store);

  instance = new QueryModelStoreProvider(registry, store, queries);

  return instance;
}
 
Example #13
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code Server} with the given configuration and characteristics.
 * @param stage the Stage in which the Server lives
 * @param resources the Resource with URI descriptions that the Server understands
 * @param port the int socket port the Server will run on
 * @param sizing the Sizing such as pool and buffer sizes
 * @param timing the Timing such as probe interval and missing content timeout
 * @return Server
 */
public static Server startWith(
        final Stage stage,
        final Resources resources,
        final int port,
        final Sizing sizing,
        final Timing timing) {

  return startWith(stage, resources, Filters.none(), port, sizing, timing);
}
 
Example #14
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code Server} with the given configuration and characteristics.
 * @param stage the Stage in which the Server lives
 * @param resources the Resource with URI descriptions that the Server understands
 * @param filters the Filters used to process requests before dispatching to a resource
 * @param port the int socket port the Server will run on
 * @param sizing the Sizing such as pool and buffer sizes
 * @param timing the Timing such as probe interval and missing content timeout
 * @return Server
 */
public static Server startWith(
        final Stage stage,
        final Resources resources,
        final Filters filters,
        final int port,
        final Sizing sizing,
        final Timing timing) {

  return startWith(stage, resources, filters, port, sizing, timing, "queueMailbox", "queueMailbox");
}
 
Example #15
Source File: Organization.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
static Completes<OrganizationState> with(
        final Stage stage,
        final Class<? extends Actor> entityType,
        final Id organizationId,
        final String name,
        final String description) {
  final String actorName = nameFrom(organizationId);
  final Address address = stage.addressFactory().from(organizationId.value, actorName);
  final Definition definition = Definition.has(entityType, Definition.parameters(organizationId), actorName);
  final Organization organization = stage.actorFor(Organization.class, definition, address);
  return organization.defineWith(name, description);
}
 
Example #16
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
public static Server startWithAgent(
        final Stage stage,
        final Resources resources,
        final int port,
        final int dispatcherPoolSize) {

  return startWithAgent(stage, resources, Filters.none(), port, dispatcherPoolSize);
}
 
Example #17
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
public static Server startWithAgent(
        final Stage stage,
        final Resources resources,
        final Filters filters,
        final int port,
        final int dispatcherPoolSize) {

  return startWithAgent(stage, resources, filters, port, dispatcherPoolSize, "queueMailbox");
}
 
Example #18
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code Server} with the given configuration and characteristics.
 * <p>
 * WARNING: The Server has been tested with the {@code "queueMailbox"} mailbox type.
 * This factory method enables you to change that default to another type. If you do
 * change the mailbox type you do so at your own risk.
 *
 * @param stage the Stage in which the Server lives
 * @param resources the Resource with URI descriptions that the Server understands
 * @param filters the Filters used to process requests before dispatching to a resource
 * @param port the int socket port the Server will run on
 * @param sizing the Sizing such as pool and buffer sizes
 * @param timing the Timing such as probe interval and missing content timeout
 * @param severMailboxTypeName the String name of the mailbox to used by the Server
 * @param channelMailboxTypeName the String name of the mailbox to use by the socket channel
 * @return Server
 */
public static Server startWith(
        final Stage stage,
        final Resources resources,
        final Filters filters,
        final int port,
        final Sizing sizing,
        final Timing timing,
        final String severMailboxTypeName,
        final String channelMailboxTypeName) {

  // this may be overridden by using a different RefreshableSelector
  // initialization that supports a count- or time-based refresh
  // prior to starting the Server.
  RefreshableSelector.withNoThreshold(stage.world().defaultLogger());

  final Server server = stage.actorFor(
          Server.class,
          Definition.has(
                  ServerActor.class,
                  new ServerInstantiator(resources, filters, port, sizing, timing, channelMailboxTypeName),
                  severMailboxTypeName,
                  ServerActor.ServerName),
          stage.world().addressFactory().withHighId(),
          stage.world().defaultLogger());

  server.startUp();

  return server;
}
 
Example #19
Source File: Server.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code Server} with the given configuration and characteristics.
 * @param stage the Stage in which the Server lives
 * @param properties the java.util.Properties with properties named per vlingo-http.properties
 * @return Server
 */
public static Server startWith(final Stage stage, java.util.Properties properties) {
  final Configuration configuration = Configuration.defineWith(properties);

  final Resources resources = Loader.loadResources(properties);

  return startWith(
          stage,
          resources,
          configuration.port(),
          configuration.sizing(),
          configuration.timing());
}
 
Example #20
Source File: Stock.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
static Completes<StockState> openIn(final Stage stage, final Location location) {
    final Address address =
            stage.addressFactory().uniqueWith(generateName());

    final StockId stockId = StockId.from(address.idString());

    final Stock stock =
            stage.actorFor(Stock.class,
                    Definition.has(StockEntity.class, Definition.parameters(stockId)), address);

    return stock.openIn(location);
}
 
Example #21
Source File: ConfigurationResource.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected ResourceHandler resourceHandlerInstance(final Stage stage) {
  try {
    for (final Constructor<?> ctor : resourceHandlerClass.getConstructors()) {
      if (ctor.getParameterCount() == 1) {
        return (ResourceHandler) ctor.newInstance(new Object[] { stage.world() } );
      }
    }
    return resourceHandlerClass.newInstance();
  } catch (Exception e) {
    throw new IllegalArgumentException("The instance for resource handler '" + resourceHandlerClass.getName() + "' cannot be created.");
  }
}
 
Example #22
Source File: StockTest.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testAvailableQuantityManipulation() {
    final ItemId itemId = ItemId.of(1l);
    final Location location = Location.LA;
    final Stage stage = TestWorld.Instance.get().stage();

    final StockState state =
            Stock.openIn(stage, Location.LA)
                    .andThenTo(updated -> Stock.increaseAvailabilityFor(stage, location, itemId, 500))
                    .andThenTo(updated -> Stock.increaseAvailabilityFor(stage, location, itemId, 100))
                    .andThenTo(updated -> Stock.unload(stage, location, itemId, 200))
                    .await();

    Assertions.assertEquals(400, state.quantityFor(itemId));
}
 
Example #23
Source File: CartQueryProvider.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
public static CartQueryProvider using(final Stage stage,
                                      final StatefulTypeRegistry registry,
                                      final StateStore stateStore) {
  if (instance == null) {
    registerStateAdapter(stage);
    registerStatefulTypes(stateStore, registry);
    final CartQuery queries = stage.actorFor(CartQuery.class, CartQueryActor.class, stateStore);

    instance = new CartQueryProvider(stateStore, queries);
  }

  return instance;
}
 
Example #24
Source File: Forum.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
static Tuple2<ForumId, Forum> startWith(
        final Stage stage,
        final Tenant tenant,
        final ForumDescription description) {
  final Forum forum = stage.actorFor(Forum.class, Definition.has(ForumEntity.class, Definition.parameters(tenant, description.forumId)));
  forum.startWith(description.creator, description.moderator, description.topic, description.description, description.exclusiveOwner);
  return Tuple2.from(description.forumId, forum);
}
 
Example #25
Source File: Dispatcher.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Answer a new {@code Dispatcher} backed by {@code DispatcherActor} within {@code Stage}
 * and assigned to manage dispatching to the given {@code Resources}.
 * @param stage the Stage within which the new DispatcherActor will reside
 * @param resources the Resources that may be dispatched
 * @return Dispatcher
 */
public static Dispatcher startWith(final Stage stage, final Resources resources) {
  final Dispatcher dispatcher =
          stage.actorFor(
                  Dispatcher.class,
                  Definition.has(DispatcherActor.class, new DispatcherInstantiator(resources)));

  return dispatcher;
}
 
Example #26
Source File: DispatcherPool.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
protected AbstractDispatcherPool(final Stage stage, final Resources resources, final int dispatcherPoolSize) {
  this.dispatcherPool = new Dispatcher[dispatcherPoolSize];

  for (int idx = 0; idx < dispatcherPoolSize; ++idx) {
    dispatcherPool[idx] = Dispatcher.startWith(stage, resources);
  }
}
 
Example #27
Source File: Resource.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
void allocateHandlerPool(final Stage stage) {
  for (int idx = 0; idx < handlerPoolSize; ++idx) {
    handlerPool[idx] =
      stage.actorFor(
        ResourceRequestHandler.class,
        Definition.has(
          ResourceRequestHandlerActor.class,
          Definition.parameters(resourceHandlerInstance(stage))));
  }
}
 
Example #28
Source File: TestHttpClient.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
public TestHttpClient(final String host, final int port) throws Exception {
    final Stage stage =
            Bootstrap.instance().world().stage();

    final Address address =
            Address.from(Host.of(host), port, AddressType.NONE);

    final ResponseConsumer responseConsumer =
            (response) -> System.out.println("Unknown response received: " + response.status);

    this.httpClient = Client.using(defaultedKeepAliveExceptFor(stage, address, responseConsumer));
}
 
Example #29
Source File: CalculatorState.java    From vlingo-examples with Mozilla Public License 2.0 5 votes vote down vote up
CalculatorState(final Stage stage, final PartitionCalculationInterest interest, final int totalWorkers, final int totalPartitionValues, final int totalMessages) {
  this.totalPartitionValues = totalPartitionValues;
  this.totalMessages = totalMessages;
  this.pi = 0;
  this.resultsCount = 0;

  this.workerIndex = 0;
  this.workers = workers(stage, totalWorkers);
  
  this.interest = interest;
}
 
Example #30
Source File: CommandRouter.java    From vlingo-lattice with Mozilla Public License 2.0 5 votes vote down vote up
static CommandRouter of(final Stage stage, final Type type, final int totalRoutees) {
  switch (type) {
  case LoadBalancing:
    return stage.actorFor(CommandRouter.class, LoadBalancingCommandRouter.class, totalRoutees);
  case Partitioning:
    return stage.actorFor(CommandRouter.class, PartitioningCommandRouter.class, totalRoutees);
  case RoundRobin:
    return stage.actorFor(CommandRouter.class, RoundRobinCommandRouter.class, totalRoutees);
  }
  throw new IllegalArgumentException("The command router type is not mapped: " + type);
}