Java Code Examples for akka.actor.ActorSystem

The following examples show how to use akka.actor.ActorSystem. These examples are extracted from open source projects. 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 Project: usergrid   Author: apache   File: QueueActorRouterProducer.java    License: Apache License 2.0 8 votes vote down vote up
@Override
public void produceRouter(ActorSystem system, String role) {

    ClusterSingletonManagerSettings settings =
            ClusterSingletonManagerSettings.create( system ).withRole( "io" );

    system.actorOf( ClusterSingletonManager.props(
            Props.create( GuiceActorProducer.class, QueueActorRouter.class ),
            PoisonPill.getInstance(), settings ), "queueActorRouter" );

    ClusterSingletonProxySettings proxySettings =
            ClusterSingletonProxySettings.create( system ).withRole( role );

    system.actorOf(
            ClusterSingletonProxy.props( "/user/queueActorRouter", proxySettings ), "queueActorRouterProxy" );
}
 
Example #2
Source Project: ditto   Author: eclipse   File: HttpPublisherActor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private HttpPublisherActor(final Connection connection, final HttpPushFactory factory) {
    super(connection);
    this.factory = factory;

    final ActorSystem system = getContext().getSystem();
    final ConnectionConfig connectionConfig =
            DittoConnectivityConfig.of(DefaultScopedConfig.dittoScoped(system.settings().config()))
                    .getConnectionConfig();
    config = connectionConfig.getHttpPushConfig();

    materializer = ActorMaterializer.create(getContext());
    sourceQueue =
            Source.<Pair<HttpRequest, HttpPushContext>>queue(config.getMaxQueueSize(), OverflowStrategy.dropNew())
                    .viaMat(factory.createFlow(system, log), Keep.left())
                    .toMat(Sink.foreach(this::processResponse), Keep.left())
                    .run(materializer);
}
 
Example #3
Source Project: sunbird-lms-service   Author: project-sunbird   File: BadgeClassActorTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
  ActorSystem system = ActorSystem.create("system");
  probe = new TestKit(system);

  mockBadgingService = PowerMockito.mock(BadgrServiceImpl.class);

  Props props = Props.create(BadgeClassActor.class, mockBadgingService);
  subject = system.actorOf(props);

  actorMessage = new Request();

  ResponseCode error = ResponseCode.resourceNotFound;
  resourceNotFoundException =
      new ProjectCommonException(
          error.getErrorCode(), error.getErrorMessage(), error.getResponseCode());
}
 
Example #4
Source Project: deployment-examples   Author: Rookout   File: UnitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testAsync() {
    final ActorSystem actorSystem = ActorSystem.create("test");
    try {
        final ExecutionContextExecutor ec = actorSystem.dispatcher();
        final AsyncController controller = new AsyncController(actorSystem, ec);
        final CompletionStage<Result> future = controller.message();

        // Block until the result is completed
        await().until(() -> {
            assertThat(future.toCompletableFuture()).isCompletedWithValueMatching(result -> {
                return contentAsString(result).equals("Hi!");
            });
        });
    } finally {
        actorSystem.terminate();
    }
}
 
Example #5
Source Project: chuidiang-ejemplos   Author: chuidiang   File: HelloActorMain.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void main( String[] args )
{
   // an actor needs an ActorSystem
   ActorSystem system = ActorSystem.create("HelloWorldSystem");

   // create and start the actor
   Props actor = Props.create(HelloActor.class);
   ActorRef helloActor = system.actorOf(actor, "HelloActor");

   // send the actor two messages
   helloActor.tell("hello 1",helloActor);
   helloActor.tell("hello 2",helloActor);
   helloActor.tell("hello 3",helloActor);
  

   // shut down the system
   system.terminate();
}
 
Example #6
Source Project: servicecomb-pack   Author: apache   File: TransactionInterceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void passesOmegaContextAmongActors() throws Exception {
  ActorSystem actorSystem = ActorSystem.create();

  ActorRef actorRef = actorSystem.actorOf(UserServiceActor.props(userService));
  actorRef.tell(user, noSender());

  waitTillSavedUser(username);

  assertArrayEquals(
      new String[] {
          new TxStartedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod, 0, "", 0, 0, 0, 0, 0, user).toString(),
          new TxEndedEvent(globalTxId, newLocalTxId, globalTxId, compensationMethod).toString()},
      toArray(messages)
  );
  actorSystem.terminate();
}
 
Example #7
Source Project: ditto   Author: eclipse   File: ThingPersistenceOperationsActorIT.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected ActorRef startEntityActor(final ActorSystem system, final ActorRef pubSubMediator, final ThingId id) {
    final Props props =
            ThingSupervisorActor.props(pubSubMediator,
                    new DistributedPub<ThingEvent>() {
                        @Override
                        public ActorRef getPublisher() {
                            return pubSubMediator;
                        }

                        @Override
                        public Object wrapForPublication(final ThingEvent message) {
                            return message;
                        }
                    },
                    ThingPersistenceActor::props);

    return system.actorOf(props, id.toString());
}
 
Example #8
Source Project: usergrid   Author: apache   File: UniqueValuesServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void produceRouter( ActorSystem system, String role ) {

    ClusterSingletonManagerSettings settings =
        ClusterSingletonManagerSettings.create( system ).withRole("io");

    system.actorOf( ClusterSingletonManager.props(
        Props.create( GuiceActorProducer.class, UniqueValuesRouter.class ),
        PoisonPill.getInstance(), settings ), "uvRouter" );

    ClusterSingletonProxySettings proxySettings =
        ClusterSingletonProxySettings.create( system ).withRole( role );

    system.actorOf( ClusterSingletonProxy.props( "/user/uvRouter", proxySettings ), "uvProxy" );

    subscribeToReservations( system );
}
 
Example #9
Source Project: amcgala   Author: th-koeln   File: AgentClient.java    License: Educational Community License v2.0 6 votes vote down vote up
public AgentClient(String agentConfiguration) {
    Config config =  ConfigFactory.load().getConfig("client").withFallback(ConfigFactory.load(agentConfiguration).withFallback(ConfigFactory.load("amcgala")));
    boolean localMode = config.getBoolean("org.amcgala.agent.simulation.local-mode");
    if (localMode) {
        system = ActorSystem.create("Client", config);
        ActorRef simulationManager = system.actorOf(Props.create(SimulationManager.class), "simulation-manager");
        simulationManager.tell(new SimulationManager.SimulationCreation(config), ActorRef.noSender());
    }else{
        system = ActorSystem.create("Client", config);
    }

    List<List<String>> lists = (List<List<String>>) config.getAnyRefList("org.amcgala.agent.client.agents");
    for (List<String> l : lists) {
        try {
            int numberOfAgents = Integer.parseInt(l.get(0));
            Class agentClass = ClassLoader.getSystemClassLoader().loadClass(l.get(1));
            createAgents(numberOfAgents, agentClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
 
Example #10
Source Project: akka-tutorial   Author: HPI-Information-Systems   File: Calculator.java    License: Apache License 2.0 6 votes vote down vote up
public static void runMaster(String host, int port, SchedulingStrategy.Factory schedulingStrategyFactory, int numLocalWorkers) {
	
	// Create the ActorSystem
	final Config config = AkkaUtils.createRemoteAkkaConfig(host, port);
	final ActorSystem actorSystem = ActorSystem.create(DEFAULT_MASTER_SYSTEM_NAME, config);

	// Create the Reaper.
	actorSystem.actorOf(Reaper.props(), Reaper.DEFAULT_NAME);

	// Create the Listener
	final ActorRef listener = actorSystem.actorOf(Listener.props(), Listener.DEFAULT_NAME);

	// Create the Master
	final ActorRef master = actorSystem.actorOf(Master.props(listener, schedulingStrategyFactory, numLocalWorkers), Master.DEFAULT_NAME);

	// Create the Shepherd
	final ActorRef shepherd = actorSystem.actorOf(Shepherd.props(master), Shepherd.DEFAULT_NAME);

	// Enter interactive loop
	Calculator.enterInteractiveLoop(listener, master, shepherd);
	
	System.out.println("Stopping...");

	// Await termination: The termination should be issued by the reaper
	Calculator.awaitTermination(actorSystem);
}
 
Example #11
Source Project: akka-tutorial   Author: HPI-Information-Systems   File: OctopusSlave.java    License: Apache License 2.0 6 votes vote down vote up
public static void start(String actorSystemName, int workers, String host, int port, String masterhost, int masterport) {
	
	final Config config = createConfiguration(actorSystemName, SLAVE_ROLE, host, port, masterhost, masterport);
	
	final ActorSystem system = createSystem(actorSystemName, config);
	
	Cluster.get(system).registerOnMemberUp(new Runnable() {
		@Override
		public void run() {
			//system.actorOf(ClusterListener.props(), ClusterListener.DEFAULT_NAME);
			system.actorOf(MetricsListener.props(), MetricsListener.DEFAULT_NAME);

			for (int i = 0; i < workers; i++)
				system.actorOf(Worker.props(), Worker.DEFAULT_NAME + i);
		}
	});
}
 
Example #12
Source Project: flink   Author: flink-tpc-ds   File: AkkaRpcServiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to create RPC service from configuration and hostname, port.
 *
 * @param hostname The hostname/address that describes the TaskManager's data location.
 * @param portRangeDefinition The port range to start TaskManager on.
 * @param configuration The configuration for the TaskManager.
 * @param actorSystemName The actor system name of the RpcService.
 * @param actorSystemExecutorConfiguration The configuration of the executor of the actor system.
 * @return The rpc service which is used to start and connect to the TaskManager RpcEndpoint .
 * @throws IOException Thrown, if the actor system can not bind to the address
 * @throws Exception Thrown is some other error occurs while creating akka actor system
 */
public static RpcService createRpcService(
	String hostname,
	String portRangeDefinition,
	Configuration configuration,
	String actorSystemName,
	@Nonnull BootstrapTools.ActorSystemExecutorConfiguration actorSystemExecutorConfiguration) throws Exception {

	final ActorSystem actorSystem = BootstrapTools.startActorSystem(
		configuration,
		actorSystemName,
		hostname,
		portRangeDefinition,
		LOG,
		actorSystemExecutorConfiguration);

	return instantiateAkkaRpcService(configuration, actorSystem);
}
 
Example #13
Source Project: flink   Author: flink-tpc-ds   File: AkkaRpcActorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that actors are properly terminated when the AkkaRpcService is shut down.
 */
@Test
public void testActorTerminationWhenServiceShutdown() throws Exception {
	final ActorSystem rpcActorSystem = AkkaUtils.createDefaultActorSystem();
	final RpcService rpcService = new AkkaRpcService(
		rpcActorSystem, AkkaRpcServiceConfiguration.defaultConfiguration());

	try {
		SimpleRpcEndpoint rpcEndpoint = new SimpleRpcEndpoint(rpcService, SimpleRpcEndpoint.class.getSimpleName());

		rpcEndpoint.start();

		CompletableFuture<Void> terminationFuture = rpcEndpoint.getTerminationFuture();

		rpcService.stopService();

		terminationFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS);
	} finally {
		rpcActorSystem.terminate();
		Await.ready(rpcActorSystem.whenTerminated(), FutureUtils.toFiniteDuration(timeout));
	}
}
 
Example #14
Source Project: flink   Author: flink-tpc-ds   File: MetricUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the {@link MetricUtils#startMetricsRpcService(Configuration, String)} respects
 * the given {@link MetricOptions#QUERY_SERVICE_THREAD_PRIORITY}.
 */
@Test
public void testStartMetricActorSystemRespectsThreadPriority() throws Exception {
	final Configuration configuration = new Configuration();
	final int expectedThreadPriority = 3;
	configuration.setInteger(MetricOptions.QUERY_SERVICE_THREAD_PRIORITY, expectedThreadPriority);

	final RpcService rpcService = MetricUtils.startMetricsRpcService(configuration, "localhost");
	assertThat(rpcService, instanceOf(AkkaRpcService.class));

	final ActorSystem actorSystem = ((AkkaRpcService) rpcService).getActorSystem();

	try {
		final int threadPriority = actorSystem.settings().config().getInt("akka.actor.default-dispatcher.thread-priority");

		assertThat(threadPriority, is(expectedThreadPriority));
	} finally {
		AkkaUtils.terminateActorSystem(actorSystem).get();
	}
}
 
Example #15
Source Project: Flink-CEPplus   Author: ljygz   File: MesosServicesUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link MesosServices} instance depending on the high availability settings.
 *
 * @param configuration containing the high availability settings
 * @param hostname the hostname to advertise to remote clients
 * @return a mesos services instance
 * @throws Exception if the mesos services instance could not be created
 */
public static MesosServices createMesosServices(Configuration configuration, String hostname) throws Exception {

	ActorSystem localActorSystem = AkkaUtils.createLocalActorSystem(configuration);

	MesosArtifactServer artifactServer = createArtifactServer(configuration, hostname);

	HighAvailabilityMode highAvailabilityMode = HighAvailabilityMode.fromConfig(configuration);

	switch (highAvailabilityMode) {
		case NONE:
			return new StandaloneMesosServices(localActorSystem, artifactServer);

		case ZOOKEEPER:
			final String zkMesosRootPath = configuration.getString(
				HighAvailabilityOptions.HA_ZOOKEEPER_MESOS_WORKERS_PATH);

			ZooKeeperUtilityFactory zooKeeperUtilityFactory = new ZooKeeperUtilityFactory(
				configuration,
				zkMesosRootPath);

			return new ZooKeeperMesosServices(localActorSystem, artifactServer, zooKeeperUtilityFactory);

		default:
			throw new Exception("High availability mode " + highAvailabilityMode + " is not supported.");
	}
}
 
Example #16
Source Project: ditto   Author: eclipse   File: MessageMappingProcessorActorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private void resetActorSystemWithCachingSignalEnrichmentProvider() {
    TestKit.shutdownActorSystem(actorSystem);
    actorSystem = ActorSystem.create("AkkaTestSystemWithCachingSignalEnrichmentProvider",
            TestConstants.CONFIG
                    .withValue("ditto.connectivity.signal-enrichment.provider",
                            ConfigValueFactory.fromAnyRef(
                                    ConnectivityCachingSignalEnrichmentProvider.class.getCanonicalName())
                    )
    );
    MockConciergeForwarderActor.create(actorSystem);
}
 
Example #17
Source Project: ditto   Author: eclipse   File: FeaturesRouteTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    final ActorSystem actorSystem = system();
    final ProtocolAdapterProvider adapterProvider = ProtocolAdapterProvider.load(protocolConfig, actorSystem);

    final DittoHeaders dittoHeaders = DittoHeaders.newBuilder().correlationId(testName.getMethodName())
            .build();

    featuresRoute = new FeaturesRoute(createDummyResponseActor(), actorSystem, httpConfig, commandConfig,
            messageConfig, claimMessageConfig, adapterProvider.getHttpHeaderTranslator());
    final Route route = extractRequestContext(
            ctx -> featuresRoute.buildFeaturesRoute(ctx, dittoHeaders, KNOWN_THING_ID));
    underTest = testRoute(route);
}
 
Example #18
Source Project: akka-java-springfactory   Author: sabomichal   File: ActorSystemFactoryBean.java    License: MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	ActorSystem system;
	if (name != null && config != null) {
		system = ActorSystem.create(name, config);
	} else if (name != null) {
		system = ActorSystem.create(name);
	} else {
		system = ActorSystem.create();
	}
	// init extensions
	SpringExtension.instance().get(system).setApplicationContext(ctx);
	actorSystem = system;
}
 
Example #19
Source Project: ts-reaktive   Author: Tradeshift   File: S3.java    License: MIT License 5 votes vote down vote up
public S3(ActorSystem system, String bucket, String prefix) {
    this.materializer = SharedActorMaterializer.get(system);
    this.serializer = EventMarshallers.getAkkaSerializer(system);
    this.bucket = bucket;
    this.bucketKeyPrefix = prefix.endsWith("/") ? prefix : prefix + "/";
    this.client = S3Client.create(system, materializer);
}
 
Example #20
Source Project: akka-java-examples   Author: royrusso   File: System.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws Exception {

        final ActorSystem actorSystem = ActorSystem.create("actor-server");

        final ActorRef handler = actorSystem.actorOf(Props.create(EventHandler.class));
        actorSystem.eventStream().subscribe(handler, Event.class);

        Thread.sleep(5000);

        final ActorRef actorRef = actorSystem.actorOf(Props.create(BaseProcessor.class), "eventsourcing-processor");

        actorRef.tell(new Command("CMD 1"), null);
        actorRef.tell(new Command("CMD 2"), null);
        actorRef.tell(new Command("CMD 3"), null);
        actorRef.tell("snapshot", null);
        actorRef.tell(new Command("CMD 4"), null);
        actorRef.tell(new Command("CMD 5"), null);
        actorRef.tell("printstate", null);

        Thread.sleep(5000);

        log.debug("Actor System Shutdown Starting...");

        actorSystem.shutdown();
    }
 
Example #21
Source Project: ditto   Author: eclipse   File: DefaultHttpClientFacade.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the {@code HttpClientProvider} instance.
 *
 * @param actorSystem the {@code ActorSystem} in which to create the HttpClientProvider.
 * @param httpProxyConfig the config of the HTTP proxy.
 * @return the instance.
 */
public static DefaultHttpClientFacade getInstance(final ActorSystem actorSystem,
        final HttpProxyConfig httpProxyConfig) {

    // the HttpClientProvider is only configured at the very first invocation of getInstance(Config) as we can
    // assume that the config does not change during runtime
    DefaultHttpClientFacade result = instance;
    if (null == result) {
        result = createInstance(actorSystem, httpProxyConfig);
        instance = result;
    }
    return result;
}
 
Example #22
Source Project: flink   Author: apache   File: MesosServicesUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link MesosServices} instance depending on the high availability settings.
 *
 * @param configuration containing the high availability settings
 * @param hostname the hostname to advertise to remote clients
 * @return a mesos services instance
 * @throws Exception if the mesos services instance could not be created
 */
public static MesosServices createMesosServices(Configuration configuration, String hostname) throws Exception {

	ActorSystem localActorSystem = AkkaUtils.createLocalActorSystem(configuration);

	MesosArtifactServer artifactServer = createArtifactServer(configuration, hostname);

	HighAvailabilityMode highAvailabilityMode = HighAvailabilityMode.fromConfig(configuration);

	switch (highAvailabilityMode) {
		case NONE:
			return new StandaloneMesosServices(localActorSystem, artifactServer);

		case ZOOKEEPER:
			final String zkMesosRootPath = configuration.getString(
				HighAvailabilityOptions.HA_ZOOKEEPER_MESOS_WORKERS_PATH);

			ZooKeeperUtilityFactory zooKeeperUtilityFactory = new ZooKeeperUtilityFactory(
				configuration,
				zkMesosRootPath);

			return new ZooKeeperMesosServices(localActorSystem, artifactServer, zooKeeperUtilityFactory);

		default:
			throw new Exception("High availability mode " + highAvailabilityMode + " is not supported.");
	}
}
 
Example #23
Source Project: flux   Author: flipkart-incubator   File: EventSchedulerRegistryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize() {
    ActorSystem actorSystem = actorSystemManager.retrieveActorSystem();

    //create cluster singleton actor of {@link AkkaEventSchedulerService}
    Props actorProps = Props.create(AkkaEventSchedulerService.class, eventSchedulerService);
    ClusterSingletonManagerSettings settings = ClusterSingletonManagerSettings.create(actorSystem);
    actorSystem.actorOf(ClusterSingletonManager.props(actorProps, PoisonPill.getInstance(), settings), "eventSchedulerServiceActor");
}
 
Example #24
Source Project: Flink-CEPplus   Author: ljygz   File: MetricUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ActorSystem startMetricsActorSystem(Configuration configuration, String hostname, Logger logger) throws Exception {
	final String portRange = configuration.getString(MetricOptions.QUERY_SERVICE_PORT);
	final int threadPriority = configuration.getInteger(MetricOptions.QUERY_SERVICE_THREAD_PRIORITY);
	return BootstrapTools.startActorSystem(
		configuration,
		METRICS_ACTOR_SYSTEM_NAME,
		hostname,
		portRange,
		logger,
		new BootstrapTools.FixedThreadPoolExecutorConfiguration(1, 1, threadPriority));
}
 
Example #25
Source Project: oreilly-reactive-architecture-student   Author: ironfish   File: CoffeeHouseApp.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "coffee-house");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name));
    final CoffeeHouseApp coffeeHouseApp = new CoffeeHouseApp(system);
    coffeeHouseApp.run();
}
 
Example #26
Source Project: oreilly-reactive-architecture-student   Author: ironfish   File: CoffeeHouseApp.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "coffee-house");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name));
    final CoffeeHouseApp coffeeHouseApp = new CoffeeHouseApp(system);
    coffeeHouseApp.run();
}
 
Example #27
Source Project: oreilly-reactive-architecture-student   Author: ironfish   File: CoffeeHouseApp.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "coffee-house");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name));
    final CoffeeHouseApp coffeeHouseApp = new CoffeeHouseApp(system);
    coffeeHouseApp.run();
}
 
Example #28
Source Project: Flink-CEPplus   Author: ljygz   File: ProcessShutDownThread.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a shut down thread.
 *
 * @param log                Log of the corresponding YARN process.
 * @param actorSystem        Actor system to await termination of.
 * @param terminationTimeout Actor system termination timeout before
 *                           shutting down the JVM.
 */
public ProcessShutDownThread(
		Logger log,
		ActorSystem actorSystem,
		Duration terminationTimeout) {

	this.log = checkNotNull(log, "Logger");
	this.actorSystem = checkNotNull(actorSystem, "Actor system");
	this.terminationTimeout = checkNotNull(terminationTimeout, "Termination timeout");
}
 
Example #29
Source Project: oreilly-reactive-architecture-student   Author: ironfish   File: CoffeeHouseApp.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Map<String, String> opts = argsToOpts(Arrays.asList(args));
    applySystemProperties(opts);
    final String name = opts.getOrDefault("name", "coffee-house");

    final ActorSystem system = ActorSystem.create(String.format("%s-system", name));
    final CoffeeHouseApp coffeeHouseApp = new CoffeeHouseApp(system);
    coffeeHouseApp.run();
}
 
Example #30
Source Project: ditto   Author: eclipse   File: TransistorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Connect a transistor to 2 test collectors and a test sink.
 */
@Before
public void init() {
    system = ActorSystem.create();
    final Source<Integer, TestPublisher.Probe<Integer>> collectorSource = TestSource.probe(system);
    final Source<Integer, TestPublisher.Probe<Integer>> baseSource = TestSource.probe(system);
    final Sink<Integer, TestSubscriber.Probe<Integer>> emitterSink = TestSink.probe(system);
    final Transistor<Integer> underTest = Transistor.of();

    final Graph<SourceShape<Integer>, Pair<TestPublisher.Probe<Integer>, TestPublisher.Probe<Integer>>>
            collectorGateTransistor =
            GraphDSL$.MODULE$.create3(
                    collectorSource, baseSource, underTest,
                    (collector, base, notUsed) -> Pair.create(collector, base),
                    (builder, collectorShape, baseShape, transistorShape) -> {
                        builder.from(collectorShape.out()).toInlet(transistorShape.in0());
                        builder.from(baseShape.out()).toInlet(transistorShape.in1());
                        return SourceShape.of(transistorShape.out());
                    });

    final Pair<Pair<TestPublisher.Probe<Integer>, TestPublisher.Probe<Integer>>, TestSubscriber.Probe<Integer>> m =
            Source.fromGraph(collectorGateTransistor)
                    .toMat(emitterSink, Keep.both())
                    .run(ActorMaterializer.create(system));

    collector = m.first().first();
    base = m.first().second();
    emitter = m.second();
}