Search in sources :

Example 1 with EntityViewId

use of org.thingsboard.server.common.data.id.EntityViewId in project thingsboard by thingsboard.

the class DefaultDataUpdateService method updateEntityViewLatestTelemetry.

private ListenableFuture<List<Void>> updateEntityViewLatestTelemetry(EntityView entityView) {
    EntityViewId entityId = entityView.getId();
    List<String> keys = entityView.getKeys() != null && entityView.getKeys().getTimeseries() != null ? entityView.getKeys().getTimeseries() : Collections.emptyList();
    long startTs = entityView.getStartTimeMs();
    long endTs = entityView.getEndTimeMs() == 0 ? Long.MAX_VALUE : entityView.getEndTimeMs();
    ListenableFuture<List<String>> keysFuture;
    if (keys.isEmpty()) {
        keysFuture = Futures.transform(tsService.findAllLatest(TenantId.SYS_TENANT_ID, entityView.getEntityId()), latest -> latest.stream().map(TsKvEntry::getKey).collect(Collectors.toList()), MoreExecutors.directExecutor());
    } else {
        keysFuture = Futures.immediateFuture(keys);
    }
    ListenableFuture<List<TsKvEntry>> latestFuture = Futures.transformAsync(keysFuture, fetchKeys -> {
        List<ReadTsKvQuery> queries = fetchKeys.stream().filter(key -> !isBlank(key)).map(key -> new BaseReadTsKvQuery(key, startTs, endTs, 1, "DESC")).collect(Collectors.toList());
        if (!queries.isEmpty()) {
            return tsService.findAll(TenantId.SYS_TENANT_ID, entityView.getEntityId(), queries);
        } else {
            return Futures.immediateFuture(null);
        }
    }, MoreExecutors.directExecutor());
    return Futures.transformAsync(latestFuture, latestValues -> {
        if (latestValues != null && !latestValues.isEmpty()) {
            ListenableFuture<List<Void>> saveFuture = tsService.saveLatest(TenantId.SYS_TENANT_ID, entityId, latestValues);
            return saveFuture;
        }
        return Futures.immediateFuture(null);
    }, MoreExecutors.directExecutor());
}
Also used : TimePageLink(org.thingsboard.server.common.data.page.TimePageLink) RuleChainMetaData(org.thingsboard.server.common.data.rule.RuleChainMetaData) Autowired(org.springframework.beans.factory.annotation.Autowired) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) TenantId(org.thingsboard.server.common.data.id.TenantId) EntityRelation(org.thingsboard.server.common.data.relation.EntityRelation) TenantService(org.thingsboard.server.dao.tenant.TenantService) TbRuleChainInputNodeConfiguration(org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration) OAuth2Service(org.thingsboard.server.dao.oauth2.OAuth2Service) EntityService(org.thingsboard.server.dao.entity.EntityService) JsonNode(com.fasterxml.jackson.databind.JsonNode) DeviceProfileRepository(org.thingsboard.server.dao.sql.device.DeviceProfileRepository) EntityViewService(org.thingsboard.server.dao.entityview.EntityViewService) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) PageLink(org.thingsboard.server.common.data.page.PageLink) RelationEntity(org.thingsboard.server.dao.model.sql.RelationEntity) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) Collectors(java.util.stream.Collectors) Alarm(org.thingsboard.server.common.data.alarm.Alarm) AlarmDao(org.thingsboard.server.dao.alarm.AlarmDao) EntityView(org.thingsboard.server.common.data.EntityView) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) TbDeviceProfileNodeConfiguration(org.thingsboard.rule.engine.profile.TbDeviceProfileNodeConfiguration) List(java.util.List) DeviceProfileEntity(org.thingsboard.server.dao.model.sql.DeviceProfileEntity) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) TbDeviceProfileNode(org.thingsboard.rule.engine.profile.TbDeviceProfileNode) AlarmSeverity(org.thingsboard.server.common.data.alarm.AlarmSeverity) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) DynamicValue(org.thingsboard.server.common.data.query.DynamicValue) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) JacksonUtil(org.thingsboard.common.util.JacksonUtil) TbRuleChainInputNode(org.thingsboard.rule.engine.flow.TbRuleChainInputNode) Tenant(org.thingsboard.server.common.data.Tenant) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) RuleChainService(org.thingsboard.server.dao.rule.RuleChainService) ArrayList(java.util.ArrayList) RelationService(org.thingsboard.server.dao.relation.RelationService) Service(org.springframework.stereotype.Service) AlarmService(org.thingsboard.server.dao.alarm.AlarmService) AlarmQuery(org.thingsboard.server.common.data.alarm.AlarmQuery) InstallScripts(org.thingsboard.server.service.install.InstallScripts) AlarmInfo(org.thingsboard.server.common.data.alarm.AlarmInfo) FilterPredicateValue(org.thingsboard.server.common.data.query.FilterPredicateValue) RuleChainType(org.thingsboard.server.common.data.rule.RuleChainType) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) Profile(org.springframework.context.annotation.Profile) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Futures(com.google.common.util.concurrent.Futures) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) PageData(org.thingsboard.server.common.data.page.PageData) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) DaoUtil(org.thingsboard.server.dao.DaoUtil) RelationTypeGroup(org.thingsboard.server.common.data.relation.RelationTypeGroup) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) Collections(java.util.Collections) EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) List(java.util.List) ArrayList(java.util.ArrayList)

Example 2 with EntityViewId

use of org.thingsboard.server.common.data.id.EntityViewId in project thingsboard by thingsboard.

the class AlarmMsgConstructor method constructAlarmUpdatedMsg.

public AlarmUpdateMsg constructAlarmUpdatedMsg(TenantId tenantId, UpdateMsgType msgType, Alarm alarm) {
    String entityName = null;
    switch(alarm.getOriginator().getEntityType()) {
        case DEVICE:
            entityName = deviceService.findDeviceById(tenantId, new DeviceId(alarm.getOriginator().getId())).getName();
            break;
        case ASSET:
            entityName = assetService.findAssetById(tenantId, new AssetId(alarm.getOriginator().getId())).getName();
            break;
        case ENTITY_VIEW:
            entityName = entityViewService.findEntityViewById(tenantId, new EntityViewId(alarm.getOriginator().getId())).getName();
            break;
    }
    AlarmUpdateMsg.Builder builder = AlarmUpdateMsg.newBuilder().setMsgType(msgType).setIdMSB(alarm.getId().getId().getMostSignificantBits()).setIdLSB(alarm.getId().getId().getLeastSignificantBits()).setName(alarm.getName()).setType(alarm.getType()).setOriginatorName(entityName).setOriginatorType(alarm.getOriginator().getEntityType().name()).setSeverity(alarm.getSeverity().name()).setStatus(alarm.getStatus().name()).setStartTs(alarm.getStartTs()).setEndTs(alarm.getEndTs()).setAckTs(alarm.getAckTs()).setClearTs(alarm.getClearTs()).setDetails(JacksonUtil.toString(alarm.getDetails())).setPropagate(alarm.isPropagate()).setPropagateToOwner(alarm.isPropagateToOwner()).setPropagateToTenant(alarm.isPropagateToTenant());
    return builder.build();
}
Also used : AlarmUpdateMsg(org.thingsboard.server.gen.edge.v1.AlarmUpdateMsg) EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) DeviceId(org.thingsboard.server.common.data.id.DeviceId) AssetId(org.thingsboard.server.common.data.id.AssetId)

Example 3 with EntityViewId

use of org.thingsboard.server.common.data.id.EntityViewId in project thingsboard by thingsboard.

the class EntityViewController method assignEntityViewToPublicCustomer.

@ApiOperation(value = "Make entity view publicly available (assignEntityViewToPublicCustomer)", notes = "Entity View will be available for non-authorized (not logged-in) users. " + "This is useful to create dashboards that you plan to share/embed on a publicly available website. " + "However, users that are logged-in and belong to different tenant will not be able to access the entity view." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/public/entityView/{entityViewId}", method = RequestMethod.POST)
@ResponseBody
public EntityView assignEntityViewToPublicCustomer(@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
    checkParameter(ENTITY_VIEW_ID, strEntityViewId);
    try {
        EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
        EntityView entityView = checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER);
        Customer publicCustomer = customerService.findOrCreatePublicCustomer(entityView.getTenantId());
        EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(getCurrentUser().getTenantId(), entityViewId, publicCustomer.getId()));
        logEntityAction(entityViewId, savedEntityView, savedEntityView.getCustomerId(), ActionType.ASSIGNED_TO_CUSTOMER, null, strEntityViewId, publicCustomer.getId().toString(), publicCustomer.getName());
        return savedEntityView;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.ENTITY_VIEW), null, null, ActionType.ASSIGNED_TO_CUSTOMER, e, strEntityViewId);
        throw handleException(e);
    }
}
Also used : EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) EntityView(org.thingsboard.server.common.data.EntityView) Customer(org.thingsboard.server.common.data.Customer) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ExecutionException(java.util.concurrent.ExecutionException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with EntityViewId

use of org.thingsboard.server.common.data.id.EntityViewId in project thingsboard by thingsboard.

the class EntityViewController method unassignEntityViewFromCustomer.

@ApiOperation(value = "Unassign Entity View from customer (unassignEntityViewFromCustomer)", notes = "Clears assignment of the Entity View to customer. Customer will not be able to query Entity View afterwards." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/customer/entityView/{entityViewId}", method = RequestMethod.DELETE)
@ResponseBody
public EntityView unassignEntityViewFromCustomer(@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
    checkParameter(ENTITY_VIEW_ID, strEntityViewId);
    try {
        EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
        EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER);
        if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
            throw new IncorrectParameterException("Entity View isn't assigned to any customer!");
        }
        Customer customer = checkCustomerId(entityView.getCustomerId(), Operation.READ);
        EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId));
        logEntityAction(entityViewId, entityView, entityView.getCustomerId(), ActionType.UNASSIGNED_FROM_CUSTOMER, null, strEntityViewId, customer.getId().toString(), customer.getName());
        sendEntityAssignToCustomerNotificationMsg(savedEntityView.getTenantId(), savedEntityView.getId(), customer.getId(), EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER);
        return savedEntityView;
    } catch (Exception e) {
        logEntityAction(emptyId(EntityType.ENTITY_VIEW), null, null, ActionType.UNASSIGNED_FROM_CUSTOMER, e, strEntityViewId);
        throw handleException(e);
    }
}
Also used : EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) EntityView(org.thingsboard.server.common.data.EntityView) Customer(org.thingsboard.server.common.data.Customer) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) ExecutionException(java.util.concurrent.ExecutionException) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with EntityViewId

use of org.thingsboard.server.common.data.id.EntityViewId in project thingsboard by thingsboard.

the class EntityViewController method copyAttributesFromEntityToEntityView.

private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, SecurityUser user) throws ThingsboardException {
    EntityViewId entityId = entityView.getId();
    if (keys != null && !keys.isEmpty()) {
        ListenableFuture<List<AttributeKvEntry>> getAttrFuture = attributesService.find(getTenantId(), entityView.getEntityId(), scope, keys);
        return Futures.transform(getAttrFuture, attributeKvEntries -> {
            List<AttributeKvEntry> attributes;
            if (attributeKvEntries != null && !attributeKvEntries.isEmpty()) {
                attributes = attributeKvEntries.stream().filter(attributeKvEntry -> {
                    long startTime = entityView.getStartTimeMs();
                    long endTime = entityView.getEndTimeMs();
                    long lastUpdateTs = attributeKvEntry.getLastUpdateTs();
                    return startTime == 0 && endTime == 0 || (endTime == 0 && startTime < lastUpdateTs) || (startTime == 0 && endTime > lastUpdateTs) ? true : startTime < lastUpdateTs && endTime > lastUpdateTs;
                }).collect(Collectors.toList());
                tsSubService.saveAndNotify(entityView.getTenantId(), entityId, scope, attributes, new FutureCallback<Void>() {

                    @Override
                    public void onSuccess(@Nullable Void tmp) {
                        try {
                            logAttributesUpdated(user, entityId, scope, attributes, null);
                        } catch (ThingsboardException e) {
                            log.error("Failed to log attribute updates", e);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        try {
                            logAttributesUpdated(user, entityId, scope, attributes, t);
                        } catch (ThingsboardException e) {
                            log.error("Failed to log attribute updates", e);
                        }
                    }
                });
            }
            return null;
        }, MoreExecutors.directExecutor());
    } else {
        return Futures.immediateFuture(null);
    }
}
Also used : EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

EntityViewId (org.thingsboard.server.common.data.id.EntityViewId)19 EntityView (org.thingsboard.server.common.data.EntityView)14 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)11 IncorrectParameterException (org.thingsboard.server.dao.exception.IncorrectParameterException)10 ExecutionException (java.util.concurrent.ExecutionException)8 ApiOperation (io.swagger.annotations.ApiOperation)7 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)6 CustomerId (org.thingsboard.server.common.data.id.CustomerId)6 EdgeId (org.thingsboard.server.common.data.id.EdgeId)6 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)5 ArrayList (java.util.ArrayList)5 List (java.util.List)5 Customer (org.thingsboard.server.common.data.Customer)5 Futures (com.google.common.util.concurrent.Futures)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 Edge (org.thingsboard.server.common.data.edge.Edge)4 AssetId (org.thingsboard.server.common.data.id.AssetId)4 DeviceId (org.thingsboard.server.common.data.id.DeviceId)4