akka.actor.ActorContext Java Examples
The following examples show how to use
akka.actor.ActorContext.
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: RuleManager.java From iotplatform with Apache License 2.0 | 6 votes |
public Optional<ActorRef> update(ActorContext context, RuleId ruleId, ComponentLifecycleEvent event) { RuleMetaData rule; if (event != ComponentLifecycleEvent.DELETED) { rule = systemContext.getRuleService().findRuleById(ruleId); } else { rule = ruleMap.keySet().stream().filter(r -> r.getId().equals(ruleId)) .peek(r -> r.setState(ComponentLifecycleState.SUSPENDED)).findFirst().orElse(null); if (rule != null) { ruleMap.remove(rule); ruleActors.remove(ruleId); } } if (rule != null) { RuleActorMetaData actorMd = ruleMap.get(rule); if (actorMd == null) { ActorRef ref = getOrCreateRuleActor(context, rule.getId()); actorMd = RuleActorMetaData.systemRule(rule.getId(), rule.getWeight(), ref); ruleMap.put(rule, actorMd); } refreshRuleChain(); return Optional.of(actorMd.getActorRef()); } else { log.warn("[{}] Can't process unknown rule!", ruleId); return Optional.empty(); } }
Example #2
Source File: PluginActorMessageProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void onUpdate(ActorContext context) throws Exception { PluginMetaData oldPluginMd = pluginMd; pluginMd = systemContext.getPluginService().findPluginById(entityId); boolean requiresRestart = false; logger.info("[{}] Plugin configuration was updated from {} to {}.", entityId, oldPluginMd, pluginMd); if (!oldPluginMd.getClazz().equals(pluginMd.getClazz())) { logger.info("[{}] Plugin requires restart due to clazz change from {} to {}.", entityId, oldPluginMd.getClazz(), pluginMd.getClazz()); requiresRestart = true; } else if (!oldPluginMd.getConfiguration().equals(pluginMd.getConfiguration())) { logger.info("[{}] Plugin requires restart due to configuration change from {} to {}.", entityId, oldPluginMd.getConfiguration(), pluginMd.getConfiguration()); requiresRestart = true; } if (requiresRestart) { this.state = ComponentLifecycleState.SUSPENDED; if (pluginImpl != null) { pluginImpl.stop(trustedCtx); } start(); } }
Example #3
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
private void processSubscriptionCommands(ActorContext context, ToDeviceActorMsg msg) { SessionId sessionId = msg.getSessionId(); SessionType sessionType = msg.getSessionType(); FromDeviceMsg inMsg = msg.getPayload(); if (inMsg.getMsgType() == MsgType.SUBSCRIBE_ATTRIBUTES_REQUEST) { logger.debug("[{}] Registering attributes subscription for session [{}]", deviceId, sessionId); attributeSubscriptions.put(sessionId, new SessionInfo(sessionType, msg.getServerAddress())); } else if (inMsg.getMsgType() == MsgType.UNSUBSCRIBE_ATTRIBUTES_REQUEST) { logger.debug("[{}] Canceling attributes subscription for session [{}]", deviceId, sessionId); attributeSubscriptions.remove(sessionId); } else if (inMsg.getMsgType() == MsgType.SUBSCRIBE_RPC_COMMANDS_REQUEST) { logger.debug("[{}] Registering rpc subscription for session [{}][{}]", deviceId, sessionId, sessionType); rpcSubscriptions.put(sessionId, new SessionInfo(sessionType, msg.getServerAddress())); sendPendingRequests(context, sessionId, sessionType, msg.getServerAddress()); } else if (inMsg.getMsgType() == MsgType.UNSUBSCRIBE_RPC_COMMANDS_REQUEST) { logger.debug("[{}] Canceling rpc subscription for session [{}][{}]", deviceId, sessionId, sessionType); rpcSubscriptions.remove(sessionId); } }
Example #4
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
private Consumer<Map.Entry<Integer, ToDeviceRpcRequestMetadata>> processPendingRpc(ActorContext context, SessionId sessionId, Optional<ServerAddress> server, Set<UUID> sentOneWayIds) { return entry -> { ToDeviceRpcRequest request = entry.getValue().getMsg().getMsg(); ToDeviceRpcRequestBody body = request.getBody(); if (request.isOneway()) { sentOneWayIds.add(request.getId()); ToPluginRpcResponseDeviceMsg responsePluginMsg = toPluginRpcResponseMsg(entry.getValue().getMsg(), (String) null); context.parent().tell(responsePluginMsg, ActorRef.noSender()); } ToDeviceRpcRequestMsg rpcRequest = new ToDeviceRpcRequestMsg(entry.getKey(), body.getMethod(), body.getParams()); ToDeviceSessionActorMsg response = new BasicToDeviceSessionActorMsg(rpcRequest, sessionId); sendMsgToSessionActor(response, server); }; }
Example #5
Source File: RuleActorMessageProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void onActivate(ActorContext context) throws Exception { logger.info("[{}] Going to process onActivate rule.", entityId); this.state = ComponentLifecycleState.ACTIVE; if (filters != null) { filters.forEach(RuleLifecycleComponent::resume); if (processor != null) { processor.resume(); } else { initProcessor(); } if (action != null) { action.resume(); } logger.info("[{}] Rule resumed.", entityId); } else { start(); } }
Example #6
Source File: RuleActorMessageProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
private void pushToNextRule(ActorContext context, ChainProcessingContext ctx, RuleEngineError error) { if (error != null) { ctx = ctx.withError(error); } if (ctx.isFailure()) { logger.debug("[{}][{}] Forwarding processing chain to device actor due to failure.", ruleMd.getId(), ctx.getInMsg().getDeviceId()); ctx.getDeviceActor().tell(new RulesProcessedMsg(ctx), ActorRef.noSender()); } else if (!ctx.hasNext()) { logger.debug("[{}][{}] Forwarding processing chain to device actor due to end of chain.", ruleMd.getId(), ctx.getInMsg().getDeviceId()); ctx.getDeviceActor().tell(new RulesProcessedMsg(ctx), ActorRef.noSender()); } else { logger.debug("[{}][{}] Forwarding processing chain to next rule actor.", ruleMd.getId(), ctx.getInMsg().getDeviceId()); ChainProcessingContext nextTask = ctx.getNext(); nextTask.getCurrentActor().tell(new RuleProcessingMsg(nextTask), context.self()); } }
Example #7
Source File: ASyncMsgProcessor.java From iotplatform with Apache License 2.0 | 6 votes |
@Override public void processToDeviceMsg(ActorContext context, ToDeviceMsg msg) { try { if (msg.getMsgType() != MsgType.SESSION_CLOSE) { switch (msg.getMsgType()) { case STATUS_CODE_RESPONSE: case GET_ATTRIBUTES_RESPONSE: ResponseMsg responseMsg = (ResponseMsg) msg; if (responseMsg.getRequestId() >= 0) { logger.debug("[{}] Pending request processed: {}", responseMsg.getRequestId(), responseMsg); pendingMap.remove(responseMsg.getRequestId()); } break; } sessionCtx.onMsg(new BasicSessionActorToAdaptorMsg(this.sessionCtx, msg)); } else { sessionCtx.onMsg(org.iotp.analytics.ruleengine.common.msg.session.ctrl.SessionCloseMsg .onCredentialsRevoked(sessionCtx.getSessionId())); } } catch (SessionException e) { logger.warning("Failed to push session response msg", e); } }
Example #8
Source File: ConciergeEnforcerClusterRouterFactory.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Creates a new {@link ClusterRouterGroup} for the {@code EnforcerActor} at path * {@value #CONCIERGE_SERVICE_ENFORCER_PATH} for cluster role of {@value ConciergeMessagingConstants#CLUSTER_ROLE}. * * @param context the ActorContext in which to create the cluster router (e.g. a RootActor). * @param numberOfRoutees the number of routees to which to "dispatch" messages based on the hashing of the sent * messages. * @return the ActorRef of the crated cluster router */ public static ActorRef createConciergeEnforcerClusterRouter(final ActorContext context, final int numberOfRoutees) { final List<String> routeesPaths = Collections.singletonList(CONCIERGE_SERVICE_ENFORCER_PATH); final Set<String> clusterRoles = new HashSet<>(Collections.singletonList(ConciergeMessagingConstants.CLUSTER_ROLE)); return context.actorOf( new ClusterRouterGroup( new ConsistentHashingGroup(routeesPaths), new ClusterRouterGroupSettings(numberOfRoutees, routeesPaths, true, clusterRoles)) .props(), CONCIERGE_ENFORCER_ROUTER_ACTORNAME); }
Example #9
Source File: AcknowledgementAggregatorActorStarter.java From ditto with Eclipse Public License 2.0 | 5 votes |
private AcknowledgementAggregatorActorStarter(final ActorContext context, final ThingModifyCommand<?> thingModifyCommand, final AcknowledgementConfig acknowledgementConfig, final HeaderTranslator headerTranslator, final Consumer<Signal<?>> responseSignalConsumer) { actorContext = checkNotNull(context, "context"); this.thingModifyCommand = checkNotNull(thingModifyCommand, "thingModifyCommand"); this.acknowledgementConfig = checkNotNull(acknowledgementConfig, "acknowledgementConfig"); this.headerTranslator = checkNotNull(headerTranslator, "headerTranslator"); this.responseSignalConsumer = checkNotNull(responseSignalConsumer, "responseSignalConsumer"); }
Example #10
Source File: PluginManager.java From iotplatform with Apache License 2.0 | 5 votes |
public void init(ActorContext context) { PageDataIterable<PluginMetaData> pluginIterator = new PageDataIterable<>(getFetchPluginsFunction(), ContextAwareActor.ENTITY_PACK_LIMIT); for (PluginMetaData plugin : pluginIterator) { log.debug("[{}] Creating plugin actor", plugin.getId()); getOrCreatePluginActor(context, plugin.getId()); log.debug("Plugin actor created."); } }
Example #11
Source File: AbstractSessionActorMsgProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
protected Optional<ServerAddress> forwardToAppActorIfAdressChanged(ActorContext ctx, ToDeviceActorMsg toForward, Optional<ServerAddress> oldAddress) { Optional<ServerAddress> newAddress = systemContext.getRoutingService().resolveById(toForward.getDeviceId()); if (!newAddress.equals(oldAddress)) { if (newAddress.isPresent()) { systemContext.getRpcService().tell(newAddress.get(), toForward.toOtherAddress(systemContext.getRoutingService().getCurrentServer())); } else { getAppActor().tell(toForward, ctx.self()); } } return newAddress; }
Example #12
Source File: RuleActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
void onPluginMsg(ActorContext context, PluginToRuleMsg<?> msg) { RuleProcessingMsg pendingMsg = pendingMsgMap.remove(msg.getUid()); if (pendingMsg != null) { ChainProcessingContext ctx = pendingMsg.getCtx(); Optional<ToDeviceMsg> ruleResponseOptional = action.convert(msg); if (ruleResponseOptional.isPresent()) { ctx.mergeResponse(ruleResponseOptional.get()); pushToNextRule(context, ctx, null); } else { pushToNextRule(context, ctx, RuleEngineError.NO_RESPONSE_FROM_ACTIONS); } } else { logger.warning("[{}] Processing timeout detected: [{}]", entityId, msg.getUid()); } }
Example #13
Source File: AbstractPubSubFactory.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Create a pub-sub factory. * * @param context context of the actor under which publisher and subscriber actors are created. * @param messageClass the class of messages to publish and subscribe for. * @param topicExtractor a function extracting from each message the topics it was published at. * @param provider provider of the underlying ddata extension. */ protected AbstractPubSubFactory(final ActorContext context, final Class<T> messageClass, final PubSubTopicExtractor<T> topicExtractor, final DDataProvider provider) { this.actorRefFactory = context; this.messageClass = messageClass; factoryId = provider.clusterRole; this.topicExtractor = topicExtractor; ddataConfig = provider.getConfig(context.system()); ddata = CompressedDData.of(context.system(), provider); }
Example #14
Source File: AbstractSessionActorMsgProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
protected void forwardToAppActor(ActorContext ctx, ToAssetActorMsg toForward, Optional<ServerAddress> address) { if (address.isPresent()) { systemContext.getRpcService().tell(address.get(), toForward.toOtherAddress(systemContext.getRoutingService().getCurrentServer())); } else { getAppActor().tell(toForward, ctx.self()); } }
Example #15
Source File: SyncMsgProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
@Override protected void processToDeviceActorMsg(ActorContext ctx, ToDeviceActorSessionMsg msg) { updateSessionCtx(msg, SessionType.SYNC); pendingMsg = toDeviceMsg(msg); pendingResponse = true; currentTargetServer = forwardToAppActor(ctx, pendingMsg); scheduleMsgWithDelay(ctx, new SessionTimeoutMsg(sessionId), getTimeout(systemContext, msg.getSessionMsg().getSessionContext()), ctx.parent()); }
Example #16
Source File: ClusterUtil.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Start a proxy to a singleton actor. * * @param context context to create the proxy actor in. * @param role role of the singleton actor. * @param singleton actor reference of the singleton manager. * @return actor reference of the proxy to the singleton actor. */ public static ActorRef startSingletonProxy(final ActorContext context, final String role, final ActorRef singleton) { final ClusterSingletonProxySettings settings = ClusterSingletonProxySettings.create(context.system()).withRole(role); final Props proxyProps = ClusterSingletonProxy.props(singleton.path().toStringWithoutAddress(), settings); return context.actorOf(proxyProps, singleton.path().name() + "Proxy"); }
Example #17
Source File: SshLocalManagerImpl.java From java-11-examples with Apache License 2.0 | 5 votes |
public void onSessionCreateResquest(ActorContext actorContext, ActorRef sender, ActorRef self, SessionCreateRequest sessionCreateRequest) { LOG.info("create session from: {}", sessionCreateRequest.getClientActorAddress()); try { String sessionId = UUID.randomUUID().toString(); //1. create session objects and actor SshClientSessionListenerImpl sshClientSessionListener = new SshClientSessionListenerImpl(); SshClientSession sshSession = sshSessionFactory.createSshSession(sessionCreateRequest.getHostData(), sessionCreateRequest.getUserCredentials(), sessionId, sshClientSessionListener); ActorRef sshSessionActorRef = actorContext.system().actorOf(Props.create( SshSessionActor.class, sshSession, sessionCreateRequest.getClientId(), sessionCreateRequest.getClientActorAddress(), sshClientSessionListener), Utils.generateSessionActorName(sessionId)); //2. notify creator about ssh session creation result String sessionActorAddress = Utils.getSshSessionAddress(nodeAddress, sshSession.getId()); SessionCreateResponse sessionCreateResponse = new SessionCreateResponse(sshSession.getId(), sessionCreateRequest.getClientId(), sessionActorAddress, Utils.getSshLocalManagerActorAddress(nodeAddress)); sender.tell(sessionCreateResponse, self); ActiveSessionData activeSessionInfo = new ActiveSessionData( sessionCreateRequest.getClientId(), sshSessionActorRef, sshSession.getId(), sessionCreateRequest.getClientActorAddress(), sshSession); activeSessions.put(sshSession.getId(), activeSessionInfo); } catch (SshClientException e) { SessionCreateError sessionError = new SessionCreateError(sessionCreateRequest.getClientId()); sender.tell(sessionError, self); } }
Example #18
Source File: RuleManager.java From iotplatform with Apache License 2.0 | 5 votes |
public void init(ActorContext context) { PageDataIterable<RuleMetaData> ruleIterator = new PageDataIterable<>(getFetchRulesFunction(), ContextAwareActor.ENTITY_PACK_LIMIT); ruleMap = new HashMap<>(); for (RuleMetaData rule : ruleIterator) { log.debug("[{}] Creating rule actor {}", rule.getId(), rule); ActorRef ref = getOrCreateRuleActor(context, rule.getId()); RuleActorMetaData actorMd = RuleActorMetaData.systemRule(rule.getId(), rule.getWeight(), ref); ruleMap.put(rule, actorMd); log.debug("[{}] Rule actor created.", rule.getId()); } refreshRuleChain(); }
Example #19
Source File: SyncMsgProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
public void processToAssetMsg(ActorContext context, ToDeviceMsg msg) { try { sessionCtx.onMsg(new BasicSessionActorToAdaptorMsg(this.sessionCtx, msg)); pendingResponse = false; } catch (SessionException e) { logger.warning("Failed to push session response msg", e); } terminateSession(context, this.sessionId); }
Example #20
Source File: DittoProtocolSubImpl.java From ditto with Eclipse Public License 2.0 | 5 votes |
static DittoProtocolSubImpl of(final ActorContext context) { final DistributedSub liveSignalSub = LiveSignalPubSubFactory.of(context).startDistributedSub(); final DistributedSub twinEventSub = ThingEventPubSubFactory.readSubjectsOnly(context).startDistributedSub(); return new DittoProtocolSubImpl(liveSignalSub, twinEventSub); }
Example #21
Source File: LiveSignalPubImpl.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Start a live signal pub in an actor system. * * @param context context of the actor under which the pub and sub supervisors are started. * @return the live signal pub. */ static LiveSignalPubImpl of(final ActorContext context) { final DistributedPub<?> distributedPub = LiveSignalPubSubFactory.of(context).startDistributedPub(); final DistributedPub<Command> liveCommandPub = distributedPub.withTopicExtractor(getTopicExtractor(StreamingType.LIVE_COMMANDS)); final DistributedPub<Event> liveEventPub = distributedPub.withTopicExtractor(getTopicExtractor(StreamingType.LIVE_EVENTS)); final DistributedPub<Signal> messagePub = distributedPub.withTopicExtractor(getTopicExtractor(StreamingType.MESSAGES)); return new LiveSignalPubImpl(liveCommandPub, liveEventPub, messagePub); }
Example #22
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
void onRulesProcessedMsg(ActorContext context, RulesProcessedMsg msg) { ChainProcessingContext ctx = msg.getCtx(); ToDeviceActorMsg inMsg = ctx.getInMsg(); SessionId sid = inMsg.getSessionId(); ToDeviceSessionActorMsg response; if (ctx.getResponse() != null) { response = new BasicToDeviceSessionActorMsg(ctx.getResponse(), sid); } else { response = new BasicToDeviceSessionActorMsg(ctx.getError(), sid); } sendMsgToSessionActor(response, inMsg.getServerAddress()); }
Example #23
Source File: AbstractSessionActorMsgProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
protected void forwardToAppActor(ActorContext ctx, ToDeviceActorMsg toForward, Optional<ServerAddress> address) { if (address.isPresent()) { systemContext.getRpcService().tell(address.get(), toForward.toOtherAddress(systemContext.getRoutingService().getCurrentServer())); } else { getAppActor().tell(toForward, ctx.self()); } }
Example #24
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
void processRpcResponses(ActorContext context, ToDeviceActorMsg msg) { SessionId sessionId = msg.getSessionId(); FromDeviceMsg inMsg = msg.getPayload(); if (inMsg.getMsgType() == MsgType.TO_DEVICE_RPC_RESPONSE) { logger.debug("[{}] Processing rpc command response [{}]", deviceId, sessionId); ToDeviceRpcResponseMsg responseMsg = (ToDeviceRpcResponseMsg) inMsg; ToDeviceRpcRequestMetadata requestMd = rpcPendingMap.remove(responseMsg.getRequestId()); boolean success = requestMd != null; if (success) { ToPluginRpcResponseDeviceMsg responsePluginMsg = toPluginRpcResponseMsg(requestMd.getMsg(), responseMsg.getData()); Optional<ServerAddress> pluginServerAddress = requestMd.getMsg().getServerAddress(); if (pluginServerAddress.isPresent()) { systemContext.getRpcService().tell(pluginServerAddress.get(), responsePluginMsg); logger.debug("[{}] Rpc command response sent to remote plugin actor [{}]!", deviceId, requestMd.getMsg().getMsg().getId()); } else { context.parent().tell(responsePluginMsg, ActorRef.noSender()); logger.debug("[{}] Rpc command response sent to local plugin actor [{}]!", deviceId, requestMd.getMsg().getMsg().getId()); } } else { logger.debug("[{}] Rpc command response [{}] is stale!", deviceId, responseMsg.getRequestId()); } if (msg.getSessionType() == SessionType.SYNC) { BasicCommandAckResponse response = success ? BasicCommandAckResponse.onSuccess(MsgType.TO_DEVICE_RPC_REQUEST, responseMsg.getRequestId()) : BasicCommandAckResponse.onError(MsgType.TO_DEVICE_RPC_REQUEST, responseMsg.getRequestId(), new TimeoutException()); sendMsgToSessionActor(new BasicToDeviceSessionActorMsg(response, msg.getSessionId()), msg.getServerAddress()); } } }
Example #25
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
void process(ActorContext context, RuleChainDeviceMsg srcMsg) { ChainProcessingMetaData md = new ChainProcessingMetaData(srcMsg.getRuleChain(), srcMsg.getToDeviceActorMsg(), new DeviceMetaData(deviceId, deviceName, deviceType, deviceAttributes), context.self()); ChainProcessingContext ctx = new ChainProcessingContext(md); if (ctx.getChainLength() > 0) { RuleProcessingMsg msg = new RuleProcessingMsg(ctx); ActorRef ruleActorRef = ctx.getCurrentActor(); ruleActorRef.tell(msg, ActorRef.noSender()); } else { context.self().tell(new RulesProcessedMsg(ctx), context.self()); } }
Example #26
Source File: RuleActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void onSuspend(ActorContext context) { logger.info("[{}] Going to process onSuspend rule.", entityId); this.state = ComponentLifecycleState.SUSPENDED; if (filters != null) { filters.forEach(f -> f.suspend()); } if (processor != null) { processor.suspend(); } if (action != null) { action.suspend(); } }
Example #27
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
public void processTimeout(ActorContext context, TimeoutMsg msg) { ToDeviceRpcRequestMetadata requestMd = rpcPendingMap.remove(msg.getId()); if (requestMd != null) { logger.debug("[{}] RPC request [{}] timeout detected!", deviceId, msg.getId()); ToPluginRpcResponseDeviceMsg responsePluginMsg = toPluginRpcResponseMsg(requestMd.getMsg(), requestMd.isSent() ? RpcError.TIMEOUT : RpcError.NO_ACTIVE_CONNECTION); context.parent().tell(responsePluginMsg, ActorRef.noSender()); } }
Example #28
Source File: PluginActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void onActivate(ActorContext context) throws Exception { logger.info("[{}] Going to process onActivate plugin.", entityId); this.state = ComponentLifecycleState.ACTIVE; if (pluginImpl != null) { pluginImpl.resume(trustedCtx); logger.info("[{}] Plugin resumed.", entityId); } else { start(); } }
Example #29
Source File: PluginActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
@Override public void onSuspend(ActorContext context) { logger.info("[{}] Going to process onSuspend plugin.", entityId); this.state = ComponentLifecycleState.SUSPENDED; if (pluginImpl != null) { pluginImpl.suspend(trustedCtx); } }
Example #30
Source File: DeviceActorMessageProcessor.java From iotplatform with Apache License 2.0 | 5 votes |
void processRpcRequest(ActorContext context, ToDeviceRpcRequestPluginMsg msg) { ToDeviceRpcRequest request = msg.getMsg(); ToDeviceRpcRequestBody body = request.getBody(); ToDeviceRpcRequestMsg rpcRequest = new ToDeviceRpcRequestMsg(rpcSeq++, body.getMethod(), body.getParams()); long timeout = request.getExpirationTime() - System.currentTimeMillis(); if (timeout <= 0) { logger.debug("[{}][{}] Ignoring message due to exp time reached", deviceId, request.getId(), request.getExpirationTime()); return; } boolean sent = rpcSubscriptions.size() > 0; Set<SessionId> syncSessionSet = new HashSet<>(); rpcSubscriptions.entrySet().forEach(sub -> { ToDeviceSessionActorMsg response = new BasicToDeviceSessionActorMsg(rpcRequest, sub.getKey()); sendMsgToSessionActor(response, sub.getValue().getServer()); if (SessionType.SYNC == sub.getValue().getType()) { syncSessionSet.add(sub.getKey()); } }); syncSessionSet.forEach(rpcSubscriptions::remove); if (request.isOneway() && sent) { ToPluginRpcResponseDeviceMsg responsePluginMsg = toPluginRpcResponseMsg(msg, (String) null); context.parent().tell(responsePluginMsg, ActorRef.noSender()); logger.debug("[{}] Rpc command response sent [{}]!", deviceId, request.getId()); } else { registerPendingRpcRequest(context, msg, sent, rpcRequest, timeout); } if (sent) { logger.debug("[{}] RPC request {} is sent!", deviceId, request.getId()); } else { logger.debug("[{}] RPC request {} is NOT sent!", deviceId, request.getId()); } }