akka.actor.ActorRef Java Examples
The following examples show how to use
akka.actor.ActorRef.
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: BulkUploadManagementActorTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testBulkUploadGetStatus() { Response response = getCassandraRecordByIdForBulkUploadResponse(); when(cassandraOperation.getRecordById( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyList())) .thenReturn(response); TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.GET_BULK_OP_STATUS.getValue()); reqObj.getRequest().put(JsonKey.PROCESS_ID, PROCESS_ID); subject.tell(reqObj, probe.getRef()); Response res = probe.expectMsgClass(duration("10 second"), Response.class); List<Map<String, Object>> list = (List<Map<String, Object>>) res.get(JsonKey.RESPONSE); if (!list.isEmpty()) { Map<String, Object> map = list.get(0); String processId = (String) map.get(JsonKey.PROCESS_ID); Assert.assertTrue(null != processId); } }
Example #2
Source File: AmqpClientActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void sendConnectCommandWhenAlreadyConnected() throws JMSException { new TestKit(actorSystem) {{ 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(CONNECTED_SUCCESS); amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef()); expectMsg(CONNECTED_SUCCESS); // no reconnect happens Mockito.verify(mockConnection, Mockito.times(1)).start(); }}; }
Example #3
Source File: LocationClientImpl.java From sunbird-lms-service with MIT License | 6 votes |
@Override public List<String> getRelatedLocationIds(ActorRef actorRef, List<String> codes) { Map<String, Object> requestMap = new HashMap<>(); requestMap.put(JsonKey.LOCATION_CODES, codes); Request request = new Request(); request.setOperation(LocationActorOperation.GET_RELATED_LOCATION_IDS.getValue()); request.getRequest().putAll(requestMap); ProjectLogger.log("LocationClientImpl: getRelatedLocationIds called", LoggerEnum.INFO); Object obj = interServiceCommunication.getResponse(actorRef, request); checkLocationResponseForException(obj); if (obj instanceof Response) { Response responseObj = (Response) obj; List<String> responseList = (List<String>) responseObj.getResult().get(JsonKey.RESPONSE); return responseList; } return new ArrayList<>(); }
Example #4
Source File: AmqpClientActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testCloseConnectionFails() throws JMSException { new TestKit(actorSystem) {{ doThrow(JMS_EXCEPTION).when(mockConnection).close(); 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(CONNECTED_SUCCESS); amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef()); expectMsg(DISCONNECTED_SUCCESS); }}; }
Example #5
Source File: AmqpClientActor.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Override protected boolean isEventUpToDate(final Object event, final BaseClientState state, @Nullable final ActorRef sender) { switch (state) { case CONNECTED: // while connected, events from publisher or consumer child actors are relevant return sender != null && sender.path().toStringWithoutAddress().startsWith(getSelf().path().toStringWithoutAddress()) && (sender.path().name().startsWith(AmqpConsumerActor.ACTOR_NAME_PREFIX) || sender.path().name().startsWith(AmqpPublisherActor.ACTOR_NAME_PREFIX)); case CONNECTING: return Objects.equals(sender, connectConnectionHandler); case DISCONNECTING: return Objects.equals(sender, disconnectConnectionHandler); case TESTING: default: // no need to check testConnectionHandler because test runs only once during this actor's lifetime // ignore random events by default - they could come from a connection handler that is already dead return false; } }
Example #6
Source File: UserExternalIdManagementActorTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testUpsertUserExternalIdentityDetailsRemoveSuccess() { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); Request request = new Request(); request.setOperation(UserActorOperations.UPSERT_USER_EXTERNAL_IDENTITY_DETAILS.getValue()); HashMap<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.OPERATION_TYPE, "UPDATE"); List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> extIdMap = new HashMap<>(); extIdMap.put(JsonKey.OPERATION, "REMOVE"); extIdMap.put(JsonKey.ID_TYPE, "anyIdType"); extIdMap.put(JsonKey.PROVIDER, "anyProvider"); list.add(extIdMap); innerMap.put(JsonKey.EXTERNAL_IDS, list); innerMap.put(JsonKey.USER_ID, "anyUserId"); request.setRequest(innerMap); subject.tell(request, probe.getRef()); Response response = probe.expectMsgClass(duration("100 second"), Response.class); Assert.assertTrue(null != response && response.getResponseCode() == ResponseCode.OK); }
Example #7
Source File: RabbitMQClientActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void testConnectionWithoutPublisherHandling() { new TestKit(actorSystem) {{ final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId(); final Connection connectionWithoutTargets = TestConstants.createConnection(randomConnectionId, new Target[0]); final Props props = RabbitMQClientActor.propsForTests(connectionWithoutTargets, getRef(), getRef(), (con, exHandler) -> mockConnectionFactory).withDispatcher(CallingThreadDispatcher.Id()); final ActorRef rabbitClientActor = actorSystem.actorOf(props); watch(rabbitClientActor); rabbitClientActor.tell(OpenConnection.of(randomConnectionId, DittoHeaders.empty()), getRef()); expectMsg(CONNECTED_SUCCESS); rabbitClientActor.tell(CloseConnection.of(randomConnectionId, DittoHeaders.empty()), getRef()); expectMsg(DISCONNECTED_SUCCESS); }}; }
Example #8
Source File: TenantPreferenceManagementActorTest.java From sunbird-lms-service with MIT License | 6 votes |
@Test public void testGetTanentPreferenceSuccessWithKeysDiff() { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); Request actorMessage = new Request(); actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, orgId); actorMessage.getRequest().put(JsonKey.KEYS, Arrays.asList("anyKey")); actorMessage.getRequest().put(JsonKey.REQUESTED_BY, USER_ID); actorMessage.setOperation(ActorOperations.GET_TENANT_PREFERENCE.getValue()); subject.tell(actorMessage, probe.getRef()); Response res = probe.expectMsgClass(duration("10 second"), Response.class); Assert.assertTrue(null != res); }
Example #9
Source File: LocationRequestValidator.java From sunbird-lms-service with MIT License | 6 votes |
private Set<Location> getParentLocations(ActorRef actorRef, Location locationObj) { Set<Location> locationSet = new LinkedHashSet<>(); Location location = locationObj; int count = getOrder(location.getType()); locationSet.add(location); while (count > 0) { Location parent = null; if (getOrder(location.getType()) == 0 && StringUtils.isNotEmpty(location.getId())) { parent = locationClient.getLocationById(actorRef, location.getId()); } else if (StringUtils.isNotEmpty(location.getParentId())) { parent = locationClient.getLocationById(actorRef, location.getParentId()); } if (null != parent) { locationSet.add(parent); location = parent; } count--; } return locationSet; }
Example #10
Source File: ThingPersistenceActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
private void testModifyThing(final DittoHeaders dittoHeaders, final Thing thing, final Thing modifiedThing) { final ModifyThing modifyThingCommand = ModifyThing.of(getIdOrThrow(thing), modifiedThing, null, dittoHeaders); new TestKit(actorSystem) { { final ActorRef underTest = createPersistenceActorFor(thing); final CreateThing createThing = CreateThing.of(thing, null, dittoHeaders); underTest.tell(createThing, getRef()); final CreateThingResponse createThingResponse = expectMsgClass(CreateThingResponse.class); assertThingInResponse(createThingResponse.getThingCreated().orElse(null), thing); underTest.tell(modifyThingCommand, getRef()); expectMsgEquals(modifyThingResponse(thing, modifiedThing, dittoHeaders, false)); } }; }
Example #11
Source File: AkkaInvocationHandler.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
AkkaInvocationHandler( String address, String hostname, ActorRef rpcEndpoint, Time timeout, long maximumFramesize, @Nullable CompletableFuture<Void> terminationFuture) { this.address = Preconditions.checkNotNull(address); this.hostname = Preconditions.checkNotNull(hostname); this.rpcEndpoint = Preconditions.checkNotNull(rpcEndpoint); this.isLocal = this.rpcEndpoint.path().address().hasLocalScope(); this.timeout = Preconditions.checkNotNull(timeout); this.maximumFramesize = maximumFramesize; this.terminationFuture = terminationFuture; }
Example #12
Source File: HiveMqtt5SubscriptionHandler.java From ditto with Eclipse Public License 2.0 | 6 votes |
private CompletableFuture<Mqtt5SubAck> subscribe(final Source source, final Mqtt5Subscribe mqtt5Subscribe, final ActorRef consumerActor) { return client.toAsync() .subscribe(mqtt5Subscribe, msg -> consumerActor.tell(msg, ActorRef.noSender())) .whenComplete((mqtt5SubAck, throwable) -> { if (throwable != null) { // Handle failure to subscribe log.warning("Error subscribing to topics: <{}>: {}", source.getAddresses(), throwable.getMessage()); } else { // Handle successful subscription, e.g. logging or incrementing a metric log.info("Successfully subscribed to <{}>", source.getAddresses()); } }); }
Example #13
Source File: BackOffActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void backOffDuringBackOffWillDelayMessage() { new TestKit(actorSystem) {{ final ActorRef underTest = childActorOf(BackOffActor.props(createBackOffConfig())); final String initialMessage = "This should not be received as the back off is cancelled."; underTest.tell(BackOffActor.createBackOffWithAnswerMessage(initialMessage), getRef()); // verify there happens a back off expectNoMessage(HALF_BACK_OFF_DURATION); final String expectedMessage = "I expect to receive this after the second backOff"; underTest.tell(BackOffActor.createBackOffWithAnswerMessage(expectedMessage), getRef()); // verify there happens another back off expectNoMessage(BACK_OFF_DURATION); // verify we receive the answer afterwards expectMsg(DOUBLE_BACK_OFF_DURATION, expectedMessage); }}; }
Example #14
Source File: PolicyPersistenceActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void modifyPolicy() { final Policy policy = createPolicyWithRandomId(); final CreatePolicy createPolicyCommand = CreatePolicy.of(policy, dittoHeadersV2); final Policy modifiedPolicy = policy.setEntry( PoliciesModelFactory.newPolicyEntry(Label.of("anotherOne"), POLICY_SUBJECTS, POLICY_RESOURCES_ALL)); final ModifyPolicy modifyPolicyCommand = ModifyPolicy.of(policy.getEntityId().get(), modifiedPolicy, dittoHeadersV2); new TestKit(actorSystem) { { final ActorRef underTest = createPersistenceActorFor(this, policy); underTest.tell(createPolicyCommand, getRef()); final CreatePolicyResponse createPolicyResponse = expectMsgClass(CreatePolicyResponse.class); DittoPolicyAssertions.assertThat(createPolicyResponse.getPolicyCreated().get()) .isEqualEqualToButModified(policy); underTest.tell(modifyPolicyCommand, getRef()); expectMsgEquals(modifyPolicyResponse(incrementRevision(policy, 2), dittoHeadersV2, false)); } }; }
Example #15
Source File: HttpPushClientActorTest.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Test public void placeholderReplacement() throws Exception { final Target target = TestConstants.Targets.TARGET_WITH_PLACEHOLDER .withAddress("PATCH:" + TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress()); connection = connection.toBuilder().setTargets(singletonList(target)).build(); new TestKit(actorSystem) {{ // GIVEN: local HTTP connection is connected final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), getConnection(false))); underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef()); expectMsg(new Status.Success(BaseClientState.CONNECTED)); // WHEN: a thing event is sent to a target with header mapping content-type=application/json final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(Collections.emptyList()); final OutboundSignal outboundSignal = OutboundSignalFactory.newOutboundSignal(thingModifiedEvent, singletonList(target)); underTest.tell(outboundSignal, getRef()); // THEN: a POST-request is forwarded to the path defined in the target final HttpRequest thingModifiedRequest = requestQueue.take(); responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK)); assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target:ditto/thing@twin"); }}; }
Example #16
Source File: HiveMqtt5ClientActor.java From ditto with Eclipse Public License 2.0 | 6 votes |
@Override protected void doConnectClient(final Connection connection, @Nullable final ActorRef origin) { final ActorRef self = getSelf(); getClient().toAsync() .connectWith() .cleanStart(CLEAN_START) .send() .whenComplete((unused, throwable) -> { if (null != throwable) { // BaseClientActor will handle and log all ConnectionFailures. log.debug("Connecting failed ({}): {}", throwable.getClass().getName(), throwable.getMessage()); self.tell(new ImmutableConnectionFailure(origin, throwable, null), origin); } else { // tell self we connected successfully to proceed with connection establishment connectionLogger.success("Connection to {0} established successfully.", connection.getHostname()); self.tell(new MqttClientConnected(origin), getSelf()); } }); }
Example #17
Source File: DispatcherActor.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Verify the actor path of self agrees with what is advertised in ditto-services-models-concierge. * * @param self ActorRef of this actor. */ private static void sanityCheck(final ActorRef self) { final String selfPath = self.path().toStringWithoutAddress(); if (!Objects.equals(DISPATCHER_ACTOR_PATH, selfPath)) { final String message = String.format("Path of <%s> is <%s>, which does not agree with the advertised path <%s>", ACTOR_NAME, selfPath, DISPATCHER_ACTOR_PATH); throw new IllegalStateException(message); } }
Example #18
Source File: SubscriptionActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void emptyResults() { new TestKit(actorSystem) {{ final ActorRef underTest = watch(newSubscriptionActor(Duration.ofMinutes(1L), this)); connect(underTest, Source.empty(), this); expectMsg(SubscriptionComplete.of(underTest.path().name(), DittoHeaders.empty())); }}; }
Example #19
Source File: MessageMappingProcessorActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void testTopicOnLiveTopicPathCombinationError() { final String correlationId = UUID.randomUUID().toString(); final AuthorizationContext authorizationContext = AuthorizationModelFactory.newAuthContext( DittoAuthorizationContextType.UNSPECIFIED, AuthorizationModelFactory.newAuthSubject("integration:" + correlationId + ":hub-application/json")); new TestKit(actorSystem) {{ final ActorRef messageMappingProcessorActor = createMessageMappingProcessorActor(this); // WHEN: message sent with valid topic and invalid topic+path combination final String topicPrefix = "Testspace/octopus/things/live/"; final String topic = topicPrefix + "commands/retrieve"; final String path = "/policyId"; final String messageContent = "{ \n" + " \"topic\":\"" + topic + "\",\n" + " \"path\":\"" + path + "\"\n" + "}"; final ExternalMessage inboundMessage = ExternalMessageFactory.newExternalMessageBuilder(Collections.emptyMap()) .withText(messageContent) .withAuthorizationContext(authorizationContext) .build(); messageMappingProcessorActor.tell(inboundMessage, getRef()); // THEN: resulting error response retains the topic including thing ID and channel final ExternalMessage outboundMessage = expectMsgClass(PublishMappedMessage.class).getOutboundSignal().getExternalMessage(); assertThat(outboundMessage) .extracting(e -> JsonFactory.newObject(e.getTextPayload().orElse("{}")) .getValue("topic")) .isEqualTo(Optional.of(JsonValue.of(topicPrefix + "errors"))); }}; }
Example #20
Source File: Platform.java From mercury with Apache License 2.0 | 5 votes |
public void release(String route) throws IOException { if (route != null && registry.containsKey(route)) { ServiceDef def = registry.get(route); if (!def.isPrivate() && ServerPersonality.getInstance().getType() != ServerPersonality.Type.PLATFORM) { TargetRoute cloud = PostOffice.getInstance().getCloudRoute(); if (cloud != null) { boolean tell = false; if (cloud.isEventNode()) { EventNodeConnector connector = EventNodeConnector.getInstance(); if (connector.isConnected() && connector.isReady()) { // event node does not have local buffering so we can only send when it is connected tell = true; } } else { // MQ has local buffering so we can send any time tell = true; } if (tell) { PostOffice.getInstance().send(ServiceDiscovery.SERVICE_REGISTRY, new Kv(ServiceDiscovery.ROUTE, route), new Kv(ServiceDiscovery.ORIGIN, getOrigin()), new Kv(ServiceDiscovery.TYPE, ServiceDiscovery.UNREGISTER)); } } } ActorRef manager = getManager(route); if (manager != null) { registry.remove(route); manager.tell(STOP, ActorRef.noSender()); } } else { throw new IOException("Route "+route+" not found"); } }
Example #21
Source File: BaseClientActor.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Starts the {@link MessageMappingProcessorActor} responsible for payload transformation/mapping as child actor * behind a (cluster node local) RoundRobin pool and a dynamic resizer from the current mapping context. * * @return {@link org.eclipse.ditto.services.connectivity.messaging.MessageMappingProcessorActor} or exception, * which will also cause a side-effect that stores the mapping actor in the local variable {@code * messageMappingProcessorActor}. */ private ActorRef startMessageMappingProcessorActor() { final Connection connection = connection(); final MessageMappingProcessor processor; try { // this one throws DittoRuntimeExceptions when the mapper could not be configured processor = MessageMappingProcessor.of(connectionId(), connection().getPayloadMappingDefinition(), getContext().getSystem(), connectivityConfig, protocolAdapterProvider, log); } catch (final DittoRuntimeException dre) { connectionLogger.failure("Failed to start message mapping processor due to: {}.", dre.getMessage()); log.info( "Got DittoRuntimeException during initialization of MessageMappingProcessor: {} {} - desc: {}", dre.getClass().getSimpleName(), dre.getMessage(), dre.getDescription().orElse("")); getSender().tell(dre, getSelf()); throw dre; } log.info("Configured for processing messages with the following MessageMapperRegistry: <{}>", processor.getRegistry()); log.debug("Starting MessageMappingProcessorActor with pool size of <{}>.", connection.getProcessorPoolSize()); final Props props = MessageMappingProcessorActor.props(conciergeForwarder, getSelf(), processor, connectionId(), connectionActor, connection.getProcessorPoolSize()); return getContext().actorOf(props, MessageMappingProcessorActor.ACTOR_NAME); }
Example #22
Source File: AbstractSubscriptions.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Construct subscriptions using the given maps. * Consistency between the maps is not checked. * * @param subscriberToTopic map from subscribers to topics. * @param subscriberToFilter map from subscribers to filters. * @param topicToData map from topics to their data. */ protected AbstractSubscriptions( final Map<ActorRef, Set<String>> subscriberToTopic, final Map<ActorRef, Predicate<Collection<String>>> subscriberToFilter, final Map<String, TopicData<H>> topicToData) { this.subscriberToTopic = subscriberToTopic; this.subscriberToFilter = subscriberToFilter; this.topicToData = topicToData; }
Example #23
Source File: AkkaRpcService.java From flink with Apache License 2.0 | 5 votes |
private CompletableFuture<ActorRef> resolveActorAddress(String address) { final ActorSelection actorSel = actorSystem.actorSelection(address); return actorSel.resolveOne(TimeUtils.toDuration(configuration.getTimeout())) .toCompletableFuture() .exceptionally(error -> { throw new CompletionException( new RpcConnectionException(String.format("Could not connect to rpc endpoint under address %s.", address), error)); }); }
Example #24
Source File: KafkaClientActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void testRetrieveConnectionMetrics() { new TestKit(actorSystem) {{ final Props props = getKafkaClientActorProps(getRef(), connection); final ActorRef kafkaClientActor = actorSystem.actorOf(props); kafkaClientActor.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef()); expectMsg(CONNECTED_SUCCESS); kafkaClientActor.tell(RetrieveConnectionMetrics.of(connectionId, DittoHeaders.empty()), getRef()); expectMsgClass(RetrieveConnectionMetricsResponse.class); }}; }
Example #25
Source File: ThingPersistenceActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void ensureModifiedCorrectnessAfterRecovery() { new TestKit(actorSystem) { { final Thing thing = createThingV1WithRandomId(); final ActorRef thingPersistenceActor = watch(createPersistenceActorFor(thing)); final JsonFieldSelector fieldSelector = Thing.JsonFields.MODIFIED.getPointer().toFieldSelector(); // create thing final CreateThing createThing = CreateThing.of(thing, null, dittoHeadersV1); thingPersistenceActor.tell(createThing, getRef()); expectMsgClass(CreateThingResponse.class); final Instant createThingResponseTimestamp = Instant.now(); // restart thingPersistenceActor.tell(PoisonPill.getInstance(), getRef()); expectTerminated(thingPersistenceActor); final ActorRef thingPersistenceActorRecovered = Retry.untilSuccess(() -> createPersistenceActorFor(thing)); final RetrieveThing retrieveThing = RetrieveThing.getBuilder(getIdOrThrow(thing), dittoHeadersV1) .withSelectedFields(fieldSelector) .build(); Awaitility.await().atMost(10L, TimeUnit.SECONDS).untilAsserted(() -> { thingPersistenceActorRecovered.tell(retrieveThing, getRef()); final RetrieveThingResponse retrieveThingResponse = expectMsgClass(RetrieveThingResponse.class); assertThat(retrieveThingResponse.getThing()).isNotModifiedAfter(createThingResponseTimestamp); assertThat(getLastSender()).isEqualTo(thingPersistenceActorRecovered); }); } }; }
Example #26
Source File: AppActor.java From iotplatform with Apache License 2.0 | 5 votes |
private void processDeviceMsg(ToDeviceActorMsg toDeviceActorMsg) { TenantId tenantId = toDeviceActorMsg.getTenantId(); ActorRef tenantActor = getOrCreateTenantActor(tenantId); if (toDeviceActorMsg.getPayload().getMsgType().requiresRulesProcessing()) { tenantActor.tell(new RuleChainDeviceMsg(toDeviceActorMsg, null, ruleManager.getRuleChain()), context().self()); } else { tenantActor.tell(toDeviceActorMsg, context().self()); } }
Example #27
Source File: BulkUploadManagementActorTest.java From sunbird-lms-service with MIT License | 5 votes |
@Test public void checkTelemetryKeyFailure() throws Exception { TestKit probe = new TestKit(system); ActorRef subject = system.actorOf(props); String telemetryEnvKey = "user"; PowerMockito.mockStatic(Util.class); PowerMockito.doNothing() .when( Util.class, "initializeContext", Mockito.any(Request.class), Mockito.eq(telemetryEnvKey)); byte[] bytes = getFileAsBytes("BulkOrgUploadSample.csv"); Response response = createCassandraInsertSuccessResponse(); when(cassandraOperation.insertRecord( Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())) .thenReturn(response); Request reqObj = new Request(); reqObj.setOperation(ActorOperations.BULK_UPLOAD.getValue()); HashMap<String, Object> innerMap = new HashMap<>(); innerMap.put(JsonKey.CREATED_BY, USER_ID); innerMap.put(JsonKey.OBJECT_TYPE, JsonKey.ORGANISATION); innerMap.put(JsonKey.FILE, bytes); reqObj.getRequest().put(JsonKey.DATA, innerMap); subject.tell(reqObj, probe.getRef()); Response res = probe.expectMsgClass(duration("10 second"), Response.class); String uploadProcessId = (String) res.get(JsonKey.PROCESS_ID); Assert.assertTrue(!(telemetryEnvKey.charAt(0) >= 65 && telemetryEnvKey.charAt(0) <= 90)); }
Example #28
Source File: MongoHealthChecker.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Override protected void triggerHealthRetrieval() { generateStatusResponse().thenAccept(errorOpt -> { final CurrentMongoStatus mongoStatus; if (errorOpt.isPresent()) { final Throwable error = errorOpt.get(); mongoStatus = new CurrentMongoStatus(false, error.getClass().getCanonicalName() + ": " + error.getMessage()); } else { mongoStatus = new CurrentMongoStatus(true); } getSelf().tell(mongoStatus, ActorRef.noSender()); }); }
Example #29
Source File: MessageAggregator.java From ditto with Eclipse Public License 2.0 | 5 votes |
@SuppressWarnings("unused") private MessageAggregator( final ActorRef initialReceiver, final Class<T> messageClass, final int expectedMessages, final Duration timeout) { this.initialReceiver = initialReceiver; this.expectedMessages = expectedMessages; this.messageClass = messageClass; getTimers().startSingleTimer(TIMEOUT, TIMEOUT, timeout); }
Example #30
Source File: KafkaClientActorTest.java From ditto with Eclipse Public License 2.0 | 5 votes |
@Test public void testTestConnectionFails() { new TestKit(actorSystem) {{ final Props props = getKafkaClientActorProps(getRef(), new Status.Failure(new IllegalStateException("just for testing")), connection); final ActorRef kafkaClientActor = actorSystem.actorOf(props); kafkaClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef()); expectMsgClass(Status.Failure.class); }}; }