Search in sources :

Example 1 with RestRequest

use of org.thingsboard.server.extensions.api.plugins.rest.RestRequest in project thingsboard by thingsboard.

the class RpcRestMsgHandler method handleHttpPostRequest.

@Override
public void handleHttpPostRequest(PluginContext ctx, PluginRestMsg msg) throws ServletException {
    boolean valid = false;
    RestRequest request = msg.getRequest();
    try {
        String[] pathParams = request.getPathParams();
        if (pathParams.length == 2) {
            String method = pathParams[0].toUpperCase();
            if (DataConstants.ONEWAY.equals(method) || DataConstants.TWOWAY.equals(method)) {
                final TenantId tenantId = ctx.getSecurityCtx().orElseThrow(() -> new IllegalStateException("Security context is empty!")).getTenantId();
                JsonNode rpcRequestBody = jsonMapper.readTree(request.getRequestBody());
                RpcRequest cmd = new RpcRequest(rpcRequestBody.get("method").asText(), jsonMapper.writeValueAsString(rpcRequestBody.get("params")));
                if (rpcRequestBody.has("timeout")) {
                    cmd.setTimeout(rpcRequestBody.get("timeout").asLong());
                }
                boolean oneWay = DataConstants.ONEWAY.equals(method);
                DeviceId deviceId = DeviceId.fromString(pathParams[1]);
                valid = handleDeviceRPCRequest(ctx, msg, tenantId, deviceId, cmd, oneWay);
            }
        }
    } catch (IOException e) {
        log.debug("Failed to process POST request due to IO exception", e);
    } catch (RuntimeException e) {
        log.debug("Failed to process POST request due to Runtime exception", e);
    }
    if (!valid) {
        msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
    }
}
Also used : TenantId(org.thingsboard.server.common.data.id.TenantId) RestRequest(org.thingsboard.server.extensions.api.plugins.rest.RestRequest) DeviceId(org.thingsboard.server.common.data.id.DeviceId) RpcRequest(org.thingsboard.server.extensions.core.plugin.rpc.cmd.RpcRequest) ToDeviceRpcRequest(org.thingsboard.server.extensions.api.plugins.msg.ToDeviceRpcRequest) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException)

Example 2 with RestRequest

use of org.thingsboard.server.extensions.api.plugins.rest.RestRequest in project thingsboard by thingsboard.

the class TelemetryRestMsgHandler method handleHttpDeleteRequest.

@Override
public void handleHttpDeleteRequest(PluginContext ctx, PluginRestMsg msg) throws ServletException {
    RestRequest request = msg.getRequest();
    Exception error = null;
    try {
        String[] pathParams = request.getPathParams();
        EntityId entityId;
        String scope;
        if (pathParams.length == 2) {
            entityId = DeviceId.fromString(pathParams[0]);
            scope = pathParams[1];
        } else if (pathParams.length == 3) {
            entityId = EntityIdFactory.getByTypeAndId(pathParams[0], pathParams[1]);
            scope = pathParams[2];
        } else {
            msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
            return;
        }
        if (DataConstants.SERVER_SCOPE.equals(scope) || DataConstants.SHARED_SCOPE.equals(scope) || DataConstants.CLIENT_SCOPE.equals(scope)) {
            String keysParam = request.getParameter("keys");
            if (!StringUtils.isEmpty(keysParam)) {
                String[] keys = keysParam.split(",");
                List<String> keyList = Arrays.asList(keys);
                ctx.removeAttributes(ctx.getSecurityCtx().orElseThrow(IllegalArgumentException::new).getTenantId(), entityId, scope, keyList, new PluginCallback<Void>() {

                    @Override
                    public void onSuccess(PluginContext ctx, Void value) {
                        ctx.logAttributesDeleted(msg.getSecurityCtx(), entityId, scope, keyList, null);
                        msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.OK));
                    }

                    @Override
                    public void onFailure(PluginContext ctx, Exception e) {
                        log.error("Failed to remove attributes", e);
                        ctx.logAttributesDeleted(msg.getSecurityCtx(), entityId, scope, keyList, e);
                        handleError(e, msg, HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                });
                return;
            }
        }
    } catch (RuntimeException e) {
        log.debug("Failed to process DELETE request due to Runtime exception", e);
        error = e;
    }
    handleError(error, msg, HttpStatus.BAD_REQUEST);
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) ServletException(javax.servlet.ServletException) UncheckedApiException(org.thingsboard.server.extensions.api.exception.UncheckedApiException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvalidParametersException(org.thingsboard.server.extensions.api.exception.InvalidParametersException) EntityId(org.thingsboard.server.common.data.id.EntityId) ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) RestRequest(org.thingsboard.server.extensions.api.plugins.rest.RestRequest)

Example 3 with RestRequest

use of org.thingsboard.server.extensions.api.plugins.rest.RestRequest in project thingsboard by thingsboard.

the class PluginApiController method processRequest.

@SuppressWarnings("rawtypes")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/{pluginToken}/**")
@ResponseStatus(value = HttpStatus.OK)
public DeferredResult<ResponseEntity> processRequest(@PathVariable("pluginToken") String pluginToken, RequestEntity<byte[]> requestEntity, HttpServletRequest request) throws ThingsboardException {
    log.debug("[{}] Going to process requst uri: {}", pluginToken, requestEntity.getUrl());
    DeferredResult<ResponseEntity> result = new DeferredResult<ResponseEntity>();
    PluginMetaData pluginMd = pluginService.findPluginByApiToken(pluginToken);
    if (pluginMd == null) {
        result.setErrorResult(new PluginNotFoundException("Plugin with token: " + pluginToken + " not found!"));
    } else {
        TenantId tenantId = getCurrentUser().getTenantId();
        CustomerId customerId = getCurrentUser().getCustomerId();
        if (validatePluginAccess(pluginMd, tenantId, customerId)) {
            if (tenantId != null && ModelConstants.NULL_UUID.equals(tenantId.getId())) {
                tenantId = null;
            }
            UserId userId = getCurrentUser().getId();
            String userName = getCurrentUser().getName();
            PluginApiCallSecurityContext securityCtx = new PluginApiCallSecurityContext(pluginMd.getTenantId(), pluginMd.getId(), tenantId, customerId, userId, userName);
            actorService.process(new BasicPluginRestMsg(securityCtx, new RestRequest(requestEntity, request), result));
        } else {
            result.setResult(new ResponseEntity<>(HttpStatus.FORBIDDEN));
        }
    }
    return result;
}
Also used : BasicPluginRestMsg(org.thingsboard.server.extensions.api.plugins.rest.BasicPluginRestMsg) PluginMetaData(org.thingsboard.server.common.data.plugin.PluginMetaData) CustomerId(org.thingsboard.server.common.data.id.CustomerId) PluginApiCallSecurityContext(org.thingsboard.server.extensions.api.plugins.PluginApiCallSecurityContext) ResponseEntity(org.springframework.http.ResponseEntity) TenantId(org.thingsboard.server.common.data.id.TenantId) RestRequest(org.thingsboard.server.extensions.api.plugins.rest.RestRequest) UserId(org.thingsboard.server.common.data.id.UserId) DeferredResult(org.springframework.web.context.request.async.DeferredResult) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with RestRequest

use of org.thingsboard.server.extensions.api.plugins.rest.RestRequest in project thingsboard by thingsboard.

the class TelemetryRestMsgHandler method handleHttpGetRequest.

@Override
public void handleHttpGetRequest(PluginContext ctx, PluginRestMsg msg) throws ServletException {
    RestRequest request = msg.getRequest();
    String[] pathParams = request.getPathParams();
    if (pathParams.length < 4) {
        msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        return;
    }
    String entityType = pathParams[0];
    String entityIdStr = pathParams[1];
    String method = pathParams[2];
    TelemetryFeature feature = TelemetryFeature.forName(pathParams[3]);
    String scope = pathParams.length >= 5 ? pathParams[4] : null;
    if (StringUtils.isEmpty(entityType) || EntityType.valueOf(entityType) == null || StringUtils.isEmpty(entityIdStr) || StringUtils.isEmpty(method) || StringUtils.isEmpty(feature)) {
        msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
        return;
    }
    EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
    if (method.equals("keys")) {
        handleHttpGetKeysMethod(ctx, msg, feature, scope, entityId);
    } else if (method.equals("values")) {
        handleHttpGetValuesMethod(ctx, msg, request, feature, scope, entityId);
    }
}
Also used : EntityId(org.thingsboard.server.common.data.id.EntityId) RestRequest(org.thingsboard.server.extensions.api.plugins.rest.RestRequest)

Example 5 with RestRequest

use of org.thingsboard.server.extensions.api.plugins.rest.RestRequest in project thingsboard by thingsboard.

the class TelemetryRestMsgHandler method handleHttpPostRequest.

@Override
public void handleHttpPostRequest(PluginContext ctx, PluginRestMsg msg) throws ServletException {
    RestRequest request = msg.getRequest();
    Exception error = null;
    try {
        String[] pathParams = request.getPathParams();
        EntityId entityId;
        String scope;
        long ttl = 0L;
        TelemetryFeature feature;
        if (pathParams.length == 2) {
            entityId = DeviceId.fromString(pathParams[0]);
            scope = pathParams[1];
            feature = TelemetryFeature.ATTRIBUTES;
        } else if (pathParams.length == 3) {
            entityId = EntityIdFactory.getByTypeAndId(pathParams[0], pathParams[1]);
            scope = pathParams[2];
            feature = TelemetryFeature.ATTRIBUTES;
        } else if (pathParams.length == 4) {
            entityId = EntityIdFactory.getByTypeAndId(pathParams[0], pathParams[1]);
            feature = TelemetryFeature.forName(pathParams[2].toUpperCase());
            scope = pathParams[3];
        } else if (pathParams.length == 5) {
            entityId = EntityIdFactory.getByTypeAndId(pathParams[0], pathParams[1]);
            feature = TelemetryFeature.forName(pathParams[2].toUpperCase());
            scope = pathParams[3];
            ttl = Long.parseLong(pathParams[4]);
        } else {
            msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST));
            return;
        }
        if (feature == TelemetryFeature.ATTRIBUTES) {
            if (handleHttpPostAttributes(ctx, msg, request, entityId, scope)) {
                return;
            }
        } else if (feature == TelemetryFeature.TIMESERIES) {
            handleHttpPostTimeseries(ctx, msg, request, entityId, ttl);
            return;
        }
    } catch (IOException | RuntimeException e) {
        log.debug("Failed to process POST request due to exception", e);
        error = e;
    }
    handleError(error, msg, HttpStatus.BAD_REQUEST);
}
Also used : EntityId(org.thingsboard.server.common.data.id.EntityId) ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) RestRequest(org.thingsboard.server.extensions.api.plugins.rest.RestRequest) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) UncheckedApiException(org.thingsboard.server.extensions.api.exception.UncheckedApiException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvalidParametersException(org.thingsboard.server.extensions.api.exception.InvalidParametersException)

Aggregations

RestRequest (org.thingsboard.server.extensions.api.plugins.rest.RestRequest)5 IOException (java.io.IOException)3 ResponseEntity (org.springframework.http.ResponseEntity)3 EntityId (org.thingsboard.server.common.data.id.EntityId)3 JsonSyntaxException (com.google.gson.JsonSyntaxException)2 ServletException (javax.servlet.ServletException)2 TenantId (org.thingsboard.server.common.data.id.TenantId)2 InvalidParametersException (org.thingsboard.server.extensions.api.exception.InvalidParametersException)2 ToErrorResponseEntity (org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity)2 UncheckedApiException (org.thingsboard.server.extensions.api.exception.UncheckedApiException)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)1 DeferredResult (org.springframework.web.context.request.async.DeferredResult)1 CustomerId (org.thingsboard.server.common.data.id.CustomerId)1 DeviceId (org.thingsboard.server.common.data.id.DeviceId)1 UserId (org.thingsboard.server.common.data.id.UserId)1 PluginMetaData (org.thingsboard.server.common.data.plugin.PluginMetaData)1 PluginApiCallSecurityContext (org.thingsboard.server.extensions.api.plugins.PluginApiCallSecurityContext)1