Search in sources :

Example 1 with TbRuleChainInputNodeConfiguration

use of org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration in project thingsboard by thingsboard.

the class DefaultTbRuleChainService method getOutputLabelUsage.

@Override
public List<RuleChainOutputLabelsUsage> getOutputLabelUsage(TenantId tenantId, RuleChainId ruleChainId) {
    List<RuleNode> ruleNodes = ruleChainService.findRuleNodesByTenantIdAndType(tenantId, TbRuleChainInputNode.class.getName(), ruleChainId.getId().toString());
    Map<RuleChainId, String> ruleChainNamesCache = new HashMap<>();
    // Additional filter, "just in case" the structure of the JSON configuration will change.
    var filteredRuleNodes = ruleNodes.stream().filter(node -> {
        try {
            TbRuleChainInputNodeConfiguration configuration = JacksonUtil.treeToValue(node.getConfiguration(), TbRuleChainInputNodeConfiguration.class);
            return ruleChainId.getId().toString().equals(configuration.getRuleChainId());
        } catch (Exception e) {
            log.warn("[{}][{}] Failed to decode rule node configuration", tenantId, ruleChainId, e);
            return false;
        }
    }).collect(Collectors.toList());
    return filteredRuleNodes.stream().map(ruleNode -> {
        RuleChainOutputLabelsUsage usage = new RuleChainOutputLabelsUsage();
        usage.setRuleNodeId(ruleNode.getId());
        usage.setRuleNodeName(ruleNode.getName());
        usage.setRuleChainId(ruleNode.getRuleChainId());
        List<EntityRelation> relations = ruleChainService.getRuleNodeRelations(tenantId, ruleNode.getId());
        if (relations != null && !relations.isEmpty()) {
            usage.setLabels(relations.stream().map(EntityRelation::getType).collect(Collectors.toSet()));
        }
        return usage;
    }).filter(usage -> usage.getLabels() != null).peek(usage -> {
        String ruleChainName = ruleChainNamesCache.computeIfAbsent(usage.getRuleChainId(), id -> ruleChainService.findRuleChainById(tenantId, id).getName());
        usage.setRuleChainName(ruleChainName);
    }).sorted(Comparator.comparing(RuleChainOutputLabelsUsage::getRuleChainName).thenComparing(RuleChainOutputLabelsUsage::getRuleNodeName)).collect(Collectors.toList());
}
Also used : RequiredArgsConstructor(lombok.RequiredArgsConstructor) JacksonUtil(org.thingsboard.common.util.JacksonUtil) TbRuleChainInputNode(org.thingsboard.rule.engine.flow.TbRuleChainInputNode) RuleChainMetaData(org.thingsboard.server.common.data.rule.RuleChainMetaData) HashMap(java.util.HashMap) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) TenantId(org.thingsboard.server.common.data.id.TenantId) RuleChainUpdateResult(org.thingsboard.server.common.data.rule.RuleChainUpdateResult) RuleChainService(org.thingsboard.server.dao.rule.RuleChainService) TreeSet(java.util.TreeSet) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) RelationService(org.thingsboard.server.dao.relation.RelationService) HashSet(java.util.HashSet) RuleNodeUpdateResult(org.thingsboard.server.common.data.rule.RuleNodeUpdateResult) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) Service(org.springframework.stereotype.Service) Map(java.util.Map) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) Set(java.util.Set) Collectors(java.util.stream.Collectors) TbRuleChainOutputNode(org.thingsboard.rule.engine.flow.TbRuleChainOutputNode) RuleChainOutputLabelsUsage(org.thingsboard.server.common.data.rule.RuleChainOutputLabelsUsage) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) Comparator(java.util.Comparator) Collections(java.util.Collections) RuleChainOutputLabelsUsage(org.thingsboard.server.common.data.rule.RuleChainOutputLabelsUsage) HashMap(java.util.HashMap) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) TbRuleChainInputNode(org.thingsboard.rule.engine.flow.TbRuleChainInputNode)

Example 2 with TbRuleChainInputNodeConfiguration

use of org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration in project thingsboard by thingsboard.

the class DefaultDataUpdateService method updateNestedRuleChains.

private void updateNestedRuleChains() {
    try {
        var packSize = 1024;
        var updated = 0;
        boolean hasNext = true;
        while (hasNext) {
            List<EntityRelation> relations = relationService.findRuleNodeToRuleChainRelations(TenantId.SYS_TENANT_ID, RuleChainType.CORE, packSize);
            hasNext = relations.size() == packSize;
            for (EntityRelation relation : relations) {
                try {
                    RuleNodeId sourceNodeId = new RuleNodeId(relation.getFrom().getId());
                    RuleNode sourceNode = ruleChainService.findRuleNodeById(TenantId.SYS_TENANT_ID, sourceNodeId);
                    if (sourceNode == null) {
                        log.info("Skip processing of relation for non existing source rule node: [{}]", sourceNodeId);
                        relationService.deleteRelation(TenantId.SYS_TENANT_ID, relation);
                        continue;
                    }
                    RuleChainId sourceRuleChainId = sourceNode.getRuleChainId();
                    RuleChainId targetRuleChainId = new RuleChainId(relation.getTo().getId());
                    RuleChain targetRuleChain = ruleChainService.findRuleChainById(TenantId.SYS_TENANT_ID, targetRuleChainId);
                    if (targetRuleChain == null) {
                        log.info("Skip processing of relation for non existing target rule chain: [{}]", targetRuleChainId);
                        relationService.deleteRelation(TenantId.SYS_TENANT_ID, relation);
                        continue;
                    }
                    TenantId tenantId = targetRuleChain.getTenantId();
                    RuleNode targetNode = new RuleNode();
                    targetNode.setName(targetRuleChain.getName());
                    targetNode.setRuleChainId(sourceRuleChainId);
                    targetNode.setType(TbRuleChainInputNode.class.getName());
                    TbRuleChainInputNodeConfiguration configuration = new TbRuleChainInputNodeConfiguration();
                    configuration.setRuleChainId(targetRuleChain.getId().toString());
                    targetNode.setConfiguration(JacksonUtil.valueToTree(configuration));
                    targetNode.setAdditionalInfo(relation.getAdditionalInfo());
                    targetNode.setDebugMode(false);
                    targetNode = ruleChainService.saveRuleNode(tenantId, targetNode);
                    EntityRelation sourceRuleChainToRuleNode = new EntityRelation();
                    sourceRuleChainToRuleNode.setFrom(sourceRuleChainId);
                    sourceRuleChainToRuleNode.setTo(targetNode.getId());
                    sourceRuleChainToRuleNode.setType(EntityRelation.CONTAINS_TYPE);
                    sourceRuleChainToRuleNode.setTypeGroup(RelationTypeGroup.RULE_CHAIN);
                    relationService.saveRelation(tenantId, sourceRuleChainToRuleNode);
                    EntityRelation sourceRuleNodeToTargetRuleNode = new EntityRelation();
                    sourceRuleNodeToTargetRuleNode.setFrom(sourceNode.getId());
                    sourceRuleNodeToTargetRuleNode.setTo(targetNode.getId());
                    sourceRuleNodeToTargetRuleNode.setType(relation.getType());
                    sourceRuleNodeToTargetRuleNode.setTypeGroup(RelationTypeGroup.RULE_NODE);
                    sourceRuleNodeToTargetRuleNode.setAdditionalInfo(relation.getAdditionalInfo());
                    relationService.saveRelation(tenantId, sourceRuleNodeToTargetRuleNode);
                    // Delete old relation
                    relationService.deleteRelation(tenantId, relation);
                    updated++;
                } catch (Exception e) {
                    log.info("Failed to update RuleNodeToRuleChainRelation: {}", relation, e);
                }
            }
            if (updated > 0) {
                log.info("RuleNodeToRuleChainRelations: {} entities updated so far...", updated);
            }
        }
    } catch (Exception e) {
        log.error("Unable to update Tenant", e);
    }
}
Also used : EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) TenantId(org.thingsboard.server.common.data.id.TenantId) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) ExecutionException(java.util.concurrent.ExecutionException) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) TbRuleChainInputNode(org.thingsboard.rule.engine.flow.TbRuleChainInputNode)

Example 3 with TbRuleChainInputNodeConfiguration

use of org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration in project thingsboard by thingsboard.

the class RuleChainMsgConstructor method addRuleChainConnections_V_3_3_0.

private List<RuleChainConnectionInfo> addRuleChainConnections_V_3_3_0(List<RuleNode> nodes, List<NodeConnectionInfo> connections) throws JsonProcessingException {
    List<RuleChainConnectionInfo> result = new ArrayList<>();
    for (int i = 0; i < nodes.size(); i++) {
        RuleNode node = nodes.get(i);
        if (node.getType().equalsIgnoreCase(RULE_CHAIN_INPUT_NODE)) {
            for (NodeConnectionInfo connection : connections) {
                if (connection.getToIndex() == i) {
                    RuleChainConnectionInfo e = new RuleChainConnectionInfo();
                    e.setFromIndex(connection.getFromIndex());
                    TbRuleChainInputNodeConfiguration configuration = JacksonUtil.treeToValue(node.getConfiguration(), TbRuleChainInputNodeConfiguration.class);
                    e.setTargetRuleChainId(new RuleChainId(UUID.fromString(configuration.getRuleChainId())));
                    e.setAdditionalInfo(node.getAdditionalInfo());
                    e.setType(connection.getType());
                    result.add(e);
                }
            }
        }
    }
    return result;
}
Also used : NodeConnectionInfo(org.thingsboard.server.common.data.rule.NodeConnectionInfo) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) ArrayList(java.util.ArrayList) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) RuleChainConnectionInfo(org.thingsboard.server.common.data.rule.RuleChainConnectionInfo)

Example 4 with TbRuleChainInputNodeConfiguration

use of org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration in project thingsboard by thingsboard.

the class AbstractRuleEngineFlowIntegrationTest method testTwoRuleChainsWithTwoRules.

@Test
public void testTwoRuleChainsWithTwoRules() throws Exception {
    // Creating Rule Chain
    RuleChain rootRuleChain = new RuleChain();
    rootRuleChain.setName("Root Rule Chain");
    rootRuleChain.setTenantId(savedTenant.getId());
    rootRuleChain.setRoot(true);
    rootRuleChain.setDebugMode(true);
    rootRuleChain = saveRuleChain(rootRuleChain);
    Assert.assertNull(rootRuleChain.getFirstRuleNodeId());
    // Creating Rule Chain
    RuleChain secondaryRuleChain = new RuleChain();
    secondaryRuleChain.setName("Secondary Rule Chain");
    secondaryRuleChain.setTenantId(savedTenant.getId());
    secondaryRuleChain.setRoot(false);
    secondaryRuleChain.setDebugMode(true);
    secondaryRuleChain = saveRuleChain(secondaryRuleChain);
    Assert.assertNull(secondaryRuleChain.getFirstRuleNodeId());
    RuleChainMetaData rootMetaData = new RuleChainMetaData();
    rootMetaData.setRuleChainId(rootRuleChain.getId());
    RuleNode ruleNode1 = new RuleNode();
    ruleNode1.setName("Simple Rule Node 1");
    ruleNode1.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
    ruleNode1.setDebugMode(true);
    TbGetAttributesNodeConfiguration configuration1 = new TbGetAttributesNodeConfiguration();
    configuration1.setServerAttributeNames(Collections.singletonList("serverAttributeKey1"));
    ruleNode1.setConfiguration(mapper.valueToTree(configuration1));
    RuleNode ruleNode12 = new RuleNode();
    ruleNode12.setName("Simple Rule Node 1");
    ruleNode12.setType(org.thingsboard.rule.engine.flow.TbRuleChainInputNode.class.getName());
    ruleNode12.setDebugMode(true);
    TbRuleChainInputNodeConfiguration configuration12 = new TbRuleChainInputNodeConfiguration();
    configuration12.setRuleChainId(secondaryRuleChain.getId().getId().toString());
    ruleNode12.setConfiguration(mapper.valueToTree(configuration12));
    rootMetaData.setNodes(Arrays.asList(ruleNode1, ruleNode12));
    rootMetaData.setFirstNodeIndex(0);
    NodeConnectionInfo connection = new NodeConnectionInfo();
    connection.setFromIndex(0);
    connection.setToIndex(1);
    connection.setType("Success");
    rootMetaData.setConnections(Collections.singletonList(connection));
    rootMetaData = saveRuleChainMetaData(rootMetaData);
    Assert.assertNotNull(rootMetaData);
    rootRuleChain = getRuleChain(rootRuleChain.getId());
    Assert.assertNotNull(rootRuleChain.getFirstRuleNodeId());
    RuleChainMetaData secondaryMetaData = new RuleChainMetaData();
    secondaryMetaData.setRuleChainId(secondaryRuleChain.getId());
    RuleNode ruleNode2 = new RuleNode();
    ruleNode2.setName("Simple Rule Node 2");
    ruleNode2.setType(org.thingsboard.rule.engine.metadata.TbGetAttributesNode.class.getName());
    ruleNode2.setDebugMode(true);
    TbGetAttributesNodeConfiguration configuration2 = new TbGetAttributesNodeConfiguration();
    configuration2.setServerAttributeNames(Collections.singletonList("serverAttributeKey2"));
    ruleNode2.setConfiguration(mapper.valueToTree(configuration2));
    secondaryMetaData.setNodes(Collections.singletonList(ruleNode2));
    secondaryMetaData.setFirstNodeIndex(0);
    secondaryMetaData = saveRuleChainMetaData(secondaryMetaData);
    Assert.assertNotNull(secondaryMetaData);
    // Saving the device
    Device device = new Device();
    device.setName("My device");
    device.setType("default");
    device = doPost("/api/device", device, Device.class);
    attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))).get();
    attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))).get();
    TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class);
    Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true);
    TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback);
    QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null);
    // Pushing Message to the system
    actorSystem.tell(qMsg);
    Mockito.verify(tbMsgCallback, Mockito.timeout(10000)).onSuccess();
    PageData<Event> eventsPage = getDebugEvents(savedTenant.getId(), rootRuleChain.getFirstRuleNodeId(), 1000);
    List<Event> events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
    Assert.assertEquals(2, events.size());
    Event inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
    Assert.assertEquals(rootRuleChain.getFirstRuleNodeId(), inEvent.getEntityId());
    Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
    Event outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
    Assert.assertEquals(rootRuleChain.getFirstRuleNodeId(), outEvent.getEntityId());
    Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
    Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
    RuleChain finalRuleChain = rootRuleChain;
    RuleNode lastRuleNode = secondaryMetaData.getNodes().stream().filter(node -> !node.getId().equals(finalRuleChain.getFirstRuleNodeId())).findFirst().get();
    eventsPage = getDebugEvents(savedTenant.getId(), lastRuleNode.getId(), 1000);
    events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList());
    Assert.assertEquals(2, events.size());
    inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get();
    Assert.assertEquals(lastRuleNode.getId(), inEvent.getEntityId());
    Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText());
    outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get();
    Assert.assertEquals(lastRuleNode.getId(), outEvent.getEntityId());
    Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText());
    Assert.assertEquals("serverAttributeValue1", getMetadata(outEvent).get("ss_serverAttributeKey1").asText());
    Assert.assertEquals("serverAttributeValue2", getMetadata(outEvent).get("ss_serverAttributeKey2").asText());
}
Also used : Event(org.thingsboard.server.common.data.Event) Arrays(java.util.Arrays) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) TbMsg(org.thingsboard.server.common.msg.TbMsg) Device(org.thingsboard.server.common.data.Device) RuleChainMetaData(org.thingsboard.server.common.data.rule.RuleChainMetaData) Autowired(org.springframework.beans.factory.annotation.Autowired) Tenant(org.thingsboard.server.common.data.Tenant) Mockito.spy(org.mockito.Mockito.spy) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) Answer(org.mockito.stubbing.Answer) User(org.thingsboard.server.common.data.User) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) ActorSystemContext(org.thingsboard.server.actors.ActorSystemContext) QueueToRuleEngineMsg(org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg) After(org.junit.After) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) AbstractRuleEngineControllerTest(org.thingsboard.server.controller.AbstractRuleEngineControllerTest) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) Before(org.junit.Before) TbMsgCallback(org.thingsboard.server.common.msg.queue.TbMsgCallback) DataConstants(org.thingsboard.server.common.data.DataConstants) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbGetAttributesNodeConfiguration(org.thingsboard.rule.engine.metadata.TbGetAttributesNodeConfiguration) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Test(org.junit.Test) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) Authority(org.thingsboard.server.common.data.security.Authority) Collectors(java.util.stream.Collectors) Mockito(org.mockito.Mockito) Slf4j(lombok.extern.slf4j.Slf4j) EventService(org.thingsboard.server.dao.event.EventService) List(java.util.List) PageData(org.thingsboard.server.common.data.page.PageData) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) Assert(org.junit.Assert) NodeConnectionInfo(org.thingsboard.server.common.data.rule.NodeConnectionInfo) Collections(java.util.Collections) StringDataEntry(org.thingsboard.server.common.data.kv.StringDataEntry) QueueToRuleEngineMsg(org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg) Device(org.thingsboard.server.common.data.Device) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) TbGetAttributesNodeConfiguration(org.thingsboard.rule.engine.metadata.TbGetAttributesNodeConfiguration) NodeConnectionInfo(org.thingsboard.server.common.data.rule.NodeConnectionInfo) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) StringDataEntry(org.thingsboard.server.common.data.kv.StringDataEntry) RuleChainMetaData(org.thingsboard.server.common.data.rule.RuleChainMetaData) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) Event(org.thingsboard.server.common.data.Event) TbMsgCallback(org.thingsboard.server.common.msg.queue.TbMsgCallback) TbMsg(org.thingsboard.server.common.msg.TbMsg) AbstractRuleEngineControllerTest(org.thingsboard.server.controller.AbstractRuleEngineControllerTest) Test(org.junit.Test)

Aggregations

TbRuleChainInputNodeConfiguration (org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration)4 RuleNode (org.thingsboard.server.common.data.rule.RuleNode)4 RuleChainId (org.thingsboard.server.common.data.id.RuleChainId)3 RuleChain (org.thingsboard.server.common.data.rule.RuleChain)3 Collections (java.util.Collections)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 Slf4j (lombok.extern.slf4j.Slf4j)2 TbRuleChainInputNode (org.thingsboard.rule.engine.flow.TbRuleChainInputNode)2 RuleNodeId (org.thingsboard.server.common.data.id.RuleNodeId)2 TenantId (org.thingsboard.server.common.data.id.TenantId)2 EntityRelation (org.thingsboard.server.common.data.relation.EntityRelation)2 NodeConnectionInfo (org.thingsboard.server.common.data.rule.NodeConnectionInfo)2 RuleChainMetaData (org.thingsboard.server.common.data.rule.RuleChainMetaData)2 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1