Search in sources :

Example 1 with EntityKey

use of org.thingsboard.server.common.data.query.EntityKey in project thingsboard by thingsboard.

the class DefaultTbEntityDataSubscriptionService method handleLatestCmd.

private void handleLatestCmd(TbEntityDataSubCtx ctx, LatestValueCmd latestCmd) {
    log.trace("[{}][{}] Going to process latest command: {}", ctx.getSessionId(), ctx.getCmdId(), latestCmd);
    // Fetch the latest values for telemetry keys (in case they are not copied from NoSQL to SQL DB in hybrid mode.
    if (!tsInSqlDB) {
        log.trace("[{}][{}] Going to fetch missing latest values: {}", ctx.getSessionId(), ctx.getCmdId(), latestCmd);
        List<String> allTsKeys = latestCmd.getKeys().stream().filter(key -> key.getType().equals(EntityKeyType.TIME_SERIES)).map(EntityKey::getKey).collect(Collectors.toList());
        Map<EntityData, ListenableFuture<Map<String, TsValue>>> missingTelemetryFutures = new HashMap<>();
        for (EntityData entityData : ctx.getData().getData()) {
            Map<EntityKeyType, Map<String, TsValue>> latestEntityData = entityData.getLatest();
            Map<String, TsValue> tsEntityData = latestEntityData.get(EntityKeyType.TIME_SERIES);
            Set<String> missingTsKeys = new LinkedHashSet<>(allTsKeys);
            if (tsEntityData != null) {
                missingTsKeys.removeAll(tsEntityData.keySet());
            } else {
                tsEntityData = new HashMap<>();
                latestEntityData.put(EntityKeyType.TIME_SERIES, tsEntityData);
            }
            ListenableFuture<List<TsKvEntry>> missingTsData = tsService.findLatest(ctx.getTenantId(), entityData.getEntityId(), missingTsKeys);
            missingTelemetryFutures.put(entityData, Futures.transform(missingTsData, this::toTsValue, MoreExecutors.directExecutor()));
        }
        Futures.addCallback(Futures.allAsList(missingTelemetryFutures.values()), new FutureCallback<List<Map<String, TsValue>>>() {

            @Override
            public void onSuccess(@Nullable List<Map<String, TsValue>> result) {
                missingTelemetryFutures.forEach((key, value) -> {
                    try {
                        key.getLatest().get(EntityKeyType.TIME_SERIES).putAll(value.get());
                    } catch (InterruptedException | ExecutionException e) {
                        log.warn("[{}][{}] Failed to lookup latest telemetry: {}:{}", ctx.getSessionId(), ctx.getCmdId(), key.getEntityId(), allTsKeys, e);
                    }
                });
                EntityDataUpdate update;
                if (!ctx.isInitialDataSent()) {
                    update = new EntityDataUpdate(ctx.getCmdId(), ctx.getData(), null, ctx.getMaxEntitiesPerDataSubscription());
                    ctx.setInitialDataSent(true);
                } else {
                    update = new EntityDataUpdate(ctx.getCmdId(), null, ctx.getData().getData(), ctx.getMaxEntitiesPerDataSubscription());
                }
                wsService.sendWsMsg(ctx.getSessionId(), update);
                ctx.createLatestValuesSubscriptions(latestCmd.getKeys());
            }

            @Override
            public void onFailure(Throwable t) {
                log.warn("[{}][{}] Failed to process websocket command: {}:{}", ctx.getSessionId(), ctx.getCmdId(), ctx.getQuery(), latestCmd, t);
                wsService.sendWsMsg(ctx.getSessionId(), new EntityDataUpdate(ctx.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR.getCode(), "Failed to process websocket command!"));
            }
        }, wsCallBackExecutor);
    } else {
        if (!ctx.isInitialDataSent()) {
            EntityDataUpdate update = new EntityDataUpdate(ctx.getCmdId(), ctx.getData(), null, ctx.getMaxEntitiesPerDataSubscription());
            wsService.sendWsMsg(ctx.getSessionId(), update);
            ctx.setInitialDataSent(true);
        }
        ctx.createLatestValuesSubscriptions(latestCmd.getKeys());
    }
}
Also used : TsValue(org.thingsboard.server.common.data.query.TsValue) LinkedHashSet(java.util.LinkedHashSet) Arrays(java.util.Arrays) ScheduledFuture(java.util.concurrent.ScheduledFuture) TsValue(org.thingsboard.server.common.data.query.TsValue) Autowired(org.springframework.beans.factory.annotation.Autowired) CloseStatus(org.springframework.web.socket.CloseStatus) TenantId(org.thingsboard.server.common.data.id.TenantId) PreDestroy(javax.annotation.PreDestroy) Map(java.util.Map) EntityService(org.thingsboard.server.dao.entity.EntityService) TbServiceInfoProvider(org.thingsboard.server.queue.discovery.TbServiceInfoProvider) ThreadFactory(java.util.concurrent.ThreadFactory) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) Set(java.util.Set) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) Collectors(java.util.stream.Collectors) GetTsCmd(org.thingsboard.server.service.telemetry.cmd.v2.GetTsCmd) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) EntityHistoryCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityHistoryCmd) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) UnsubscribeCmd(org.thingsboard.server.service.telemetry.cmd.v2.UnsubscribeCmd) PostConstruct(javax.annotation.PostConstruct) Lazy(org.springframework.context.annotation.Lazy) TelemetryWebSocketService(org.thingsboard.server.service.telemetry.TelemetryWebSocketService) CustomerId(org.thingsboard.server.common.data.id.CustomerId) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) AlarmDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.AlarmDataUpdate) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Getter(lombok.Getter) AlarmDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.AlarmDataCmd) LatestValueCmd(org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd) HashMap(java.util.HashMap) Scheduled(org.springframework.scheduling.annotation.Scheduled) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) LinkedHashMap(java.util.LinkedHashMap) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) Service(org.springframework.stereotype.Service) AlarmService(org.thingsboard.server.dao.alarm.AlarmService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TimeSeriesCmd(org.thingsboard.server.service.telemetry.cmd.v2.TimeSeriesCmd) EntityKey(org.thingsboard.server.common.data.query.EntityKey) Nullable(org.checkerframework.checker.nullness.qual.Nullable) LinkedHashSet(java.util.LinkedHashSet) ExecutorService(java.util.concurrent.ExecutorService) EntityData(org.thingsboard.server.common.data.query.EntityData) DbCallbackExecutorService(org.thingsboard.server.service.executors.DbCallbackExecutorService) TelemetryWebSocketSessionRef(org.thingsboard.server.service.telemetry.TelemetryWebSocketSessionRef) FutureCallback(com.google.common.util.concurrent.FutureCallback) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Futures(com.google.common.util.concurrent.Futures) AlarmDataQuery(org.thingsboard.server.common.data.query.AlarmDataQuery) SubscriptionErrorCode(org.thingsboard.server.service.telemetry.sub.SubscriptionErrorCode) PageData(org.thingsboard.server.common.data.page.PageData) EntityCountCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with EntityKey

use of org.thingsboard.server.common.data.query.EntityKey in project thingsboard by thingsboard.

the class TbAlarmDataSubCtx method doUpdate.

@Override
protected synchronized void doUpdate(Map<EntityId, EntityData> newDataMap) {
    resetInvocationCounter();
    entitiesMap.clear();
    tooManyEntities = data.hasNext();
    for (EntityData entityData : data.getData()) {
        entitiesMap.put(entityData.getEntityId(), entityData);
    }
    fetchAlarms();
    List<Integer> subIdsToCancel = new ArrayList<>();
    List<TbSubscription> subsToAdd = new ArrayList<>();
    Set<EntityId> currentSubs = new HashSet<>();
    subToEntityIdMap.forEach((subId, entityId) -> {
        if (!newDataMap.containsKey(entityId)) {
            subIdsToCancel.add(subId);
        } else {
            currentSubs.add(entityId);
        }
    });
    log.trace("[{}][{}] Subscriptions that are invalid: {}", sessionRef.getSessionId(), cmdId, subIdsToCancel);
    subIdsToCancel.forEach(subToEntityIdMap::remove);
    List<EntityData> newSubsList = newDataMap.entrySet().stream().filter(entry -> !currentSubs.contains(entry.getKey())).map(Map.Entry::getValue).collect(Collectors.toList());
    if (!newSubsList.isEmpty()) {
        List<EntityKey> keys = query.getLatestValues();
        if (keys != null && !keys.isEmpty()) {
            Map<EntityKeyType, List<EntityKey>> keysByType = getEntityKeyByTypeMap(keys);
            newSubsList.forEach(entity -> {
                log.trace("[{}][{}] Found new subscription for entity: {}", sessionRef.getSessionId(), cmdId, entity.getEntityId());
                subsToAdd.addAll(addSubscriptions(entity, keysByType, true, 0, 0));
            });
        }
        long startTs = System.currentTimeMillis() - query.getPageLink().getTimeWindow();
        newSubsList.forEach(entity -> createAlarmSubscriptionForEntity(query.getPageLink(), startTs, entity));
    }
    subIdsToCancel.forEach(subId -> localSubscriptionService.cancelSubscription(getSessionId(), subId));
    subsToAdd.forEach(localSubscriptionService::addSubscription);
}
Also used : EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) EntityData(org.thingsboard.server.common.data.query.EntityData) ArrayList(java.util.ArrayList) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityKey(org.thingsboard.server.common.data.query.EntityKey) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 3 with EntityKey

use of org.thingsboard.server.common.data.query.EntityKey in project thingsboard by thingsboard.

the class BaseEntityQueryControllerTest method testSimpleFindEntityDataByQuery.

@Test
public void testSimpleFindEntityDataByQuery() throws Exception {
    List<Device> devices = new ArrayList<>();
    for (int i = 0; i < 97; i++) {
        Device device = new Device();
        device.setName("Device" + i);
        device.setType("default");
        device.setLabel("testLabel" + (int) (Math.random() * 1000));
        devices.add(doPost("/api/device", device, Device.class));
        Thread.sleep(1);
    }
    DeviceTypeFilter filter = new DeviceTypeFilter();
    filter.setDeviceType("default");
    filter.setDeviceNameFilter("");
    EntityDataSortOrder sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime"), EntityDataSortOrder.Direction.ASC);
    EntityDataPageLink pageLink = new EntityDataPageLink(10, 0, null, sortOrder);
    List<EntityKey> entityFields = Collections.singletonList(new EntityKey(EntityKeyType.ENTITY_FIELD, "name"));
    EntityDataQuery query = new EntityDataQuery(filter, pageLink, entityFields, null, null);
    PageData<EntityData> data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
    });
    Assert.assertEquals(97, data.getTotalElements());
    Assert.assertEquals(10, data.getTotalPages());
    Assert.assertTrue(data.hasNext());
    Assert.assertEquals(10, data.getData().size());
    List<EntityData> loadedEntities = new ArrayList<>(data.getData());
    while (data.hasNext()) {
        query = query.next();
        data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
        });
        loadedEntities.addAll(data.getData());
    }
    Assert.assertEquals(97, loadedEntities.size());
    List<EntityId> loadedIds = loadedEntities.stream().map(EntityData::getEntityId).collect(Collectors.toList());
    List<EntityId> deviceIds = devices.stream().map(Device::getId).collect(Collectors.toList());
    Assert.assertEquals(deviceIds, loadedIds);
    List<String> loadedNames = loadedEntities.stream().map(entityData -> entityData.getLatest().get(EntityKeyType.ENTITY_FIELD).get("name").getValue()).collect(Collectors.toList());
    List<String> deviceNames = devices.stream().map(Device::getName).collect(Collectors.toList());
    Assert.assertEquals(deviceNames, loadedNames);
    sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, "name"), EntityDataSortOrder.Direction.DESC);
    pageLink = new EntityDataPageLink(10, 0, "device1", sortOrder);
    query = new EntityDataQuery(filter, pageLink, entityFields, null, null);
    data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
    });
    Assert.assertEquals(11, data.getTotalElements());
    Assert.assertEquals("Device19", data.getData().get(0).getLatest().get(EntityKeyType.ENTITY_FIELD).get("name").getValue());
    EntityTypeFilter filter2 = new EntityTypeFilter();
    filter2.setEntityType(EntityType.DEVICE);
    EntityDataSortOrder sortOrder2 = new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime"), EntityDataSortOrder.Direction.ASC);
    EntityDataPageLink pageLink2 = new EntityDataPageLink(10, 0, null, sortOrder2);
    List<EntityKey> entityFields2 = Collections.singletonList(new EntityKey(EntityKeyType.ENTITY_FIELD, "name"));
    EntityDataQuery query2 = new EntityDataQuery(filter2, pageLink2, entityFields2, null, null);
    PageData<EntityData> data2 = doPostWithTypedResponse("/api/entitiesQuery/find", query2, new TypeReference<PageData<EntityData>>() {
    });
    Assert.assertEquals(97, data2.getTotalElements());
    Assert.assertEquals(10, data2.getTotalPages());
    Assert.assertTrue(data2.hasNext());
    Assert.assertEquals(10, data2.getData().size());
}
Also used : Device(org.thingsboard.server.common.data.Device) Tenant(org.thingsboard.server.common.data.Tenant) EntityTypeFilter(org.thingsboard.server.common.data.query.EntityTypeFilter) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) EntityCountQuery(org.thingsboard.server.common.data.query.EntityCountQuery) KeyFilter(org.thingsboard.server.common.data.query.KeyFilter) ArrayList(java.util.ArrayList) User(org.thingsboard.server.common.data.User) EntityListFilter(org.thingsboard.server.common.data.query.EntityListFilter) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) After(org.junit.After) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityType(org.thingsboard.server.common.data.EntityType) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) TypeReference(com.fasterxml.jackson.core.type.TypeReference) EntityKey(org.thingsboard.server.common.data.query.EntityKey) Before(org.junit.Before) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) DeviceId(org.thingsboard.server.common.data.id.DeviceId) DataConstants(org.thingsboard.server.common.data.DataConstants) EntityData(org.thingsboard.server.common.data.query.EntityData) FilterPredicateValue(org.thingsboard.server.common.data.query.FilterPredicateValue) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) Test(org.junit.Test) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) Authority(org.thingsboard.server.common.data.security.Authority) Collectors(java.util.stream.Collectors) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) List(java.util.List) PageData(org.thingsboard.server.common.data.page.PageData) Assert(org.junit.Assert) Collections(java.util.Collections) Device(org.thingsboard.server.common.data.Device) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) ArrayList(java.util.ArrayList) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityTypeFilter(org.thingsboard.server.common.data.query.EntityTypeFilter) EntityKey(org.thingsboard.server.common.data.query.EntityKey) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) PageData(org.thingsboard.server.common.data.page.PageData) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Test(org.junit.Test)

Example 4 with EntityKey

use of org.thingsboard.server.common.data.query.EntityKey in project thingsboard by thingsboard.

the class BaseEntityQueryControllerTest method testFindEntityDataByQueryWithAttributes.

@Test
public void testFindEntityDataByQueryWithAttributes() throws Exception {
    List<Device> devices = new ArrayList<>();
    List<Long> temperatures = new ArrayList<>();
    List<Long> highTemperatures = new ArrayList<>();
    for (int i = 0; i < 67; i++) {
        Device device = new Device();
        String name = "Device" + i;
        device.setName(name);
        device.setType("default");
        device.setLabel("testLabel" + (int) (Math.random() * 1000));
        devices.add(doPost("/api/device?accessToken=" + name, device, Device.class));
        Thread.sleep(1);
        long temperature = (long) (Math.random() * 100);
        temperatures.add(temperature);
        if (temperature > 45) {
            highTemperatures.add(temperature);
        }
    }
    for (int i = 0; i < devices.size(); i++) {
        Device device = devices.get(i);
        String payload = "{\"temperature\":" + temperatures.get(i) + "}";
        doPost("/api/plugins/telemetry/" + device.getId() + "/" + DataConstants.SHARED_SCOPE, payload, String.class, status().isOk());
    }
    Thread.sleep(1000);
    DeviceTypeFilter filter = new DeviceTypeFilter();
    filter.setDeviceType("default");
    filter.setDeviceNameFilter("");
    EntityDataSortOrder sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime"), EntityDataSortOrder.Direction.ASC);
    EntityDataPageLink pageLink = new EntityDataPageLink(10, 0, null, sortOrder);
    List<EntityKey> entityFields = Collections.singletonList(new EntityKey(EntityKeyType.ENTITY_FIELD, "name"));
    List<EntityKey> latestValues = Collections.singletonList(new EntityKey(EntityKeyType.ATTRIBUTE, "temperature"));
    EntityDataQuery query = new EntityDataQuery(filter, pageLink, entityFields, latestValues, null);
    PageData<EntityData> data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
    });
    List<EntityData> loadedEntities = new ArrayList<>(data.getData());
    while (data.hasNext()) {
        query = query.next();
        data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
        });
        loadedEntities.addAll(data.getData());
    }
    Assert.assertEquals(67, loadedEntities.size());
    List<String> loadedTemperatures = loadedEntities.stream().map(entityData -> entityData.getLatest().get(EntityKeyType.ATTRIBUTE).get("temperature").getValue()).collect(Collectors.toList());
    List<String> deviceTemperatures = temperatures.stream().map(aLong -> Long.toString(aLong)).collect(Collectors.toList());
    Assert.assertEquals(deviceTemperatures, loadedTemperatures);
    pageLink = new EntityDataPageLink(10, 0, null, sortOrder);
    KeyFilter highTemperatureFilter = new KeyFilter();
    highTemperatureFilter.setKey(new EntityKey(EntityKeyType.ATTRIBUTE, "temperature"));
    NumericFilterPredicate predicate = new NumericFilterPredicate();
    predicate.setValue(FilterPredicateValue.fromDouble(45));
    predicate.setOperation(NumericFilterPredicate.NumericOperation.GREATER);
    highTemperatureFilter.setPredicate(predicate);
    List<KeyFilter> keyFilters = Collections.singletonList(highTemperatureFilter);
    query = new EntityDataQuery(filter, pageLink, entityFields, latestValues, keyFilters);
    data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
    });
    loadedEntities = new ArrayList<>(data.getData());
    while (data.hasNext()) {
        query = query.next();
        data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference<PageData<EntityData>>() {
        });
        loadedEntities.addAll(data.getData());
    }
    Assert.assertEquals(highTemperatures.size(), loadedEntities.size());
    List<String> loadedHighTemperatures = loadedEntities.stream().map(entityData -> entityData.getLatest().get(EntityKeyType.ATTRIBUTE).get("temperature").getValue()).collect(Collectors.toList());
    List<String> deviceHighTemperatures = highTemperatures.stream().map(aLong -> Long.toString(aLong)).collect(Collectors.toList());
    Assert.assertEquals(deviceHighTemperatures, loadedHighTemperatures);
}
Also used : Device(org.thingsboard.server.common.data.Device) Tenant(org.thingsboard.server.common.data.Tenant) EntityTypeFilter(org.thingsboard.server.common.data.query.EntityTypeFilter) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) EntityCountQuery(org.thingsboard.server.common.data.query.EntityCountQuery) KeyFilter(org.thingsboard.server.common.data.query.KeyFilter) ArrayList(java.util.ArrayList) User(org.thingsboard.server.common.data.User) EntityListFilter(org.thingsboard.server.common.data.query.EntityListFilter) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) After(org.junit.After) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityType(org.thingsboard.server.common.data.EntityType) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) TypeReference(com.fasterxml.jackson.core.type.TypeReference) EntityKey(org.thingsboard.server.common.data.query.EntityKey) Before(org.junit.Before) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) DeviceId(org.thingsboard.server.common.data.id.DeviceId) DataConstants(org.thingsboard.server.common.data.DataConstants) EntityData(org.thingsboard.server.common.data.query.EntityData) FilterPredicateValue(org.thingsboard.server.common.data.query.FilterPredicateValue) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) Test(org.junit.Test) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) Authority(org.thingsboard.server.common.data.security.Authority) Collectors(java.util.stream.Collectors) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) List(java.util.List) PageData(org.thingsboard.server.common.data.page.PageData) Assert(org.junit.Assert) Collections(java.util.Collections) DeviceTypeFilter(org.thingsboard.server.common.data.query.DeviceTypeFilter) ArrayList(java.util.ArrayList) EntityKey(org.thingsboard.server.common.data.query.EntityKey) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) TypeReference(com.fasterxml.jackson.core.type.TypeReference) NumericFilterPredicate(org.thingsboard.server.common.data.query.NumericFilterPredicate) Device(org.thingsboard.server.common.data.Device) EntityDataPageLink(org.thingsboard.server.common.data.query.EntityDataPageLink) EntityData(org.thingsboard.server.common.data.query.EntityData) EntityDataQuery(org.thingsboard.server.common.data.query.EntityDataQuery) PageData(org.thingsboard.server.common.data.page.PageData) KeyFilter(org.thingsboard.server.common.data.query.KeyFilter) Test(org.junit.Test)

Example 5 with EntityKey

use of org.thingsboard.server.common.data.query.EntityKey in project thingsboard by thingsboard.

the class DeviceState method processAttributesDeleteNotification.

private boolean processAttributesDeleteNotification(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException {
    boolean stateChanged = false;
    List<String> keys = new ArrayList<>();
    new JsonParser().parse(msg.getData()).getAsJsonObject().get("attributes").getAsJsonArray().forEach(e -> keys.add(e.getAsString()));
    String scope = msg.getMetaData().getValue(DataConstants.SCOPE);
    if (StringUtils.isEmpty(scope)) {
        scope = DataConstants.CLIENT_SCOPE;
    }
    if (!keys.isEmpty()) {
        EntityKeyType keyType = getKeyTypeFromScope(scope);
        keys.forEach(key -> latestValues.removeValue(new EntityKey(keyType, key)));
        for (DeviceProfileAlarm alarm : deviceProfile.getAlarmSettings()) {
            AlarmState alarmState = alarmStates.computeIfAbsent(alarm.getId(), a -> new AlarmState(this.deviceProfile, deviceId, alarm, getOrInitPersistedAlarmState(alarm), dynamicPredicateValueCtx));
            stateChanged |= alarmState.process(ctx, msg, latestValues, null);
        }
    }
    ctx.tellSuccess(msg);
    return stateChanged;
}
Also used : EntityKey(org.thingsboard.server.common.data.query.EntityKey) EntityKeyType(org.thingsboard.server.common.data.query.EntityKeyType) PersistedAlarmState(org.thingsboard.rule.engine.profile.state.PersistedAlarmState) DeviceProfileAlarm(org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm) ArrayList(java.util.ArrayList) JsonParser(com.google.gson.JsonParser)

Aggregations

EntityKey (org.thingsboard.server.common.data.query.EntityKey)36 EntityDataQuery (org.thingsboard.server.common.data.query.EntityDataQuery)24 EntityData (org.thingsboard.server.common.data.query.EntityData)23 Test (org.junit.Test)22 Device (org.thingsboard.server.common.data.Device)22 EntityDataPageLink (org.thingsboard.server.common.data.query.EntityDataPageLink)22 ArrayList (java.util.ArrayList)21 EntityDataSortOrder (org.thingsboard.server.common.data.query.EntityDataSortOrder)21 List (java.util.List)19 DeviceTypeFilter (org.thingsboard.server.common.data.query.DeviceTypeFilter)19 EntityKeyType (org.thingsboard.server.common.data.query.EntityKeyType)19 KeyFilter (org.thingsboard.server.common.data.query.KeyFilter)19 HashMap (java.util.HashMap)16 Map (java.util.Map)16 Collectors (java.util.stream.Collectors)16 EntityId (org.thingsboard.server.common.data.id.EntityId)15 LongDataEntry (org.thingsboard.server.common.data.kv.LongDataEntry)15 PageData (org.thingsboard.server.common.data.page.PageData)15 NumericFilterPredicate (org.thingsboard.server.common.data.query.NumericFilterPredicate)15 EntityType (org.thingsboard.server.common.data.EntityType)14