Search in sources :

Example 96 with FutureCallback

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

the class AccessValidator method validateEntityAndCallback.

public DeferredResult<ResponseEntity> validateEntityAndCallback(SecurityUser currentUser, Operation operation, EntityId entityId, ThreeConsumer<DeferredResult<ResponseEntity>, TenantId, EntityId> onSuccess, BiConsumer<DeferredResult<ResponseEntity>, Throwable> onFailure) throws ThingsboardException {
    final DeferredResult<ResponseEntity> response = new DeferredResult<>();
    validate(currentUser, operation, entityId, new HttpValidationCallback(response, new FutureCallback<DeferredResult<ResponseEntity>>() {

        @Override
        public void onSuccess(@Nullable DeferredResult<ResponseEntity> result) {
            try {
                onSuccess.accept(response, currentUser.getTenantId(), entityId);
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            onFailure.accept(response, t);
        }
    }));
    return response;
}
Also used : ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) HttpValidationCallback(org.thingsboard.server.controller.HttpValidationCallback) FutureCallback(com.google.common.util.concurrent.FutureCallback) Nullable(javax.annotation.Nullable) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) DeferredResult(org.springframework.web.context.request.async.DeferredResult)

Example 97 with FutureCallback

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

the class AccessValidator method validateEntityView.

private void validateEntityView(final SecurityUser currentUser, Operation operation, EntityId entityId, FutureCallback<ValidationResult> callback) {
    if (currentUser.isSystemAdmin()) {
        callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
    } else {
        ListenableFuture<EntityView> entityViewFuture = entityViewService.findEntityViewByIdAsync(currentUser.getTenantId(), new EntityViewId(entityId.getId()));
        Futures.addCallback(entityViewFuture, getCallback(callback, entityView -> {
            if (entityView == null) {
                return ValidationResult.entityNotFound(ENTITY_VIEW_WITH_REQUESTED_ID_NOT_FOUND);
            } else {
                try {
                    accessControlService.checkPermission(currentUser, Resource.ENTITY_VIEW, operation, entityId, entityView);
                } catch (ThingsboardException e) {
                    return ValidationResult.accessDenied(e.getMessage());
                }
                return ValidationResult.ok(entityView);
            }
        }), executor);
    }
}
Also used : Edge(org.thingsboard.server.common.data.edge.Edge) HttpValidationCallback(org.thingsboard.server.controller.HttpValidationCallback) Customer(org.thingsboard.server.common.data.Customer) Autowired(org.springframework.beans.factory.annotation.Autowired) DeviceProfileId(org.thingsboard.server.common.data.id.DeviceProfileId) RuleNodeId(org.thingsboard.server.common.data.id.RuleNodeId) TenantId(org.thingsboard.server.common.data.id.TenantId) ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) PreDestroy(javax.annotation.PreDestroy) TenantService(org.thingsboard.server.dao.tenant.TenantService) Rpc(org.thingsboard.server.common.data.rpc.Rpc) ResourceService(org.thingsboard.server.dao.resource.ResourceService) RpcService(org.thingsboard.server.dao.rpc.RpcService) ApiUsageStateService(org.thingsboard.server.dao.usagerecord.ApiUsageStateService) EntityViewService(org.thingsboard.server.dao.entityview.EntityViewService) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) EdgeId(org.thingsboard.server.common.data.id.EdgeId) AssetService(org.thingsboard.server.dao.asset.AssetService) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Function(com.google.common.base.Function) DeviceProfile(org.thingsboard.server.common.data.DeviceProfile) EdgeService(org.thingsboard.server.dao.edge.EdgeService) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) ThingsBoardThreadFactory(org.thingsboard.common.util.ThingsBoardThreadFactory) ApiUsageStateId(org.thingsboard.server.common.data.id.ApiUsageStateId) OtaPackageId(org.thingsboard.server.common.data.id.OtaPackageId) Executors(java.util.concurrent.Executors) EntityView(org.thingsboard.server.common.data.EntityView) PostConstruct(javax.annotation.PostConstruct) RuleChainId(org.thingsboard.server.common.data.id.RuleChainId) Operation(org.thingsboard.server.service.security.permission.Operation) EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) CustomerId(org.thingsboard.server.common.data.id.CustomerId) OtaPackageService(org.thingsboard.server.dao.ota.OtaPackageService) UserService(org.thingsboard.server.dao.user.UserService) OtaPackageInfo(org.thingsboard.server.common.data.OtaPackageInfo) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Device(org.thingsboard.server.common.data.Device) DeferredResult(org.springframework.web.context.request.async.DeferredResult) AssetId(org.thingsboard.server.common.data.id.AssetId) Tenant(org.thingsboard.server.common.data.Tenant) RuleChainService(org.thingsboard.server.dao.rule.RuleChainService) User(org.thingsboard.server.common.data.User) EntityIdFactory(org.thingsboard.server.common.data.id.EntityIdFactory) DeviceService(org.thingsboard.server.dao.device.DeviceService) AlarmService(org.thingsboard.server.dao.alarm.AlarmService) EntityId(org.thingsboard.server.common.data.id.EntityId) BiConsumer(java.util.function.BiConsumer) CustomerService(org.thingsboard.server.dao.customer.CustomerService) Nullable(javax.annotation.Nullable) ExecutorService(java.util.concurrent.ExecutorService) RpcId(org.thingsboard.server.common.data.id.RpcId) RuleNode(org.thingsboard.server.common.data.rule.RuleNode) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) TbResourceId(org.thingsboard.server.common.data.id.TbResourceId) FutureCallback(com.google.common.util.concurrent.FutureCallback) ApiUsageState(org.thingsboard.server.common.data.ApiUsageState) DeviceProfileService(org.thingsboard.server.dao.device.DeviceProfileService) HttpStatus(org.springframework.http.HttpStatus) Futures(com.google.common.util.concurrent.Futures) Component(org.springframework.stereotype.Component) UserId(org.thingsboard.server.common.data.id.UserId) TbResourceInfo(org.thingsboard.server.common.data.TbResourceInfo) RuleChain(org.thingsboard.server.common.data.rule.RuleChain) Resource(org.thingsboard.server.service.security.permission.Resource) ResponseEntity(org.springframework.http.ResponseEntity) Asset(org.thingsboard.server.common.data.asset.Asset) AccessControlService(org.thingsboard.server.service.security.permission.AccessControlService) EntityViewId(org.thingsboard.server.common.data.id.EntityViewId) EntityView(org.thingsboard.server.common.data.EntityView) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException)

Example 98 with FutureCallback

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

the class AbstractRpcController method handleDeviceRPCRequest.

protected DeferredResult<ResponseEntity> handleDeviceRPCRequest(boolean oneWay, DeviceId deviceId, String requestBody, HttpStatus timeoutStatus, HttpStatus noActiveConnectionStatus) throws ThingsboardException {
    try {
        JsonNode rpcRequestBody = JacksonUtil.toJsonNode(requestBody);
        ToDeviceRpcRequestBody body = new ToDeviceRpcRequestBody(rpcRequestBody.get("method").asText(), JacksonUtil.toString(rpcRequestBody.get("params")));
        SecurityUser currentUser = getCurrentUser();
        TenantId tenantId = currentUser.getTenantId();
        final DeferredResult<ResponseEntity> response = new DeferredResult<>();
        long timeout = rpcRequestBody.has(DataConstants.TIMEOUT) ? rpcRequestBody.get(DataConstants.TIMEOUT).asLong() : defaultTimeout;
        long expTime = rpcRequestBody.has(DataConstants.EXPIRATION_TIME) ? rpcRequestBody.get(DataConstants.EXPIRATION_TIME).asLong() : System.currentTimeMillis() + Math.max(minTimeout, timeout);
        UUID rpcRequestUUID = rpcRequestBody.has("requestUUID") ? UUID.fromString(rpcRequestBody.get("requestUUID").asText()) : UUID.randomUUID();
        boolean persisted = rpcRequestBody.has(DataConstants.PERSISTENT) && rpcRequestBody.get(DataConstants.PERSISTENT).asBoolean();
        String additionalInfo = JacksonUtil.toString(rpcRequestBody.get(DataConstants.ADDITIONAL_INFO));
        Integer retries = rpcRequestBody.has(DataConstants.RETRIES) ? rpcRequestBody.get(DataConstants.RETRIES).asInt() : null;
        accessValidator.validate(currentUser, Operation.RPC_CALL, deviceId, new HttpValidationCallback(response, new FutureCallback<>() {

            @Override
            public void onSuccess(@Nullable DeferredResult<ResponseEntity> result) {
                ToDeviceRpcRequest rpcRequest = new ToDeviceRpcRequest(rpcRequestUUID, tenantId, deviceId, oneWay, expTime, body, persisted, retries, additionalInfo);
                deviceRpcService.processRestApiRpcRequest(rpcRequest, fromDeviceRpcResponse -> reply(new LocalRequestMetaData(rpcRequest, currentUser, result), fromDeviceRpcResponse, timeoutStatus, noActiveConnectionStatus), currentUser);
            }

            @Override
            public void onFailure(Throwable e) {
                ResponseEntity entity;
                if (e instanceof ToErrorResponseEntity) {
                    entity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
                } else {
                    entity = new ResponseEntity(HttpStatus.UNAUTHORIZED);
                }
                logRpcCall(currentUser, deviceId, body, oneWay, Optional.empty(), e);
                response.setResult(entity);
            }
        }));
        return response;
    } catch (IllegalArgumentException ioe) {
        throw new ThingsboardException("Invalid request body", ioe, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
    }
}
Also used : JsonNode(com.fasterxml.jackson.databind.JsonNode) TenantId(org.thingsboard.server.common.data.id.TenantId) ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) SecurityUser(org.thingsboard.server.service.security.model.SecurityUser) LocalRequestMetaData(org.thingsboard.server.service.rpc.LocalRequestMetaData) ToDeviceRpcRequest(org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest) ToDeviceRpcRequestBody(org.thingsboard.server.common.data.rpc.ToDeviceRpcRequestBody) ThingsboardException(org.thingsboard.server.common.data.exception.ThingsboardException) UUID(java.util.UUID) 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)

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