Search in sources :

Example 51 with TbMsgMetaData

use of org.thingsboard.server.common.msg.TbMsgMetaData in project thingsboard by thingsboard.

the class TelemetryEdgeProcessor method constructBaseMsgMetadata.

private TbMsgMetaData constructBaseMsgMetadata(TenantId tenantId, EntityId entityId) {
    TbMsgMetaData metaData = new TbMsgMetaData();
    switch(entityId.getEntityType()) {
        case DEVICE:
            Device device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
            if (device != null) {
                metaData.putValue("deviceName", device.getName());
                metaData.putValue("deviceType", device.getType());
            }
            break;
        case ASSET:
            Asset asset = assetService.findAssetById(tenantId, new AssetId(entityId.getId()));
            if (asset != null) {
                metaData.putValue("assetName", asset.getName());
                metaData.putValue("assetType", asset.getType());
            }
            break;
        case ENTITY_VIEW:
            EntityView entityView = entityViewService.findEntityViewById(tenantId, new EntityViewId(entityId.getId()));
            if (entityView != null) {
                metaData.putValue("entityViewName", entityView.getName());
                metaData.putValue("entityViewType", entityView.getType());
            }
            break;
        default:
            log.debug("Using empty metadata for entityId [{}]", entityId);
            break;
    }
    return metaData;
}
Also used : EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) EntityView(org.thingsboard.server.common.data.EntityView) Device(org.thingsboard.server.common.data.Device) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Asset(org.thingsboard.server.common.data.asset.Asset) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) AssetId(org.thingsboard.server.common.data.id.AssetId)

Example 52 with TbMsgMetaData

use of org.thingsboard.server.common.msg.TbMsgMetaData in project thingsboard by thingsboard.

the class RuleNodeJsScriptEngine method unbindMsg.

private static TbMsg unbindMsg(JsonNode msgData, TbMsg msg) {
    try {
        String data = null;
        Map<String, String> metadata = null;
        String messageType = null;
        if (msgData.has(RuleNodeScriptFactory.MSG)) {
            JsonNode msgPayload = msgData.get(RuleNodeScriptFactory.MSG);
            data = mapper.writeValueAsString(msgPayload);
        }
        if (msgData.has(RuleNodeScriptFactory.METADATA)) {
            JsonNode msgMetadata = msgData.get(RuleNodeScriptFactory.METADATA);
            metadata = mapper.convertValue(msgMetadata, new TypeReference<Map<String, String>>() {
            });
        }
        if (msgData.has(RuleNodeScriptFactory.MSG_TYPE)) {
            messageType = msgData.get(RuleNodeScriptFactory.MSG_TYPE).asText();
        }
        String newData = data != null ? data : msg.getData();
        TbMsgMetaData newMetadata = metadata != null ? new TbMsgMetaData(metadata) : msg.getMetaData().copy();
        String newMessageType = !StringUtils.isEmpty(messageType) ? messageType : msg.getType();
        return TbMsg.transformMsg(msg, newMessageType, msg.getOriginator(), newMetadata, newData);
    } catch (Throwable th) {
        throw new RuntimeException("Failed to unbind message data from javascript result", th);
    }
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData)

Example 53 with TbMsgMetaData

use of org.thingsboard.server.common.msg.TbMsgMetaData 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)

Example 54 with TbMsgMetaData

use of org.thingsboard.server.common.msg.TbMsgMetaData in project thingsboard by thingsboard.

the class AlarmStateTest method testSetAlarmConditionMetadata_durationCondition.

@Test
public void testSetAlarmConditionMetadata_durationCondition() {
    DurationAlarmConditionSpec spec = new DurationAlarmConditionSpec();
    spec.setUnit(TimeUnit.SECONDS);
    AlarmRuleState ruleState = createMockAlarmRuleState(spec);
    int duration = 12;
    ruleState.getState().setDuration(duration);
    AlarmState alarmState = createMockAlarmState();
    TbMsgMetaData metaData = new TbMsgMetaData();
    alarmState.setAlarmConditionMetadata(ruleState, metaData);
    assertEquals(AlarmConditionSpecType.DURATION, ruleState.getSpec().getType());
    assertNotNull(metaData.getValue(DataConstants.ALARM_CONDITION_DURATION));
    assertNull(metaData.getValue(DataConstants.ALARM_CONDITION_REPEATS));
    assertEquals(String.valueOf(duration), metaData.getValue(DataConstants.ALARM_CONDITION_DURATION));
}
Also used : DurationAlarmConditionSpec(org.thingsboard.server.common.data.device.profile.DurationAlarmConditionSpec) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) Test(org.junit.Test)

Example 55 with TbMsgMetaData

use of org.thingsboard.server.common.msg.TbMsgMetaData in project thingsboard by thingsboard.

the class TbTransformMsgNodeTest method exceptionHandledCorrectly.

@Test
public void exceptionHandledCorrectly() throws TbNodeException, ScriptException {
    initWithScript();
    TbMsgMetaData metaData = new TbMsgMetaData();
    metaData.putValue("temp", "7");
    String rawJson = "{\"passed\": 5";
    RuleChainId ruleChainId = new RuleChainId(Uuids.timeBased());
    RuleNodeId ruleNodeId = new RuleNodeId(Uuids.timeBased());
    TbMsg msg = TbMsg.newMsg("USER", null, metaData, TbMsgDataType.JSON, rawJson, ruleChainId, ruleNodeId);
    when(scriptEngine.executeUpdateAsync(msg)).thenReturn(Futures.immediateFailedFuture(new IllegalStateException("error")));
    node.onMsg(ctx, msg);
    verifyError(msg, "error", IllegalStateException.class);
}
Also used : RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) TbMsgMetaData(org.thingsboard.server.common.msg.TbMsgMetaData) TbMsg(org.thingsboard.server.common.msg.TbMsg) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) Test(org.junit.Test)

Aggregations

TbMsgMetaData (org.thingsboard.server.common.msg.TbMsgMetaData)89 TbMsg (org.thingsboard.server.common.msg.TbMsg)56 Test (org.junit.Test)49 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)26 Device (org.thingsboard.server.common.data.Device)17 DeviceProfile (org.thingsboard.server.common.data.DeviceProfile)17 List (java.util.List)16 DeviceProfileData (org.thingsboard.server.common.data.device.profile.DeviceProfileData)16 DeviceId (org.thingsboard.server.common.data.id.DeviceId)15 EntityId (org.thingsboard.server.common.data.id.EntityId)15 AlarmCondition (org.thingsboard.server.common.data.device.profile.AlarmCondition)14 AlarmConditionFilter (org.thingsboard.server.common.data.device.profile.AlarmConditionFilter)14 AlarmConditionFilterKey (org.thingsboard.server.common.data.device.profile.AlarmConditionFilterKey)14 AlarmRule (org.thingsboard.server.common.data.device.profile.AlarmRule)14 DeviceProfileAlarm (org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm)14 AttributeKvEntry (org.thingsboard.server.common.data.kv.AttributeKvEntry)14 NumericFilterPredicate (org.thingsboard.server.common.data.query.NumericFilterPredicate)14 JsonNode (com.fasterxml.jackson.databind.JsonNode)13 DynamicValue (org.thingsboard.server.common.data.query.DynamicValue)13 AttributeKvCompositeKey (org.thingsboard.server.dao.model.sql.AttributeKvCompositeKey)13