Search in sources :

Example 86 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project thingsboard by thingsboard.

the class TelemetryController method getTsKvListCallback.

private FutureCallback<List<TsKvEntry>> getTsKvListCallback(final DeferredResult<ResponseEntity> response, Boolean useStrictDataTypes) {
    return new FutureCallback<>() {

        @Override
        public void onSuccess(List<TsKvEntry> data) {
            Map<String, List<TsData>> result = new LinkedHashMap<>();
            for (TsKvEntry entry : data) {
                Object value = useStrictDataTypes ? getKvValue(entry) : entry.getValueAsString();
                result.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).add(new TsData(entry.getTs(), value));
            }
            response.setResult(new ResponseEntity<>(result, HttpStatus.OK));
        }

        @Override
        public void onFailure(Throwable e) {
            log.error("Failed to fetch historical data", e);
            AccessValidator.handleError(e, response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    };
}
Also used : TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH(org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) RequestParam(org.springframework.web.bind.annotation.RequestParam) Arrays(java.util.Arrays) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) BaseDeleteTsKvQuery(org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery) TsData(org.thingsboard.server.service.telemetry.TsData) ENTITY_TYPE_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ENTITY_TYPE_PARAM_DESCRIPTION) SORT_ORDER_ALLOWABLE_VALUES(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) STRICT_DATA_TYPES_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.STRICT_DATA_TYPES_DESCRIPTION) TenantId(org.thingsboard.server.common.data.id.TenantId) Map(java.util.Map) SAVE_ENTITY_TIMESERIES_STATUS_UNAUTHORIZED(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_UNAUTHORIZED) SAVE_ATTIRIBUTES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTIRIBUTES_STATUS_OK) JsonConverter(org.thingsboard.server.common.transport.adaptor.JsonConverter) INVALID_ENTITY_ID_OR_ENTITY_TYPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.INVALID_ENTITY_ID_OR_ENTITY_TYPE_DESCRIPTION) JsonNode(com.fasterxml.jackson.databind.JsonNode) ATTRIBUTES_KEYS_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_KEYS_DESCRIPTION) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) Set(java.util.Set) RestController(org.springframework.web.bind.annotation.RestController) DeleteTsKvQuery(org.thingsboard.server.common.data.kv.DeleteTsKvQuery) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) Operation(org.thingsboard.server.service.security.permission.Operation) BooleanDataEntry(org.thingsboard.server.common.data.kv.BooleanDataEntry) DeferredResult(org.springframework.web.context.request.async.DeferredResult) TELEMETRY_KEYS_BASE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_KEYS_BASE_DESCRIPTION) JsonParser(com.google.gson.JsonParser) DEVICE_ID(org.thingsboard.server.controller.ControllerConstants.DEVICE_ID) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) LinkedHashMap(java.util.LinkedHashMap) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) DEVICE_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.DEVICE_ID_PARAM_DESCRIPTION) DataType(org.thingsboard.server.common.data.kv.DataType) SAVE_ATTRIBUTES_REQUEST_PAYLOAD(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTRIBUTES_REQUEST_PAYLOAD) Nullable(javax.annotation.Nullable) DataConstants(org.thingsboard.server.common.data.DataConstants) ATTRIBUTES_JSON_REQUEST_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_JSON_REQUEST_DESCRIPTION) ConstraintValidator(org.thingsboard.server.dao.service.ConstraintValidator) ATTRIBUTES_SCOPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_SCOPE_DESCRIPTION) BaseAttributeKvEntry(org.thingsboard.server.common.data.kv.BaseAttributeKvEntry) FutureCallback(com.google.common.util.concurrent.FutureCallback) HttpStatus(org.springframework.http.HttpStatus) Futures(com.google.common.util.concurrent.Futures) SAVE_ENTITY_ATTRIBUTES_STATUS_UNAUTHORIZED(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_UNAUTHORIZED) ApiResponse(io.swagger.annotations.ApiResponse) MARKDOWN_CODE_BLOCK_START(org.thingsboard.server.controller.ControllerConstants.MARKDOWN_CODE_BLOCK_START) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) ENTITY_ID_PARAM_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.ENTITY_ID_PARAM_DESCRIPTION) StringDataEntry(org.thingsboard.server.common.data.kv.StringDataEntry) PathVariable(org.springframework.web.bind.annotation.PathVariable) SAVE_ENTITY_ATTRIBUTES_STATUS_INTERNAL_SERVER_ERROR(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_INTERNAL_SERVER_ERROR) SAVE_ENTITY_TIMESERIES_STATUS_INTERNAL_SERVER_ERROR(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_INTERNAL_SERVER_ERROR) DefaultTenantProfileConfiguration(org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) ApiOperation(io.swagger.annotations.ApiOperation) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PreDestroy(javax.annotation.PreDestroy) INVALID_STRUCTURE_OF_THE_REQUEST(org.thingsboard.server.controller.ControllerConstants.INVALID_STRUCTURE_OF_THE_REQUEST) EntityType(org.thingsboard.server.common.data.EntityType) TS_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.TS_STRICT_DATA_EXAMPLE) DeviceAttributesEventNotificationMsg(org.thingsboard.rule.engine.api.msg.DeviceAttributesEventNotificationMsg) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Function(com.google.common.base.Function) MARKDOWN_CODE_BLOCK_END(org.thingsboard.server.controller.ControllerConstants.MARKDOWN_CODE_BLOCK_END) AttributeData(org.thingsboard.server.service.telemetry.AttributeData) MediaType(org.springframework.http.MediaType) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) UncheckedApiException(org.thingsboard.server.service.telemetry.exception.UncheckedApiException) LATEST_TS_NON_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.LATEST_TS_NON_STRICT_DATA_EXAMPLE) Collectors(java.util.stream.Collectors) TELEMETRY_KEYS_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_KEYS_DESCRIPTION) TELEMETRY_JSON_REQUEST_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_JSON_REQUEST_DESCRIPTION) List(java.util.List) KvEntry(org.thingsboard.server.common.data.kv.KvEntry) PostConstruct(javax.annotation.PostConstruct) TELEMETRY_SCOPE_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.TELEMETRY_SCOPE_DESCRIPTION) SAVE_ATTIRIBUTES_STATUS_BAD_REQUEST(org.thingsboard.server.controller.ControllerConstants.SAVE_ATTIRIBUTES_STATUS_BAD_REQUEST) SORT_ORDER_DESCRIPTION(org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION) LongDataEntry(org.thingsboard.server.common.data.kv.LongDataEntry) JsonParseException(com.google.gson.JsonParseException) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ATTRIBUTE_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTE_DATA_EXAMPLE) SAVE_TIMESERIES_REQUEST_PAYLOAD(org.thingsboard.server.controller.ControllerConstants.SAVE_TIMESERIES_REQUEST_PAYLOAD) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) SAVE_ENTITY_ATTRIBUTES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_ATTRIBUTES_STATUS_OK) JacksonUtil(org.thingsboard.common.util.JacksonUtil) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiResponses(io.swagger.annotations.ApiResponses) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet) TenantProfile(org.thingsboard.server.common.data.TenantProfile) ActionType(org.thingsboard.server.common.data.audit.ActionType) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) EntityId(org.thingsboard.server.common.data.id.EntityId) UUIDBased(org.thingsboard.server.common.data.id.UUIDBased) DoubleDataEntry(org.thingsboard.server.common.data.kv.DoubleDataEntry) ExecutorService(java.util.concurrent.ExecutorService) AttributeKey(org.thingsboard.server.common.data.kv.AttributeKey) ATTRIBUTES_SCOPE_ALLOWED_VALUES(org.thingsboard.server.controller.ControllerConstants.ATTRIBUTES_SCOPE_ALLOWED_VALUES) AccessValidator(org.thingsboard.server.service.security.AccessValidator) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) Aggregation(org.thingsboard.server.common.data.kv.Aggregation) LATEST_TS_STRICT_DATA_EXAMPLE(org.thingsboard.server.controller.ControllerConstants.LATEST_TS_STRICT_DATA_EXAMPLE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) SAVE_ENTITY_TIMESERIES_STATUS_OK(org.thingsboard.server.controller.ControllerConstants.SAVE_ENTITY_TIMESERIES_STATUS_OK) InvalidParametersException(org.thingsboard.server.service.telemetry.exception.InvalidParametersException) TimeUnit(java.util.concurrent.TimeUnit) JsonDataEntry(org.thingsboard.server.common.data.kv.JsonDataEntry) ResponseEntity(org.springframework.http.ResponseEntity) ENTITY_ATTRIBUTE_SCOPES(org.thingsboard.server.controller.ControllerConstants.ENTITY_ATTRIBUTE_SCOPES) StringUtils(org.springframework.util.StringUtils) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsData(org.thingsboard.server.service.telemetry.TsData) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) FutureCallback(com.google.common.util.concurrent.FutureCallback) LinkedHashMap(java.util.LinkedHashMap)

Example 87 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project thingsboard by thingsboard.

the class RpcV2Controller method getPersistedRpcByDevice.

@ApiOperation(value = "Get persistent RPC requests", notes = "Allows to query RPC calls for specific device using pagination." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/persistent/device/{deviceId}", method = RequestMethod.GET)
@ResponseBody
public DeferredResult<ResponseEntity> getPersistedRpcByDevice(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(DEVICE_ID) String strDeviceId, @ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) @RequestParam int pageSize, @ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) @RequestParam int page, @ApiParam(value = "Status of the RPC", allowableValues = RPC_STATUS_ALLOWABLE_VALUES) @RequestParam(required = false) RpcStatus rpcStatus, @ApiParam(value = RPC_TEXT_SEARCH_DESCRIPTION) @RequestParam(required = false) String textSearch, @ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = RPC_SORT_PROPERTY_ALLOWABLE_VALUES) @RequestParam(required = false) String sortProperty, @ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) @RequestParam(required = false) String sortOrder) throws ThingsboardException {
    checkParameter("DeviceId", strDeviceId);
    try {
        if (rpcStatus != null && rpcStatus.equals(RpcStatus.DELETED)) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "RpcStatus: DELETED");
        }
        TenantId tenantId = getCurrentUser().getTenantId();
        PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
        DeviceId deviceId = new DeviceId(UUID.fromString(strDeviceId));
        final DeferredResult<ResponseEntity> response = new DeferredResult<>();
        accessValidator.validate(getCurrentUser(), Operation.RPC_CALL, deviceId, new HttpValidationCallback(response, new FutureCallback<>() {

            @Override
            public void onSuccess(@Nullable DeferredResult<ResponseEntity> result) {
                PageData<Rpc> rpcCalls;
                if (rpcStatus != null) {
                    rpcCalls = rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
                } else {
                    rpcCalls = rpcService.findAllByDeviceId(tenantId, deviceId, pageLink);
                }
                response.setResult(new ResponseEntity<>(rpcCalls, HttpStatus.OK));
            }

            @Override
            public void onFailure(Throwable e) {
                ResponseEntity entity;
                if (e instanceof ToErrorResponseEntity) {
                    entity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
                } else {
                    entity = new ResponseEntity(HttpStatus.UNAUTHORIZED);
                }
                response.setResult(entity);
            }
        }));
        return response;
    } catch (Exception e) {
        throw handleException(e);
    }
}
Also used : Rpc(org.thingsboard.server.common.data.rpc.Rpc) DeviceId(org.thingsboard.server.common.data.id.DeviceId) ResponseStatusException(org.springframework.web.server.ResponseStatusException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) TenantId(org.thingsboard.server.common.data.id.TenantId) ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) PageLink(org.thingsboard.server.common.data.page.PageLink) ResponseStatusException(org.springframework.web.server.ResponseStatusException) FutureCallback(com.google.common.util.concurrent.FutureCallback) Nullable(javax.annotation.Nullable) ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) DeferredResult(org.springframework.web.context.request.async.DeferredResult) 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 88 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method handleWsAttributesSubscriptionByKeys.

private void handleWsAttributesSubscriptionByKeys(TelemetryWebSocketSessionRef sessionRef, AttributesSubscriptionCmd cmd, String sessionId, EntityId entityId, List<String> keys) {
    FutureCallback<List<AttributeKvEntry>> callback = new FutureCallback<List<AttributeKvEntry>>() {

        @Override
        public void onSuccess(List<AttributeKvEntry> data) {
            List<TsKvEntry> attributesData = data.stream().map(d -> new BasicTsKvEntry(d.getLastUpdateTs(), d)).collect(Collectors.toList());
            sendWsMsg(sessionRef, new TelemetrySubscriptionUpdate(cmd.getCmdId(), attributesData));
            Map<String, Long> subState = new HashMap<>(keys.size());
            keys.forEach(key -> subState.put(key, 0L));
            attributesData.forEach(v -> subState.put(v.getKey(), v.getTs()));
            TbAttributeSubscriptionScope scope = StringUtils.isEmpty(cmd.getScope()) ? TbAttributeSubscriptionScope.ANY_SCOPE : TbAttributeSubscriptionScope.valueOf(cmd.getScope());
            TbAttributeSubscription sub = TbAttributeSubscription.builder().serviceId(serviceId).sessionId(sessionId).subscriptionId(cmd.getCmdId()).tenantId(sessionRef.getSecurityCtx().getTenantId()).entityId(entityId).allKeys(false).keyStates(subState).scope(scope).updateConsumer(DefaultTelemetryWebSocketService.this::sendWsMsg).build();
            oldSubService.addSubscription(sub);
        }

        @Override
        public void onFailure(Throwable e) {
            log.error(FAILED_TO_FETCH_ATTRIBUTES, e);
            TelemetrySubscriptionUpdate update;
            if (e instanceof UnauthorizedException) {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.UNAUTHORIZED, SubscriptionErrorCode.UNAUTHORIZED.getDefaultMsg());
            } else {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_ATTRIBUTES);
            }
            sendWsMsg(sessionRef, update);
        }
    };
    if (StringUtils.isEmpty(cmd.getScope())) {
        accessValidator.validate(sessionRef.getSecurityCtx(), Operation.READ_ATTRIBUTES, entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, keys, callback));
    } else {
        accessValidator.validate(sessionRef.getSecurityCtx(), Operation.READ_ATTRIBUTES, entityId, getAttributesFetchCallback(sessionRef.getSecurityCtx().getTenantId(), entityId, cmd.getScope(), keys, callback));
    }
}
Also used : GetHistoryCmd(org.thingsboard.server.service.telemetry.cmd.v1.GetHistoryCmd) Autowired(org.springframework.beans.factory.annotation.Autowired) AttributesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.AttributesSubscriptionCmd) CloseStatus(org.springframework.web.socket.CloseStatus) TenantId(org.thingsboard.server.common.data.id.TenantId) UnauthorizedException(org.thingsboard.server.service.telemetry.exception.UnauthorizedException) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PreDestroy(javax.annotation.PreDestroy) CmdUpdate(org.thingsboard.server.service.telemetry.cmd.v2.CmdUpdate) Map(java.util.Map) TbServiceInfoProvider(org.thingsboard.server.queue.discovery.TbServiceInfoProvider) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) TbAttributeSubscriptionScope(org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) Function(com.google.common.base.Function) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) Set(java.util.Set) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) ValidationResult(org.thingsboard.server.service.security.ValidationResult) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TenantRateLimitException(org.thingsboard.server.dao.util.TenantRateLimitException) UnsubscribeCmd(org.thingsboard.server.service.telemetry.cmd.v2.UnsubscribeCmd) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) Operation(org.thingsboard.server.service.security.permission.Operation) ValidationCallback(org.thingsboard.server.service.security.ValidationCallback) CustomerId(org.thingsboard.server.common.data.id.CustomerId) TelemetryPluginCmd(org.thingsboard.server.service.telemetry.cmd.v1.TelemetryPluginCmd) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) TimeseriesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.TimeseriesSubscriptionCmd) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AlarmDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.AlarmDataCmd) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Value(org.springframework.beans.factory.annotation.Value) HashSet(java.util.HashSet) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) Service(org.springframework.stereotype.Service) ValidationResultCode(org.thingsboard.server.service.security.ValidationResultCode) EntityId(org.thingsboard.server.common.data.id.EntityId) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) ThingsBoardExecutors(org.thingsboard.common.util.ThingsBoardExecutors) DataConstants(org.thingsboard.server.common.data.DataConstants) AccessValidator(org.thingsboard.server.service.security.AccessValidator) TbTimeseriesSubscription(org.thingsboard.server.service.subscription.TbTimeseriesSubscription) Aggregation(org.thingsboard.server.common.data.kv.Aggregation) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TbEntityDataSubscriptionService(org.thingsboard.server.service.subscription.TbEntityDataSubscriptionService) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Futures(com.google.common.util.concurrent.Futures) UserId(org.thingsboard.server.common.data.id.UserId) SubscriptionErrorCode(org.thingsboard.server.service.telemetry.sub.SubscriptionErrorCode) TelemetryPluginCmdsWrapper(org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper) TbLocalSubscriptionService(org.thingsboard.server.service.subscription.TbLocalSubscriptionService) EntityCountCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) TbAttributeSubscription(org.thingsboard.server.service.subscription.TbAttributeSubscription) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) SubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.SubscriptionCmd) TbAttributeSubscription(org.thingsboard.server.service.subscription.TbAttributeSubscription) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) UnauthorizedException(org.thingsboard.server.service.telemetry.exception.UnauthorizedException) List(java.util.List) ArrayList(java.util.ArrayList) FutureCallback(com.google.common.util.concurrent.FutureCallback) TbAttributeSubscriptionScope(org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope)

Example 89 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method getSubscriptionCallback.

private FutureCallback<List<TsKvEntry>> getSubscriptionCallback(final TelemetryWebSocketSessionRef sessionRef, final TimeseriesSubscriptionCmd cmd, final String sessionId, final EntityId entityId, final long startTs, final List<String> keys) {
    return new FutureCallback<List<TsKvEntry>>() {

        @Override
        public void onSuccess(List<TsKvEntry> data) {
            sendWsMsg(sessionRef, new TelemetrySubscriptionUpdate(cmd.getCmdId(), data));
            Map<String, Long> subState = new HashMap<>(keys.size());
            keys.forEach(key -> subState.put(key, startTs));
            data.forEach(v -> subState.put(v.getKey(), v.getTs()));
            TbTimeseriesSubscription sub = TbTimeseriesSubscription.builder().serviceId(serviceId).sessionId(sessionId).subscriptionId(cmd.getCmdId()).tenantId(sessionRef.getSecurityCtx().getTenantId()).entityId(entityId).updateConsumer(DefaultTelemetryWebSocketService.this::sendWsMsg).allKeys(false).keyStates(subState).build();
            oldSubService.addSubscription(sub);
        }

        @Override
        public void onFailure(Throwable e) {
            if (e instanceof TenantRateLimitException || e.getCause() instanceof TenantRateLimitException) {
                log.trace("[{}] Tenant rate limit detected for subscription: [{}]:{}", sessionRef.getSecurityCtx().getTenantId(), entityId, cmd);
            } else {
                log.info(FAILED_TO_FETCH_DATA, e);
            }
            TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            sendWsMsg(sessionRef, update);
        }
    };
}
Also used : TenantRateLimitException(org.thingsboard.server.dao.util.TenantRateLimitException) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) TbTimeseriesSubscription(org.thingsboard.server.service.subscription.TbTimeseriesSubscription) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) List(java.util.List) ArrayList(java.util.ArrayList) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 90 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project thingsboard by thingsboard.

the class DefaultTelemetryWebSocketService method handleWsHistoryCmd.

private void handleWsHistoryCmd(TelemetryWebSocketSessionRef sessionRef, GetHistoryCmd cmd) {
    String sessionId = sessionRef.getSessionId();
    WsSessionMetaData sessionMD = wsSessionsMap.get(sessionId);
    if (sessionMD == null) {
        log.warn("[{}] Session meta data not found. ", sessionId);
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, SESSION_META_DATA_NOT_FOUND);
        sendWsMsg(sessionRef, update);
        return;
    }
    if (cmd.getEntityId() == null || cmd.getEntityId().isEmpty() || cmd.getEntityType() == null || cmd.getEntityType().isEmpty()) {
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Device id is empty!");
        sendWsMsg(sessionRef, update);
        return;
    }
    if (cmd.getKeys() == null || cmd.getKeys().isEmpty()) {
        TelemetrySubscriptionUpdate update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.BAD_REQUEST, "Keys are empty!");
        sendWsMsg(sessionRef, update);
        return;
    }
    EntityId entityId = EntityIdFactory.getByTypeAndId(cmd.getEntityType(), cmd.getEntityId());
    List<String> keys = new ArrayList<>(getKeys(cmd).orElse(Collections.emptySet()));
    List<ReadTsKvQuery> queries = keys.stream().map(key -> new BaseReadTsKvQuery(key, cmd.getStartTs(), cmd.getEndTs(), cmd.getInterval(), getLimit(cmd.getLimit()), getAggregation(cmd.getAgg()))).collect(Collectors.toList());
    FutureCallback<List<TsKvEntry>> callback = new FutureCallback<List<TsKvEntry>>() {

        @Override
        public void onSuccess(List<TsKvEntry> data) {
            sendWsMsg(sessionRef, new TelemetrySubscriptionUpdate(cmd.getCmdId(), data));
        }

        @Override
        public void onFailure(Throwable e) {
            TelemetrySubscriptionUpdate update;
            if (UnauthorizedException.class.isInstance(e)) {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.UNAUTHORIZED, SubscriptionErrorCode.UNAUTHORIZED.getDefaultMsg());
            } else {
                update = new TelemetrySubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            }
            sendWsMsg(sessionRef, update);
        }
    };
    accessValidator.validate(sessionRef.getSecurityCtx(), Operation.READ_TELEMETRY, entityId, on(r -> Futures.addCallback(tsService.findAll(sessionRef.getSecurityCtx().getTenantId(), entityId, queries), callback, executor), callback::onFailure));
}
Also used : GetHistoryCmd(org.thingsboard.server.service.telemetry.cmd.v1.GetHistoryCmd) Autowired(org.springframework.beans.factory.annotation.Autowired) AttributesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.AttributesSubscriptionCmd) CloseStatus(org.springframework.web.socket.CloseStatus) TenantId(org.thingsboard.server.common.data.id.TenantId) UnauthorizedException(org.thingsboard.server.service.telemetry.exception.UnauthorizedException) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PreDestroy(javax.annotation.PreDestroy) CmdUpdate(org.thingsboard.server.service.telemetry.cmd.v2.CmdUpdate) Map(java.util.Map) TbServiceInfoProvider(org.thingsboard.server.queue.discovery.TbServiceInfoProvider) AttributesService(org.thingsboard.server.dao.attributes.AttributesService) TbAttributeSubscriptionScope(org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) EntityDataUpdate(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate) Function(com.google.common.base.Function) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TimeseriesService(org.thingsboard.server.dao.timeseries.TimeseriesService) Set(java.util.Set) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) ValidationResult(org.thingsboard.server.service.security.ValidationResult) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TenantRateLimitException(org.thingsboard.server.dao.util.TenantRateLimitException) UnsubscribeCmd(org.thingsboard.server.service.telemetry.cmd.v2.UnsubscribeCmd) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) Operation(org.thingsboard.server.service.security.permission.Operation) ValidationCallback(org.thingsboard.server.service.security.ValidationCallback) CustomerId(org.thingsboard.server.common.data.id.CustomerId) TelemetryPluginCmd(org.thingsboard.server.service.telemetry.cmd.v1.TelemetryPluginCmd) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) TimeseriesSubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.TimeseriesSubscriptionCmd) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AlarmDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.AlarmDataCmd) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) Value(org.springframework.beans.factory.annotation.Value) HashSet(java.util.HashSet) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) EntityDataCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd) TbCoreComponent(org.thingsboard.server.queue.util.TbCoreComponent) Service(org.springframework.stereotype.Service) ValidationResultCode(org.thingsboard.server.service.security.ValidationResultCode) EntityId(org.thingsboard.server.common.data.id.EntityId) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) UserPrincipal(org.thingsboard.server.service.security.model.UserPrincipal) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) ThingsBoardExecutors(org.thingsboard.common.util.ThingsBoardExecutors) DataConstants(org.thingsboard.server.common.data.DataConstants) AccessValidator(org.thingsboard.server.service.security.AccessValidator) TbTimeseriesSubscription(org.thingsboard.server.service.subscription.TbTimeseriesSubscription) Aggregation(org.thingsboard.server.common.data.kv.Aggregation) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) TbEntityDataSubscriptionService(org.thingsboard.server.service.subscription.TbEntityDataSubscriptionService) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Futures(com.google.common.util.concurrent.Futures) UserId(org.thingsboard.server.common.data.id.UserId) SubscriptionErrorCode(org.thingsboard.server.service.telemetry.sub.SubscriptionErrorCode) TelemetryPluginCmdsWrapper(org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper) TbLocalSubscriptionService(org.thingsboard.server.service.subscription.TbLocalSubscriptionService) EntityCountCmd(org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) TbAttributeSubscription(org.thingsboard.server.service.subscription.TbAttributeSubscription) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) Collections(java.util.Collections) StringUtils(org.springframework.util.StringUtils) SubscriptionCmd(org.thingsboard.server.service.telemetry.cmd.v1.SubscriptionCmd) BasicTsKvEntry(org.thingsboard.server.common.data.kv.BasicTsKvEntry) TsKvEntry(org.thingsboard.server.common.data.kv.TsKvEntry) ArrayList(java.util.ArrayList) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) EntityId(org.thingsboard.server.common.data.id.EntityId) TelemetrySubscriptionUpdate(org.thingsboard.server.service.telemetry.sub.TelemetrySubscriptionUpdate) BaseReadTsKvQuery(org.thingsboard.server.common.data.kv.BaseReadTsKvQuery) ReadTsKvQuery(org.thingsboard.server.common.data.kv.ReadTsKvQuery) List(java.util.List) ArrayList(java.util.ArrayList) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Aggregations

FutureCallback (com.google.common.util.concurrent.FutureCallback)98 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)56 List (java.util.List)48 Futures (com.google.common.util.concurrent.Futures)43 ArrayList (java.util.ArrayList)41 Nullable (javax.annotation.Nullable)38 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)26 Map (java.util.Map)25 Set (java.util.Set)25 TimeUnit (java.util.concurrent.TimeUnit)24 IOException (java.io.IOException)23 Collectors (java.util.stream.Collectors)23 PostConstruct (javax.annotation.PostConstruct)23 ExecutorService (java.util.concurrent.ExecutorService)22 Function (com.google.common.base.Function)21 Collections (java.util.Collections)21 TenantId (org.thingsboard.server.common.data.id.TenantId)21 PreDestroy (javax.annotation.PreDestroy)20 Logger (org.slf4j.Logger)19 LoggerFactory (org.slf4j.LoggerFactory)19