Search in sources :

Example 6 with AlarmDataPageLink

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

the class BaseAlarmServiceTest method testFindCustomerAlarm.

@Test
public void testFindCustomerAlarm() throws ExecutionException, InterruptedException {
    Customer customer = new Customer();
    customer.setTitle("TestCustomer");
    customer.setTenantId(tenantId);
    customer = customerService.saveCustomer(customer);
    Device tenantDevice = new Device();
    tenantDevice.setName("TestTenantDevice");
    tenantDevice.setType("default");
    tenantDevice.setTenantId(tenantId);
    tenantDevice = deviceService.saveDevice(tenantDevice);
    Device customerDevice = new Device();
    customerDevice.setName("TestCustomerDevice");
    customerDevice.setType("default");
    customerDevice.setTenantId(tenantId);
    customerDevice.setCustomerId(customer.getId());
    customerDevice = deviceService.saveDevice(customerDevice);
    long ts = System.currentTimeMillis();
    Alarm tenantAlarm = Alarm.builder().tenantId(tenantId).originator(tenantDevice.getId()).type(TEST_ALARM).propagate(true).severity(AlarmSeverity.CRITICAL).status(AlarmStatus.ACTIVE_UNACK).startTs(ts).build();
    AlarmOperationResult result = alarmService.createOrUpdateAlarm(tenantAlarm);
    tenantAlarm = result.getAlarm();
    Alarm deviceAlarm = Alarm.builder().tenantId(tenantId).originator(customerDevice.getId()).type(TEST_ALARM).propagate(true).severity(AlarmSeverity.CRITICAL).status(AlarmStatus.ACTIVE_UNACK).startTs(ts).build();
    result = alarmService.createOrUpdateAlarm(deviceAlarm);
    deviceAlarm = result.getAlarm();
    AlarmDataPageLink pageLink = new AlarmDataPageLink();
    pageLink.setPage(0);
    pageLink.setPageSize(10);
    pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "createdTime")));
    pageLink.setStartTs(0L);
    pageLink.setEndTs(System.currentTimeMillis());
    pageLink.setSearchPropagatedAlarms(true);
    pageLink.setSeverityList(Arrays.asList(AlarmSeverity.CRITICAL, AlarmSeverity.WARNING));
    pageLink.setStatusList(Arrays.asList(AlarmSearchStatus.ACTIVE));
    PageData<AlarmData> tenantAlarms = alarmService.findAlarmDataByQueryForEntities(tenantId, toQuery(pageLink), Arrays.asList(tenantDevice.getId(), customerDevice.getId()));
    Assert.assertEquals(2, tenantAlarms.getData().size());
    PageData<AlarmData> customerAlarms = alarmService.findAlarmDataByQueryForEntities(tenantId, toQuery(pageLink), Collections.singletonList(customerDevice.getId()));
    Assert.assertEquals(1, customerAlarms.getData().size());
    Assert.assertEquals(deviceAlarm, customerAlarms.getData().get(0));
    PageData<AlarmInfo> alarms = alarmService.findAlarms(tenantId, AlarmQuery.builder().affectedEntityId(tenantDevice.getId()).status(AlarmStatus.ACTIVE_UNACK).pageLink(new TimePageLink(10, 0, "", new SortOrder("createdTime", SortOrder.Direction.DESC), 0L, System.currentTimeMillis())).build()).get();
    Assert.assertNotNull(alarms.getData());
    Assert.assertEquals(1, alarms.getData().size());
    Assert.assertEquals(tenantAlarm, alarms.getData().get(0));
}
Also used : Customer(org.thingsboard.server.common.data.Customer) Device(org.thingsboard.server.common.data.Device) SortOrder(org.thingsboard.server.common.data.page.SortOrder) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) EntityKey(org.thingsboard.server.common.data.query.EntityKey) Alarm(org.thingsboard.server.common.data.alarm.Alarm) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) AlarmInfo(org.thingsboard.server.common.data.alarm.AlarmInfo) TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) AlarmOperationResult(org.thingsboard.server.dao.alarm.AlarmOperationResult) AlarmDataPageLink(org.thingsboard.server.common.data.query.AlarmDataPageLink) AlarmData(org.thingsboard.server.common.data.query.AlarmData) Test(org.junit.Test)

Example 7 with AlarmDataPageLink

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

the class DefaultAlarmQueryRepository method findAlarmDataByQueryForEntities.

@Override
public PageData<AlarmData> findAlarmDataByQueryForEntities(TenantId tenantId, AlarmDataQuery query, Collection<EntityId> orderedEntityIds) {
    return transactionTemplate.execute(status -> {
        AlarmDataPageLink pageLink = query.getPageLink();
        QueryContext ctx = new QueryContext(new QuerySecurityContext(tenantId, null, EntityType.ALARM));
        ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList()));
        StringBuilder selectPart = new StringBuilder(FIELDS_SELECTION);
        StringBuilder fromPart = new StringBuilder(" from alarm a ");
        StringBuilder wherePart = new StringBuilder(" where ");
        StringBuilder sortPart = new StringBuilder(" order by ");
        StringBuilder joinPart = new StringBuilder();
        boolean addAnd = false;
        if (pageLink.isSearchPropagatedAlarms()) {
            selectPart.append(" ea.entity_id as entity_id ");
            fromPart.append(JOIN_ENTITY_ALARMS);
            wherePart.append(buildPermissionsQuery(tenantId, ctx));
            addAnd = true;
        } else {
            selectPart.append(" a.originator_id as entity_id ");
        }
        EntityDataSortOrder sortOrder = pageLink.getSortOrder();
        if (sortOrder != null && sortOrder.getKey().getType().equals(EntityKeyType.ALARM_FIELD)) {
            String sortOrderKey = sortOrder.getKey().getKey();
            sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)).append(" ").append(sortOrder.getDirection().name());
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.entity_id in (:entity_ids)");
            } else {
                addAndIfNeeded(wherePart, addAnd);
                addAnd = true;
                wherePart.append(" a.originator_id in (:entity_ids)");
            }
        } else {
            joinPart.append(" inner join (select * from (VALUES");
            int entityIdIdx = 0;
            int lastEntityIdIdx = orderedEntityIds.size() - 1;
            for (EntityId entityId : orderedEntityIds) {
                joinPart.append("(uuid('").append(entityId.getId().toString()).append("'), ").append(entityIdIdx).append(")");
                if (entityIdIdx != lastEntityIdIdx) {
                    joinPart.append(",");
                } else {
                    joinPart.append(")");
                }
                entityIdIdx++;
            }
            joinPart.append(" as e(id, priority)) e ");
            if (pageLink.isSearchPropagatedAlarms()) {
                joinPart.append("on ea.entity_id = e.id");
            } else {
                joinPart.append("on a.originator_id = e.id");
            }
            sortPart.append("e.priority");
        }
        long startTs;
        long endTs;
        if (pageLink.getTimeWindow() > 0) {
            endTs = System.currentTimeMillis();
            startTs = endTs - pageLink.getTimeWindow();
        } else {
            startTs = pageLink.getStartTs();
            endTs = pageLink.getEndTs();
        }
        if (startTs > 0) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addLongParameter("startTime", startTs);
            wherePart.append("a.created_time >= :startTime");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.created_time >= :startTime");
            }
        }
        if (endTs > 0) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addLongParameter("endTime", endTs);
            wherePart.append("a.created_time <= :endTime");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.created_time <= :endTime");
            }
        }
        if (pageLink.getTypeList() != null && !pageLink.getTypeList().isEmpty()) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addStringListParameter("alarmTypes", pageLink.getTypeList());
            wherePart.append("a.type in (:alarmTypes)");
            if (pageLink.isSearchPropagatedAlarms()) {
                wherePart.append(" and ea.alarm_type in (:alarmTypes)");
            }
        }
        if (pageLink.getSeverityList() != null && !pageLink.getSeverityList().isEmpty()) {
            addAndIfNeeded(wherePart, addAnd);
            addAnd = true;
            ctx.addStringListParameter("alarmSeverities", pageLink.getSeverityList().stream().map(AlarmSeverity::name).collect(Collectors.toList()));
            wherePart.append("a.severity in (:alarmSeverities)");
        }
        if (pageLink.getStatusList() != null && !pageLink.getStatusList().isEmpty()) {
            Set<AlarmStatus> statusSet = toStatusSet(pageLink.getStatusList());
            if (!statusSet.isEmpty()) {
                addAndIfNeeded(wherePart, addAnd);
                addAnd = true;
                ctx.addStringListParameter("alarmStatuses", statusSet.stream().map(AlarmStatus::name).collect(Collectors.toList()));
                wherePart.append(" a.status in (:alarmStatuses)");
            }
        }
        String textSearchQuery = buildTextSearchQuery(ctx, query.getAlarmFields(), pageLink.getTextSearch());
        String mainQuery;
        if (!textSearchQuery.isEmpty()) {
            mainQuery = selectPart.toString() + fromPart.toString() + wherePart.toString();
            mainQuery = String.format("select * from (%s) a %s WHERE %s", mainQuery, joinPart, textSearchQuery);
        } else {
            mainQuery = selectPart.toString() + fromPart.toString() + joinPart.toString() + wherePart.toString();
        }
        String countQuery = String.format("select count(*) from (%s) result", mainQuery);
        long queryTs = System.currentTimeMillis();
        int totalElements;
        try {
            totalElements = jdbcTemplate.queryForObject(countQuery, ctx, Integer.class);
        } finally {
            queryLog.logQuery(ctx, countQuery, System.currentTimeMillis() - queryTs);
        }
        if (totalElements == 0) {
            return AlarmDataAdapter.createAlarmData(pageLink, Collections.emptyList(), totalElements, orderedEntityIds);
        }
        String dataQuery = mainQuery + sortPart;
        int startIndex = pageLink.getPageSize() * pageLink.getPage();
        if (pageLink.getPageSize() > 0) {
            dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex);
        }
        queryTs = System.currentTimeMillis();
        List<Map<String, Object>> rows;
        try {
            rows = jdbcTemplate.queryForList(dataQuery, ctx);
        } finally {
            queryLog.logQuery(ctx, dataQuery, System.currentTimeMillis() - queryTs);
        }
        return AlarmDataAdapter.createAlarmData(pageLink, rows, totalElements, orderedEntityIds);
    });
}
Also used : AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) EntityId(org.thingsboard.server.common.data.id.EntityId) EntityDataSortOrder(org.thingsboard.server.common.data.query.EntityDataSortOrder) AlarmStatus(org.thingsboard.server.common.data.alarm.AlarmStatus) AlarmDataPageLink(org.thingsboard.server.common.data.query.AlarmDataPageLink) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

AlarmDataPageLink (org.thingsboard.server.common.data.query.AlarmDataPageLink)7 EntityDataSortOrder (org.thingsboard.server.common.data.query.EntityDataSortOrder)5 Test (org.junit.Test)4 Alarm (org.thingsboard.server.common.data.alarm.Alarm)4 AlarmData (org.thingsboard.server.common.data.query.AlarmData)4 EntityKey (org.thingsboard.server.common.data.query.EntityKey)4 AlarmOperationResult (org.thingsboard.server.dao.alarm.AlarmOperationResult)4 Customer (org.thingsboard.server.common.data.Customer)3 Device (org.thingsboard.server.common.data.Device)3 AlarmInfo (org.thingsboard.server.common.data.alarm.AlarmInfo)2 SortOrder (org.thingsboard.server.common.data.page.SortOrder)2 TimePageLink (org.thingsboard.server.common.data.page.TimePageLink)2 EntityRelation (org.thingsboard.server.common.data.relation.EntityRelation)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 AlarmSearchStatus (org.thingsboard.server.common.data.alarm.AlarmSearchStatus)1 AlarmSeverity (org.thingsboard.server.common.data.alarm.AlarmSeverity)1 AlarmStatus (org.thingsboard.server.common.data.alarm.AlarmStatus)1 Asset (org.thingsboard.server.common.data.asset.Asset)1 AssetId (org.thingsboard.server.common.data.id.AssetId)1