Search in sources :

Example 1 with ToErrorResponseEntity

use of org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity in project thingsboard by thingsboard.

the class AccessValidator method handleError.

public static void handleError(Throwable e, final DeferredResult<ResponseEntity> response, HttpStatus defaultErrorStatus) {
    ResponseEntity responseEntity;
    if (e instanceof ToErrorResponseEntity) {
        responseEntity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
    } else if (e instanceof IllegalArgumentException || e instanceof IncorrectParameterException) {
        responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    } else {
        responseEntity = new ResponseEntity<>(defaultErrorStatus);
    }
    response.setResult(responseEntity);
}
Also used : ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) IncorrectParameterException(org.thingsboard.server.dao.exception.IncorrectParameterException) ToErrorResponseEntity(org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity)

Example 2 with ToErrorResponseEntity

use of org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity 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 3 with ToErrorResponseEntity

use of org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity 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

ResponseEntity (org.springframework.http.ResponseEntity)3 ToErrorResponseEntity (org.thingsboard.server.service.telemetry.exception.ToErrorResponseEntity)3 FutureCallback (com.google.common.util.concurrent.FutureCallback)2 Nullable (javax.annotation.Nullable)2 DeferredResult (org.springframework.web.context.request.async.DeferredResult)2 ThingsboardException (org.thingsboard.server.common.data.exception.ThingsboardException)2 TenantId (org.thingsboard.server.common.data.id.TenantId)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ApiOperation (io.swagger.annotations.ApiOperation)1 UUID (java.util.UUID)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)1 ResponseStatusException (org.springframework.web.server.ResponseStatusException)1 DeviceId (org.thingsboard.server.common.data.id.DeviceId)1 PageLink (org.thingsboard.server.common.data.page.PageLink)1 Rpc (org.thingsboard.server.common.data.rpc.Rpc)1 ToDeviceRpcRequestBody (org.thingsboard.server.common.data.rpc.ToDeviceRpcRequestBody)1 ToDeviceRpcRequest (org.thingsboard.server.common.msg.rpc.ToDeviceRpcRequest)1 IncorrectParameterException (org.thingsboard.server.dao.exception.IncorrectParameterException)1