Search in sources :

Example 1 with PluginContext

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

the class DeviceMessagingRuleMsgHandler method processSendMsg.

private void processSendMsg(PluginContext ctx, PendingRpcRequestMetadata requestMd, ToServerRpcRequestMsg request) {
    JsonObject params = new JsonParser().parse(request.getParams()).getAsJsonObject();
    String targetDeviceIdStr = params.get(DEVICE_ID).getAsString();
    DeviceId targetDeviceId = DeviceId.fromString(targetDeviceIdStr);
    boolean oneWay = isOneWay(params);
    long timeout = getTimeout(params);
    if (timeout <= 0) {
        replyWithError(ctx, requestMd, "Timeout can't be negative!");
    } else if (timeout > configuration.getMaxTimeout()) {
        replyWithError(ctx, requestMd, "Timeout is too large!");
    } else {
        ctx.getDevice(targetDeviceId, new PluginCallback<Device>() {

            @Override
            public void onSuccess(PluginContext ctx, Device targetDevice) {
                UUID uid = UUID.randomUUID();
                if (targetDevice == null) {
                    replyWithError(ctx, requestMd, RpcError.NOT_FOUND);
                } else if (!requestMd.getCustomerId().isNullUid() && requestMd.getTenantId().equals(targetDevice.getTenantId()) && requestMd.getCustomerId().equals(targetDevice.getCustomerId())) {
                    pendingMsgs.put(uid, requestMd);
                    log.trace("[{}] Forwarding {} to [{}]", uid, params, targetDeviceId);
                    ToDeviceRpcRequestBody requestBody = new ToDeviceRpcRequestBody(ON_MSG_METHOD_NAME, GSON.toJson(params.get("body")));
                    ctx.sendRpcRequest(new ToDeviceRpcRequest(uid, null, targetDevice.getTenantId(), targetDeviceId, oneWay, System.currentTimeMillis() + timeout, requestBody));
                } else {
                    replyWithError(ctx, requestMd, RpcError.FORBIDDEN);
                }
            }

            @Override
            public void onFailure(PluginContext ctx, Exception e) {
                replyWithError(ctx, requestMd, RpcError.INTERNAL);
            }
        });
    }
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) DeviceId(org.thingsboard.server.common.data.id.DeviceId) Device(org.thingsboard.server.common.data.Device) JsonObject(com.google.gson.JsonObject) RuleException(org.thingsboard.server.extensions.api.rules.RuleException) JsonParser(com.google.gson.JsonParser) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Example 2 with PluginContext

use of org.thingsboard.server.extensions.api.plugins.PluginContext 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 PluginContext

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

the class TelemetryRestMsgHandler method handleHttpPostTimeseries.

private void handleHttpPostTimeseries(PluginContext ctx, PluginRestMsg msg, RestRequest request, EntityId entityId, long ttl) {
    TelemetryUploadRequest telemetryRequest;
    JsonElement telemetryJson;
    try {
        telemetryJson = new JsonParser().parse(request.getRequestBody());
    } catch (Exception e) {
        throw new IllegalArgumentException("Unable to parse timeseries payload: Invalid JSON body!");
    }
    try {
        telemetryRequest = JsonConverter.convertToTelemetry(telemetryJson);
    } catch (JsonSyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    List<TsKvEntry> entries = new ArrayList<>();
    for (Map.Entry<Long, List<KvEntry>> entry : telemetryRequest.getData().entrySet()) {
        for (KvEntry kv : entry.getValue()) {
            entries.add(new BasicTsKvEntry(entry.getKey(), kv));
        }
    }
    if (entries.isEmpty()) {
        throw new IllegalArgumentException("No timeseries data found in request body!");
    }
    ctx.saveTsData(entityId, entries, ttl, new PluginCallback<Void>() {

        @Override
        public void onSuccess(PluginContext ctx, Void value) {
            msg.getResponseHolder().setResult(new ResponseEntity<>(HttpStatus.OK));
            subscriptionManager.onTimeseriesUpdateFromServer(ctx, entityId, entries);
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error("Failed to save attributes", e);
            handleError(e, msg, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    });
}
Also used : TelemetryUploadRequest(org.thingsboard.server.common.msg.core.TelemetryUploadRequest) 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) ToErrorResponseEntity(org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) JsonElement(com.google.gson.JsonElement) JsonParser(com.google.gson.JsonParser)

Example 4 with PluginContext

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

the class TelemetryRuleMsgHandler method handleGetAttributesRequest.

@Override
public void handleGetAttributesRequest(PluginContext ctx, TenantId tenantId, RuleId ruleId, GetAttributesRequestRuleToPluginMsg msg) {
    GetAttributesRequest request = msg.getPayload();
    BiPluginCallBack<List<AttributeKvEntry>, List<AttributeKvEntry>> callback = new BiPluginCallBack<List<AttributeKvEntry>, List<AttributeKvEntry>>() {

        @Override
        public void onSuccess(PluginContext ctx, List<AttributeKvEntry> clientAttributes, List<AttributeKvEntry> sharedAttributes) {
            BasicGetAttributesResponse response = BasicGetAttributesResponse.onSuccess(request.getMsgType(), request.getRequestId(), BasicAttributeKVMsg.from(clientAttributes, sharedAttributes));
            ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, response));
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error("Failed to process get attributes request", e);
            ctx.reply(new ResponsePluginToRuleMsg(msg.getUid(), tenantId, ruleId, BasicStatusCodeResponse.onError(request.getMsgType(), request.getRequestId(), e)));
        }
    };
    getAttributeKvEntries(ctx, msg.getDeviceId(), DataConstants.CLIENT_SCOPE, request.getClientAttributeNames(), callback.getV1Callback());
    getAttributeKvEntries(ctx, msg.getDeviceId(), DataConstants.SHARED_SCOPE, request.getSharedAttributeNames(), callback.getV2Callback());
}
Also used : AttributeKvEntry(org.thingsboard.server.common.data.kv.AttributeKvEntry) PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) ResponsePluginToRuleMsg(org.thingsboard.server.extensions.api.plugins.msg.ResponsePluginToRuleMsg)

Example 5 with PluginContext

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

the class TelemetryWebsocketMsgHandler method getSubscriptionCallback.

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

        @Override
        public void onSuccess(PluginContext ctx, List<TsKvEntry> data) {
            sendWsMsg(ctx, sessionRef, new SubscriptionUpdate(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()));
            SubscriptionState sub = new SubscriptionState(sessionId, cmd.getCmdId(), entityId, SubscriptionType.TIMESERIES, false, subState, cmd.getScope());
            subscriptionManager.addLocalWsSubscription(ctx, sessionId, entityId, sub);
        }

        @Override
        public void onFailure(PluginContext ctx, Exception e) {
            log.error(FAILED_TO_FETCH_DATA, e);
            SubscriptionUpdate update = new SubscriptionUpdate(cmd.getCmdId(), SubscriptionErrorCode.INTERNAL_ERROR, FAILED_TO_FETCH_DATA);
            sendWsMsg(ctx, sessionRef, update);
        }
    };
}
Also used : PluginContext(org.thingsboard.server.extensions.api.plugins.PluginContext) SubscriptionState(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState) SubscriptionUpdate(org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) UnauthorizedException(org.thingsboard.server.extensions.api.exception.UnauthorizedException) PluginCallback(org.thingsboard.server.extensions.api.plugins.PluginCallback)

Aggregations

PluginContext (org.thingsboard.server.extensions.api.plugins.PluginContext)14 IOException (java.io.IOException)9 PluginCallback (org.thingsboard.server.extensions.api.plugins.PluginCallback)9 EntityId (org.thingsboard.server.common.data.id.EntityId)6 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)5 java.util (java.util)5 ServletException (javax.servlet.ServletException)5 Slf4j (lombok.extern.slf4j.Slf4j)5 DataConstants (org.thingsboard.server.common.data.DataConstants)5 SubscriptionState (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionState)5 SubscriptionType (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionType)5 SubscriptionUpdate (org.thingsboard.server.extensions.core.plugin.telemetry.sub.SubscriptionUpdate)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 Collectors (java.util.stream.Collectors)4 ResponseEntity (org.springframework.http.ResponseEntity)4 StringUtils (org.springframework.util.StringUtils)4 DeviceId (org.thingsboard.server.common.data.id.DeviceId)4 org.thingsboard.server.common.data.kv (org.thingsboard.server.common.data.kv)4 InvalidParametersException (org.thingsboard.server.extensions.api.exception.InvalidParametersException)4 ToErrorResponseEntity (org.thingsboard.server.extensions.api.exception.ToErrorResponseEntity)4