Java Code Examples for akka.actor.ActorRef#tell()

The following examples show how to use akka.actor.ActorRef#tell() . 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: AbstractPersistentActorWithTimersAndCleanupTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDeleteMessagesFails() {
    new TestKit(actorSystem) {{
        // GIVEN: persistence actor with some messages and snapshots
        final ActorRef persistenceActor = childActorOf(DummyPersistentActor.props(FAIL_DELETE_MESSAGE));

        modifyDummyAndWaitForSnapshotSuccess(this, persistenceActor, 8);

        persistenceActor.tell(CleanupPersistence.of(DefaultEntityId.of(FAIL_DELETE_MESSAGE), DittoHeaders.empty()), getRef());
        final CleanupCommandResponse cleanupCommandResponse = expectMsgClass(CleanupCommandResponse.class);

        assertThat(cleanupCommandResponse.getStatusCode()).isEqualTo(HttpStatusCode.INTERNAL_SERVER_ERROR);

        verifyPersistencePluginCalledWithCorrectArguments(FAIL_DELETE_MESSAGE, 4);
    }};
}
 
Example 2
Source File: ThingCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rejectCreateByOwnPolicy() {
    final PolicyId policyId = PolicyId.of("empty:policy");
    final Policy policy = PoliciesModelFactory.newPolicyBuilder(policyId)
            .forLabel("dummy")
            .setSubject(GOOGLE, "not-subject")
            .setGrantedPermissions(PoliciesResourceType.policyResource("/"), READ.name(), WRITE.name())
            .build();
    final Thing thing = newThing().build();

    new TestKit(system) {{
        mockEntitiesActorInstance.setReply(THING_SUDO,
                ThingNotAccessibleException.newBuilder(THING_ID).build());

        final ActorRef underTest = newEnforcerActor(getRef());
        final CreateThing createThing = CreateThing.of(thing, policy.toJson(), headers(V_2));
        underTest.tell(createThing, getRef());
        fishForMsgClass(this, ThingNotModifiableException.class);
    }};

}
 
Example 3
Source File: CallContextProviderTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void verifyLookupOnlyPolicyIsAppliedProperly() {
	new TestKit(system) {
		{
			final TestKit metricsService = new TestKit(system);
			final ActorRef callContextProvider = system.actorOf(CallContextProvider.props(metricsService.getRef()));

			final ProvideCallContext request = new ProvideCallContext(RESOURCE_ID, ProviderPolicy.LOOKUP_ONLY);

			callContextProvider.tell(request, getRef());

			final Failure failure = expectMsgClass(Duration.ofMillis(TIMEOUT), Failure.class);

			assertThat(failure.cause(), instanceOf(CallContextLookupError.class));
		}
	};
}
 
Example 4
Source File: UserAssignRoleTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Ignore
public void testAssignEmptyRoleSuccess() throws Exception {
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.ASSIGN_ROLES.getValue());
  Map<String, Object> request = new HashMap<String, Object>();
  request.put(JsonKey.USER_ID, userId);
  request.put(JsonKey.ORGANISATION_ID, orgId);
  List<String> roles = new ArrayList<>();
  request.put(JsonKey.ROLES, roles);
  reqObj.setRequest(request);

  initCassandraForSuccess();
  subject.tell(reqObj, probe.getRef());
  Response res = probe.expectMsgClass(ACTOR_MAX_WAIT_DURATION, Response.class);
  assertTrue(null != res);
}
 
Example 5
Source File: PolicyPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void recoverPolicyCreated() {
    new TestKit(actorSystem) {
        {
            final Policy policy = createPolicyWithRandomId();
            final ActorRef policyPersistenceActor = createPersistenceActorFor(this, policy);

            final CreatePolicy createPolicyCommand = CreatePolicy.of(policy, dittoHeadersV2);
            policyPersistenceActor.tell(createPolicyCommand, getRef());
            final CreatePolicyResponse createPolicy1Response = expectMsgClass(CreatePolicyResponse.class);
            DittoPolicyAssertions.assertThat(createPolicy1Response.getPolicyCreated().get())
                    .isEqualEqualToButModified(policy);

            // restart
            terminate(this, policyPersistenceActor);
            final ActorRef policyPersistenceActorRecovered = createPersistenceActorFor(this, policy);
            final RetrievePolicy retrievePolicy =
                    RetrievePolicy.of(policy.getEntityId().orElse(null), dittoHeadersV2);

            final RetrievePolicyResponse expectedResponse =
                    retrievePolicyResponse(incrementRevision(policy, 1), dittoHeadersV2);

            Awaitility.await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
                policyPersistenceActorRecovered.tell(retrievePolicy, getRef());
                expectMsgEquals(expectedResponse);
            });

            assertThat(getLastSender()).isEqualTo(policyPersistenceActorRecovered);
        }
    };
}
 
Example 6
Source File: WaiterTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
@Test
public void sendingServeCoffeeShouldResultInApproveCoffeeToCoffeeHouse() {
    new JavaTestKit(system) {{
        ActorRef coffeeHouse = getRef();
        TestProbe guest = new TestProbe(system);
        ActorRef waiter = system.actorOf(Waiter.props(coffeeHouse, system.deadLetters(), Integer.MAX_VALUE));
        waiter.tell(new Waiter.ServeCoffee(new Coffee.Akkaccino()), guest.ref());
        expectMsgEquals(new CoffeeHouse.ApproveCoffee(new Coffee.Akkaccino(), guest.ref()));
    }};
}
 
Example 7
Source File: EmailServiceActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void testSendEmailFailureWithInvalidParameterValue() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(BackgroundOperations.emailService.name());

  HashMap<String, Object> innerMap = new HashMap<>();
  Map<String, Object> pageMap = new HashMap<String, Object>();
  List<String> emailIdList = new ArrayList<>();
  emailIdList.add("aaa");
  List<String> userIdList = new ArrayList<>();
  userIdList.add("001");
  Map<String, Object> queryMap = new HashMap<>();
  Map<String, Object> filterMap = new HashMap<>();
  queryMap.put(JsonKey.FILTERS, filterMap);
  pageMap.put(JsonKey.RECIPIENT_EMAILS, emailIdList);
  pageMap.put(JsonKey.RECIPIENT_SEARCH_QUERY, queryMap);
  innerMap.put(JsonKey.EMAIL_REQUEST, pageMap);
  innerMap.put(JsonKey.RECIPIENT_USERIDS, userIdList);
  innerMap.put(JsonKey.RECIPIENT_SEARCH_QUERY, queryMap);
  reqObj.setRequest(innerMap);
  subject.tell(reqObj, probe.getRef());
  ProjectCommonException exc =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  assertTrue(exc.getCode().equals(ResponseCode.invalidParameterValue.getErrorCode()));
}
 
Example 8
Source File: SearchRootActor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private SearchRootActor(final SearchConfig searchConfig, final ActorRef pubSubMediator,
        final ActorMaterializer materializer) {

    log = Logging.getLogger(getContext().system(), this);

    final MongoDbConfig mongoDbConfig = searchConfig.getMongoDbConfig();
    final MongoDbConfig.MonitoringConfig monitoringConfig = mongoDbConfig.getMonitoringConfig();

    final DittoMongoClient mongoDbClient = MongoClientWrapper.getBuilder(mongoDbConfig)
            .addCommandListener(getCommandListenerOrNull(monitoringConfig))
            .addConnectionPoolListener(getConnectionPoolListenerOrNull(monitoringConfig))
            .build();

    final ThingsSearchPersistence thingsSearchPersistence = getThingsSearchPersistence(searchConfig, mongoDbClient);
    final ActorRef searchActor = initializeSearchActor(searchConfig.getLimitsConfig(), thingsSearchPersistence);
    pubSubMediator.tell(DistPubSubAccess.put(searchActor), getSelf());

    final TimestampPersistence backgroundSyncPersistence =
            MongoTimestampPersistence.initializedInstance(BACKGROUND_SYNC_COLLECTION_NAME, mongoDbClient,
                    materializer);

    final ActorRef searchUpdaterRootActor = startChildActor(SearchUpdaterRootActor.ACTOR_NAME,
            SearchUpdaterRootActor.props(searchConfig, pubSubMediator, materializer, thingsSearchPersistence,
                    backgroundSyncPersistence));
    final ActorRef healthCheckingActor = initializeHealthCheckActor(searchConfig, searchUpdaterRootActor);

    createHealthCheckingActorHttpBinding(searchConfig.getHttpConfig(), healthCheckingActor, materializer);
}
 
Example 9
Source File: HttpPushClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTLSConnectionFails() {
    // GIVEN: server has a self-signed certificate
    connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort()).build();
    final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
            .clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
            .clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
            .build();
    final SSLContext sslContext = SSLContextCreator.fromConnection(connection, DittoHeaders.empty())
            .clientCertificate(credentials);
    final HttpsConnectionContext invalidHttpsContext = ConnectionContext.https(sslContext);

    final int port = binding.localAddress().getPort();
    binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
    binding = Http.get(actorSystem)
            .bindAndHandle(handler,
                    ConnectHttp.toHostHttps("127.0.0.1", port).withCustomHttpsContext(invalidHttpsContext),
                    mat)
            .toCompletableFuture()
            .join();

    new TestKit(actorSystem) {{
        // WHEN: the connection is tested
        final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
        underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());

        // THEN: the test fails
        final Status.Failure failure = expectMsgClass(Status.Failure.class);
        assertThat(failure.cause()).isInstanceOf(DittoRuntimeException.class);
        assertThat(((DittoRuntimeException) failure.cause()).getDescription().orElse(""))
                .contains("unable to find valid certification path");
        expectTerminated(underTest);
    }};
}
 
Example 10
Source File: Master.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
protected void handle(EndMessage message) {
	this.isEnded = true;
	
	for (ActorRef worker : this.workers)
		worker.tell(PoisonPill.getInstance(), this.self());
	
	if (this.workers.isEmpty())
		this.self().tell(PoisonPill.getInstance(), this.self());
}
 
Example 11
Source File: WaiterTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
@Test
public void sendingServeCoffeeShouldResultInApproveCoffeeToCoffeeHouse() {
    new JavaTestKit(system) {{
        ActorRef coffeeHouse = getRef();
        TestProbe guest = new TestProbe(system);
        ActorRef waiter = system.actorOf(Waiter.props(coffeeHouse));
        waiter.tell(new Waiter.ServeCoffee(new Coffee.Akkaccino()), guest.ref());
        expectMsgEquals(new CoffeeHouse.ApproveCoffee(new Coffee.Akkaccino(), guest.ref()));
    }};
}
 
Example 12
Source File: CoffeeHouseTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateGuestActorsWhenCreateGuestMessageSent() {
    new JavaTestKit(system) {{
        ActorRef coffeeHouse = system.actorOf(CoffeeHouse.props(Integer.MAX_VALUE), "create-guest");
        coffeeHouse.tell(new CoffeeHouse.CreateGuest(new Coffee.Akkaccino(), Integer.MAX_VALUE), ActorRef.noSender());
        expectActor(this, "/user/create-guest/$*");
    }};
}
 
Example 13
Source File: SubscriptionManagerTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void illegalDemand() {
    new TestKit(actorSystem) {{
        final ActorRef underTest = createSubscriptionManager();
        underTest.tell(createSubscription(1), getRef());
        final String sid = expectMsgClass(SubscriptionCreated.class).getSubscriptionId();
        underTest.tell(RequestFromSubscription.of(sid, 0L, DittoHeaders.empty()), getRef());
        expectMsgClass(SubscriptionFailed.class);
    }};
}
 
Example 14
Source File: HealthActorTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Test
public void getHealthCheck() {
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.HEALTH_CHECK.getValue());
  subject.tell(reqObj, probe.getRef());
  Response res = probe.expectMsgClass(duration("200 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example 15
Source File: CoffeeHouseTest.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
@Test
public void sendingApproveCoffeeShouldForwardPrepareCoffeeIfCaffeineLimitNotReached() {
    new JavaTestKit(system) {{
        ActorRef coffeeHouse = createActor(CoffeeHouse.class, "prepare-coffee", () -> new CoffeeHouse(Integer.MAX_VALUE) {
            @Override
            protected ActorRef createBarista() {
                return getRef();
            }
        });
        coffeeHouse.tell(new CoffeeHouse.CreateGuest(new Coffee.Akkaccino(), Integer.MAX_VALUE), ActorRef.noSender());
        ActorRef guest = expectActor(this, "/user/prepare-coffee/$*");
        coffeeHouse.tell(new CoffeeHouse.ApproveCoffee(new Coffee.Akkaccino(), guest), getRef());
        expectMsgEquals(new Barista.PrepareCoffee(new Coffee.Akkaccino(), guest));
    }};
}
 
Example 16
Source File: Shepherd.java    From akka-tutorial with Apache License 2.0 5 votes vote down vote up
private void handle(ShutdownMessage message) {
	
	// Shutdown all slaves that connected to this Shepherd
	for (ActorRef slave : this.slaves)
		slave.tell(new ShutdownMessage(), this.getSelf());
	
	// Stop accepting new slaves (to do so, the actor can simply stop itself)
	this.getSelf().tell(PoisonPill.getInstance(), this.getSelf());
}
 
Example 17
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCreateSessionFails() throws JMSException {
    new TestKit(actorSystem) {{
        when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE)).thenThrow(JMS_EXCEPTION);
        final Props props =
                AmqpClientActor.propsForTests(connection, getRef(),
                        getRef(), (ac, el) -> mockConnection);
        final ActorRef amqpClientActor = actorSystem.actorOf(props);

        amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
        expectMsg(new Status.Failure(SESSION_EXCEPTION));
    }};
}
 
Example 18
Source File: BackOffActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static void assertIsInBackOffMode(final ActorRef underTest, final TestKit probe,
        final boolean isInBackOff) {
    underTest.tell(BackOffActor.createIsInBackOffMessage(), probe.getRef());
    final BackOffActor.IsInBackOffResponse response = probe.expectMsgClass(BackOffActor.IsInBackOffResponse.class);
    assertThat(response.isInBackOff()).isEqualTo(isInBackOff);
}
 
Example 19
Source File: AmqpPublisherActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testPublishMessageWithAmqpProperties() throws Exception {

    new TestKit(actorSystem) {{

        // GIVEN: a message is published with headers matching AMQP properties.
        final TestProbe probe = new TestProbe(actorSystem);
        setupMocks(probe);
        final OutboundSignal.Mapped mappedOutboundSignal = getMockOutboundSignal(
                ConnectivityModelFactory.newTargetBuilder(createTestTarget())
                        .headerMapping(ConnectivityModelFactory.newHeaderMapping(
                                JsonFactory.newObjectBuilder()
                                        .set("creation-time", "-1")
                                        .set("absolute-expiry-time", "1234")
                                        .set("group-sequence", "abc")
                                        .set("group-id", "hello")
                                        .set("subject", "subjective")
                                        .set("application-property-with-dash", "value0")
                                        .set("amqp.application.property:to", "value1")
                                        .set("amqp.application.property:anotherApplicationProperty", "value2")
                                        .build()
                        ))
                        .build()
        );

        final Props props = getPublisherActorProps();
        final ActorRef publisherActor = childActorOf(props);

        // WHEN: the publisher sends the message to an AMQP target address
        publisherCreated(this, publisherActor);

        publisherActor.tell(mappedOutboundSignal, getRef());

        final ArgumentCaptor<JmsMessage> messageCaptor = ArgumentCaptor.forClass(JmsMessage.class);
        verify(messageProducer, timeout(1000)).send(messageCaptor.capture(), any(CompletionListener.class));
        final Message message = messageCaptor.getValue();
        final Map<String, String> receivedHeaders =
                JMSPropertyMapper.getPropertiesAndApplicationProperties(message);

        assertThat(message.getJMSTimestamp()).isEqualTo(-1L);
        assertThat(message.getJMSType()).isEqualTo("subjective");

        // THEN: valid AMQP properties and application properties are set and invalid ones are dropped.
        assertThat(receivedHeaders).containsEntry("group-id", "hello");
        assertThat(receivedHeaders).containsEntry("subject", "subjective");
        assertThat(receivedHeaders).containsEntry("creation-time", "-1");
        assertThat(receivedHeaders).containsEntry("absolute-expiry-time", "1234");
        assertThat(receivedHeaders).containsEntry("application-property-with-dash", "value0");
        assertThat(receivedHeaders).containsEntry("amqp.application.property:to", "value1");
        assertThat(receivedHeaders).containsEntry("anotherApplicationProperty", "value2");
        // group-sequence is an AMQP prop of type "int", therefore it must not be contained in the headers here
        assertThat(receivedHeaders).doesNotContainKey("group-sequence");
    }};

}
 
Example 20
Source File: AbstractShardedPersistenceActor.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void notifySender(final ActorRef sender, final WithDittoHeaders message) {
    accessCounter++;
    sender.tell(message, getSelf());
}