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);
}
});
}
}
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);
}
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);
}
});
}
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());
}
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);
}
};
}
Aggregations