From 6cc45544d6f2b9afb5ac3ffd9b5236ab34b7e945 Mon Sep 17 00:00:00 2001 From: YevhenBondarenko Date: Sun, 19 Jun 2022 20:41:20 +0200 Subject: [PATCH 1/7] license:format --- .../server/service/install/update/RateLimitsUpdater.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/install/update/RateLimitsUpdater.java b/application/src/main/java/org/thingsboard/server/service/install/update/RateLimitsUpdater.java index 054f68f71d..c136f97b52 100644 --- a/application/src/main/java/org/thingsboard/server/service/install/update/RateLimitsUpdater.java +++ b/application/src/main/java/org/thingsboard/server/service/install/update/RateLimitsUpdater.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From bda442bab23307f58170c53c047c5326023e5e30 Mon Sep 17 00:00:00 2001 From: YevhenBondarenko Date: Mon, 20 Jun 2022 13:35:50 +0200 Subject: [PATCH 2/7] refactored tb services --- .../server/controller/AlarmController.java | 24 +- .../server/controller/AssetController.java | 119 +++++--- .../server/controller/BaseController.java | 67 +---- .../server/controller/CustomerController.java | 23 +- .../controller/DashboardController.java | 196 ++++++++---- .../server/controller/DeviceController.java | 243 +++++++++------ .../controller/DeviceProfileController.java | 51 +++- .../server/controller/EdgeController.java | 126 +++++--- .../controller/EntityRelationController.java | 46 ++- .../controller/EntityViewController.java | 141 ++++++--- .../controller/OtaPackageController.java | 45 ++- .../controller/RuleChainController.java | 184 ++++++++---- .../controller/TbResourceController.java | 31 +- .../controller/TelemetryController.java | 39 +-- .../server/controller/TenantController.java | 12 +- .../controller/TenantProfileController.java | 32 +- .../server/controller/UserController.java | 42 ++- .../controller/WidgetsBundleController.java | 21 +- .../service/action/EntityActionService.java | 1 - .../device/ClaimDevicesServiceImpl.java | 71 ++--- .../entitiy/AbstractTbEntityService.java | 121 -------- .../DefaultTbNotificationEntityService.java | 153 +++++----- .../entitiy/SimpleTbEntityService.java | 10 +- .../entitiy/TbNotificationEntityService.java | 65 ++-- .../entitiy/alarm/DefaultTbAlarmService.java | 64 ++-- .../service/entitiy/alarm/TbAlarmService.java | 11 +- .../entitiy/asset/DefaultTbAssetService.java | 143 +++------ .../service/entitiy/asset/TbAssetService.java | 16 +- .../customer/DefaultTbCustomerService.java | 37 +-- .../dashboard/DefaultTbDashboardService.java | 280 +++++++----------- .../entitiy/dashboard/TbDashboardService.java | 23 +- .../device/DefaultTbDeviceService.java | 252 ++++++---------- .../entitiy/device/TbDeviceService.java | 28 +- .../DefaultTbDeviceProfileService.java | 100 +++++++ .../profile}/TbDeviceProfileService.java | 6 +- .../DefaultTbDeviceProfileService.java | 111 ------- .../entitiy/edge/DefaultTbEdgeService.java | 127 +++----- .../service/entitiy/edge/TbEdgeService.java | 14 +- .../DefaultTbEntityRelationService.java | 63 ++++ .../relation}/TbEntityRelationService.java | 10 +- .../DefaultTbEntityRelationService.java | 76 ----- .../DefaultTbEntityViewService.java | 207 ++++++------- .../TbEntityViewService.java | 22 +- .../ota/DefaultTbOtaPackageService.java | 91 ++++++ .../TbOtaPackageService.java | 15 +- .../DefaultTbOtaPackageService.java | 107 ------- .../entitiy/queue/DefaultTbQueueService.java | 2 + .../tenant/DefaultTbTenantService.java | 50 ++-- .../entitiy/tenant/TbTenantService.java | 2 +- .../DefaultTbTenantProfileService.java | 25 +- .../profile}/TbTenantProfileService.java | 7 +- .../entitiy/user/DefaultUserService.java | 60 ++-- .../service/entitiy/user/TbUserService.java | 5 +- .../bundle}/DefaultWidgetsBundleService.java | 31 +- .../bundle}/TbWidgetsBundleService.java | 9 +- .../resource/DefaultTbResourceService.java | 38 +-- .../rule/DefaultTbRuleChainService.java | 272 +++++++---------- .../service/rule/TbRuleChainService.java | 22 +- .../dao/device/ClaimDevicesService.java | 4 +- 59 files changed, 2028 insertions(+), 2165 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java rename application/src/main/java/org/thingsboard/server/service/entitiy/{deviceProfile => device/profile}/TbDeviceProfileService.java (81%) delete mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/DefaultTbDeviceProfileService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java rename application/src/main/java/org/thingsboard/server/service/entitiy/{entityRelation => entity/relation}/TbEntityRelationService.java (69%) delete mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/DefaultTbEntityRelationService.java rename application/src/main/java/org/thingsboard/server/service/entitiy/{entityView => entityview}/DefaultTbEntityViewService.java (56%) rename application/src/main/java/org/thingsboard/server/service/entitiy/{entityView => entityview}/TbEntityViewService.java (65%) create mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java rename application/src/main/java/org/thingsboard/server/service/entitiy/{otaPackageController => ota}/TbOtaPackageService.java (73%) delete mode 100644 application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java rename application/src/main/java/org/thingsboard/server/service/entitiy/{tenant_profile => tenant/profile}/DefaultTbTenantProfileService.java (54%) rename application/src/main/java/org/thingsboard/server/service/entitiy/{tenant_profile => tenant/profile}/TbTenantProfileService.java (68%) rename application/src/main/java/org/thingsboard/server/service/entitiy/{widgetsBundle => widgets/bundle}/DefaultWidgetsBundleService.java (55%) rename application/src/main/java/org/thingsboard/server/service/entitiy/{widgetsBundle => widgets/bundle}/TbWidgetsBundleService.java (68%) diff --git a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java index b0ed1ed01d..a9d20f88a2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java @@ -30,12 +30,14 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmInfo; import org.thingsboard.server.common.data.alarm.AlarmQuery; import org.thingsboard.server.common.data.alarm.AlarmSearchStatus; import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.alarm.AlarmStatus; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AlarmId; @@ -132,9 +134,15 @@ public class AlarmController extends BaseController { @RequestMapping(value = "/alarm", method = RequestMethod.POST) @ResponseBody public Alarm saveAlarm(@ApiParam(value = "A JSON value representing the alarm.") @RequestBody Alarm alarm) throws ThingsboardException { - alarm.setTenantId(getCurrentUser().getTenantId()); + alarm.setTenantId(getTenantId()); checkEntity(alarm.getId(), alarm, Resource.ALARM); - return tbAlarmService.save(alarm, getCurrentUser()); + try { + return tbAlarmService.save(alarm, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ALARM), alarm, actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Delete Alarm (deleteAlarm)", @@ -164,7 +172,11 @@ public class AlarmController extends BaseController { checkParameter(ALARM_ID, strAlarmId); AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); - tbAlarmService.ack(alarm, getCurrentUser()); + try { + tbAlarmService.ack(alarm, getCurrentUser()).get(); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Clear Alarm (clearAlarm)", @@ -178,7 +190,11 @@ public class AlarmController extends BaseController { checkParameter(ALARM_ID, strAlarmId); AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); - tbAlarmService.clear(alarm, getCurrentUser()); + try { + tbAlarmService.clear(alarm, getCurrentUser()).get(); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Get Alarms (getAlarms)", diff --git a/application/src/main/java/org/thingsboard/server/controller/AssetController.java b/application/src/main/java/org/thingsboard/server/controller/AssetController.java index 4718feb774..39a575949f 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AssetController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AssetController.java @@ -34,9 +34,11 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetInfo; import org.thingsboard.server.common.data.asset.AssetSearchQuery; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -144,12 +146,18 @@ public class AssetController extends BaseController { @RequestMapping(value = "/asset", method = RequestMethod.POST) @ResponseBody public Asset saveAsset(@ApiParam(value = "A JSON value representing the asset.") @RequestBody Asset asset) throws ThingsboardException { - if (TB_SERVICE_QUEUE.equals(asset.getType())) { - throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + try { + if (TB_SERVICE_QUEUE.equals(asset.getType())) { + throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + asset.setTenantId(getTenantId()); + checkEntity(asset.getId(), asset, Resource.ASSET); + return tbAssetService.save(asset, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), asset, actionType, getCurrentUser(), e); + throw handleException(e); } - asset.setTenantId(getCurrentUser().getTenantId()); - checkEntity(asset.getId(), asset, Resource.ASSET); - return tbAssetService.save(asset, getCurrentUser()); } @ApiOperation(value = "Delete asset (deleteAsset)", @@ -164,6 +172,8 @@ public class AssetController extends BaseController { Asset asset = checkAssetId(assetId, Operation.DELETE); tbAssetService.delete(asset, getCurrentUser()).get(); } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), ActionType.DELETED, + getCurrentUser(), e, strAssetId); throw handleException(e); } } @@ -175,13 +185,21 @@ public class AssetController extends BaseController { @ResponseBody public Asset assignAssetToCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable("customerId") String strCustomerId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - checkParameter("customerId", strCustomerId); - checkParameter(ASSET_ID, strAssetId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); - return tbAssetService.assignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); + try { + checkParameter("customerId", strCustomerId); + checkParameter(ASSET_ID, strAssetId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); + return tbAssetService.assignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, + getCurrentUser(), e, strAssetId, strCustomerId); + + throw handleException(e); + } } @ApiOperation(value = "Unassign asset from customer (unassignAssetFromCustomer)", @@ -190,14 +208,21 @@ public class AssetController extends BaseController { @RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE) @ResponseBody public Asset unassignAssetFromCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - checkParameter(ASSET_ID, strAssetId); - AssetId assetId = new AssetId(toUUID(strAssetId)); - Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER); - if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Asset isn't assigned to any customer!"); + try { + checkParameter(ASSET_ID, strAssetId); + AssetId assetId = new AssetId(toUUID(strAssetId)); + Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER); + if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Asset isn't assigned to any customer!"); + } + Customer customer = checkCustomerId(asset.getCustomerId(), Operation.READ); + return tbAssetService.unassignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, + getCurrentUser(), e, strAssetId); + throw handleException(e); } - Customer customer = checkCustomerId(asset.getCustomerId(), Operation.READ); - return tbAssetService.unassignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); } @ApiOperation(value = "Make asset publicly available (assignAssetToPublicCustomer)", @@ -208,10 +233,16 @@ public class AssetController extends BaseController { @RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST) @ResponseBody public Asset assignAssetToPublicCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - checkParameter(ASSET_ID, strAssetId); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); - return tbAssetService.assignAssetToPublicCustomer(getTenantId(), assetId, getCurrentUser()); + try { + checkParameter(ASSET_ID, strAssetId); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); + return tbAssetService.assignAssetToPublicCustomer(getTenantId(), assetId, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, getCurrentUser(), e, strAssetId); + throw handleException(e); + } } @ApiOperation(value = "Get Tenant Assets (getTenantAssets)", @@ -454,16 +485,23 @@ public class AssetController extends BaseController { @ResponseBody public Asset assignAssetToEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ASSET_ID, strAssetId); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ASSET_ID, strAssetId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.READ); - return tbAssetService.assignAssetToEdge(getTenantId(), assetId, edge, getCurrentUser()); + return tbAssetService.assignAssetToEdge(getTenantId(), assetId, edge, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_EDGE; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, + getCurrentUser(), e, strAssetId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Unassign asset from edge (unassignAssetFromEdge)", @@ -478,15 +516,22 @@ public class AssetController extends BaseController { @ResponseBody public Asset unassignAssetFromEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ASSET_ID, strAssetId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ASSET_ID, strAssetId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - Asset asset = checkAssetId(assetId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + Asset asset = checkAssetId(assetId, Operation.READ); - return tbAssetService.unassignAssetFromEdge(getTenantId(), asset, edge, getCurrentUser()); + return tbAssetService.unassignAssetFromEdge(getTenantId(), asset, edge, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, + getCurrentUser(), e, strAssetId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get assets assigned to edge (getEdgeAssets)", diff --git a/application/src/main/java/org/thingsboard/server/controller/BaseController.java b/application/src/main/java/org/thingsboard/server/controller/BaseController.java index 050745844b..0f8c40956e 100644 --- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java +++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java @@ -15,7 +15,6 @@ */ package org.thingsboard.server.controller; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.Getter; @@ -39,7 +38,6 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.EntityViewInfo; -import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.OtaPackage; import org.thingsboard.server.common.data.OtaPackageInfo; @@ -53,7 +51,6 @@ import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmInfo; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetInfo; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.edge.EdgeEventType; @@ -88,7 +85,6 @@ import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.plugin.ComponentType; import org.thingsboard.server.common.data.queue.Queue; -import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.rpc.Rpc; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainType; @@ -126,10 +122,10 @@ import org.thingsboard.server.exception.ThingsboardErrorResponseHandler; import org.thingsboard.server.queue.discovery.PartitionService; import org.thingsboard.server.queue.provider.TbQueueProducerProvider; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.action.EntityActionService; import org.thingsboard.server.service.component.ComponentDiscoveryService; import org.thingsboard.server.service.edge.EdgeNotificationService; import org.thingsboard.server.service.edge.rpc.EdgeRpcService; +import org.thingsboard.server.service.entitiy.TbNotificationEntityService; import org.thingsboard.server.service.ota.OtaPackageStateService; import org.thingsboard.server.service.profile.TbDeviceProfileCache; import org.thingsboard.server.service.resource.TbResourceService; @@ -276,7 +272,7 @@ public abstract class BaseController { protected EdgeRpcService edgeGrpcService; @Autowired - protected EntityActionService entityActionService; + protected TbNotificationEntityService notificationEntityService; @Autowired protected QueueService queueService; @@ -882,69 +878,10 @@ public abstract class BaseController { return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); } - protected void logEntityAction(I entityId, E entity, CustomerId customerId, - ActionType actionType, Exception e, Object... additionalInfo) throws ThingsboardException { - logEntityAction(getCurrentUser(), entityId, entity, customerId, actionType, e, additionalInfo); - } - - protected void logEntityAction(User user, I entityId, E entity, CustomerId customerId, - ActionType actionType, Exception e, Object... additionalInfo) throws ThingsboardException { - entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); - } - - public static Exception toException(Throwable error) { return error != null ? (Exception.class.isInstance(error) ? (Exception) error : new Exception(error)) : null; } - protected String entityToStr(E entity) { - try { - return json.writeValueAsString(json.valueToTree(entity)); - } catch (JsonProcessingException e) { - log.warn("[{}] Failed to convert entity to string!", entity, e); - } - return null; - } - - protected void sendRelationNotificationMsg(TenantId tenantId, EntityRelation relation, EdgeEventActionType action) { - try { - if (!relation.getFrom().getEntityType().equals(EntityType.EDGE) && - !relation.getTo().getEntityType().equals(EntityType.EDGE)) { - sendNotificationMsgToEdgeService(tenantId, null, null, json.writeValueAsString(relation), EdgeEventType.RELATION, action); - } - } catch (Exception e) { - log.warn("Failed to push relation to core: {}", relation, e); - } - } - - protected void sendDeleteNotificationMsg(TenantId tenantId, EntityId entityId, List edgeIds) { - sendDeleteNotificationMsg(tenantId, entityId, edgeIds, null); - } - - protected void sendDeleteNotificationMsg(TenantId tenantId, EntityId entityId, List edgeIds, String body) { - if (edgeIds != null && !edgeIds.isEmpty()) { - for (EdgeId edgeId : edgeIds) { - sendNotificationMsgToEdgeService(tenantId, edgeId, entityId, body, null, EdgeEventActionType.DELETED); - } - } - } - - protected void sendAlarmDeleteNotificationMsg(TenantId tenantId, EntityId entityId, List edgeIds, Alarm alarm) { - try { - sendDeleteNotificationMsg(tenantId, entityId, edgeIds, json.writeValueAsString(alarm)); - } catch (Exception e) { - log.warn("Failed to push delete alarm msg to core: {}", alarm, e); - } - } - - protected void sendEntityAssignToCustomerNotificationMsg(TenantId tenantId, EntityId entityId, CustomerId customerId, EdgeEventActionType action) { - try { - sendNotificationMsgToEdgeService(tenantId, null, entityId, json.writeValueAsString(customerId), null, action); - } catch (Exception e) { - log.warn("Failed to push assign/unassign to/from customer to core: {}", customerId, e); - } - } - protected void sendEntityNotificationMsg(TenantId tenantId, EntityId entityId, EdgeEventActionType action) { sendNotificationMsgToEdgeService(tenantId, null, entityId, null, null, action); } diff --git a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java index 4ebcde7d36..6979f0f0a6 100644 --- a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java +++ b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java @@ -32,6 +32,8 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; @@ -143,9 +145,16 @@ public class CustomerController extends BaseController { @RequestMapping(value = "/customer", method = RequestMethod.POST) @ResponseBody public Customer saveCustomer(@ApiParam(value = "A JSON value representing the customer.") @RequestBody Customer customer) throws ThingsboardException { - customer.setTenantId(getTenantId()); - checkEntity(customer.getId(), customer, Resource.CUSTOMER); - return tbCustomerService.save(customer, getCurrentUser()); + try { + customer.setTenantId(getTenantId()); + checkEntity(customer.getId(), customer, Resource.CUSTOMER); + return tbCustomerService.save(customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.CUSTOMER), customer, + actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Delete Customer (deleteCustomer)", @@ -157,12 +166,14 @@ public class CustomerController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void deleteCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException { - checkParameter(CUSTOMER_ID, strCustomerId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.DELETE); try { + checkParameter(CUSTOMER_ID, strCustomerId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.DELETE); tbCustomerService.delete(customer, getCurrentUser()); } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.CUSTOMER), ActionType.DELETED, + getCurrentUser(), e, strCustomerId); throw handleException(e); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java index 47acdc64a4..c8e1d6408e 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java @@ -39,10 +39,12 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.HomeDashboard; import org.thingsboard.server.common.data.HomeDashboardInfo; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -181,9 +183,16 @@ public class DashboardController extends BaseController { public Dashboard saveDashboard( @ApiParam(value = "A JSON value representing the dashboard.") @RequestBody Dashboard dashboard) throws ThingsboardException { - dashboard.setTenantId(getTenantId()); - checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD); - return tbDashboardService.save(dashboard, getCurrentUser()); + try { + dashboard.setTenantId(getTenantId()); + checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD); + return tbDashboardService.save(dashboard, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), dashboard, + actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Delete the Dashboard (deleteDashboard)", @@ -194,10 +203,16 @@ public class DashboardController extends BaseController { public void deleteDashboard( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE); - tbDashboardService.delete(dashboard, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE); + tbDashboardService.delete(dashboard, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), ActionType.DELETED, + getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Assign the Dashboard (assignDashboardToCustomer)", @@ -212,15 +227,22 @@ public class DashboardController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter(CUSTOMER_ID, strCustomerId); - checkParameter(DASHBOARD_ID, strDashboardId); + try { + checkParameter(CUSTOMER_ID, strCustomerId); + checkParameter(DASHBOARD_ID, strDashboardId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - return tbDashboardService.assignDashboardToCustomer(dashboardId, customer, getCurrentUser()); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + return tbDashboardService.assignDashboardToCustomer(dashboard, customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, + getCurrentUser(), e, strDashboardId, strCustomerId); + throw handleException(e); + } } @ApiOperation(value = "Unassign the Dashboard (unassignDashboardFromCustomer)", @@ -235,13 +257,20 @@ public class DashboardController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter("customerId", strCustomerId); - checkParameter(DASHBOARD_ID, strDashboardId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - return tbDashboardService.unassignDashboardFromCustomer(dashboard, customer, getCurrentUser()); + try { + checkParameter("customerId", strCustomerId); + checkParameter(DASHBOARD_ID, strDashboardId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + return tbDashboardService.unassignDashboardFromCustomer(dashboard, customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), + actionType, getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Update the Dashboard Customers (updateDashboardCustomers)", @@ -258,11 +287,18 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids, or empty to remove all customers") @RequestBody(required = false) String[] strCustomerIds) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.updateDashboardCustomers(dashboard, customerIds, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.updateDashboardCustomers(dashboard, customerIds, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, + getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Adds the Dashboard Customers (addDashboardCustomers)", @@ -278,11 +314,18 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids") @RequestBody String[] strCustomerIds) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.addDashboardCustomers(dashboard, customerIds, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.addDashboardCustomers(dashboard, customerIds, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), + actionType, getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Remove the Dashboard Customers (removeDashboardCustomers)", @@ -298,11 +341,18 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids") @RequestBody String[] strCustomerIds) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.removeDashboardCustomers(dashboard, customerIds, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.removeDashboardCustomers(dashboard, customerIds, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), + actionType, getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Assign the Dashboard to Public Customer (assignDashboardToPublicCustomer)", @@ -319,10 +369,17 @@ public class DashboardController extends BaseController { public Dashboard assignDashboardToPublicCustomer( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - return tbDashboardService.assignDashboardToPublicCustomer(dashboardId, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + return tbDashboardService.assignDashboardToPublicCustomer(dashboard, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), + actionType, getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Unassign the Dashboard from Public Customer (unassignDashboardFromPublicCustomer)", @@ -335,10 +392,17 @@ public class DashboardController extends BaseController { public Dashboard unassignDashboardFromPublicCustomer( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - return tbDashboardService.unassignDashboardFromPublicCustomer(dashboard, getCurrentUser()); + try { + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + return tbDashboardService.unassignDashboardFromPublicCustomer(dashboard, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, + getCurrentUser(), e, strDashboardId); + throw handleException(e); + } } @ApiOperation(value = "Get Tenant Dashboards by System Administrator (getTenantDashboards)", @@ -623,15 +687,22 @@ public class DashboardController extends BaseController { @ResponseBody public Dashboard assignDashboardToEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter("edgeId", strEdgeId); - checkParameter(DASHBOARD_ID, strDashboardId); + try { + checkParameter("edgeId", strEdgeId); + checkParameter(DASHBOARD_ID, strDashboardId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - checkDashboardId(dashboardId, Operation.READ); - return tbDashboardService.asignDashboardToEdge(dashboardId, edge, getCurrentUser()); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + checkDashboardId(dashboardId, Operation.READ); + return tbDashboardService.asignDashboardToEdge(getTenantId(), dashboardId, edge, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_EDGE; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + actionType, getCurrentUser(), e, strDashboardId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Unassign dashboard from edge (unassignDashboardFromEdge)", @@ -647,16 +718,23 @@ public class DashboardController extends BaseController { @ResponseBody public Dashboard unassignDashboardFromEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DASHBOARD_ID, strDashboardId); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DASHBOARD_ID, strDashboardId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.READ); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.READ); - return tbDashboardService.unassignDashboardFromEdge(dashboard, edge, getCurrentUser()); + return tbDashboardService.unassignDashboardFromEdge(dashboard, edge, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), + actionType, getCurrentUser(), e, strDashboardId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get Edge Dashboards (getEdgeDashboards)", @@ -704,7 +782,7 @@ public class DashboardController extends BaseController { } } - private Set customerIdFromStr(String [] strCustomerIds, Dashboard dashboard) { + private Set customerIdFromStr(String[] strCustomerIds, Dashboard dashboard) { Set customerIds = new HashSet<>(); if (strCustomerIds != null) { for (String strCustomerId : strCustomerIds) { diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java index 793ea64336..04b2b31b00 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java @@ -43,8 +43,10 @@ import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceInfo; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.device.DeviceSearchQuery; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; @@ -166,14 +168,20 @@ public class DeviceController extends BaseController { public Device saveDevice(@ApiParam(value = "A JSON value representing the device.") @RequestBody Device device, @ApiParam(value = "Optional value of the device credentials to be used during device creation. " + "If omitted, access token will be auto-generated.") @RequestParam(name = "accessToken", required = false) String accessToken) throws ThingsboardException { - device.setTenantId(getCurrentUser().getTenantId()); - Device oldDevice = null; - if (device.getId() != null) { - oldDevice = checkDeviceId(device.getId(), Operation.WRITE); - } else { - checkEntity(null, device, Resource.DEVICE); + try { + device.setTenantId(getCurrentUser().getTenantId()); + Device oldDevice = null; + if (device.getId() != null) { + oldDevice = checkDeviceId(device.getId(), Operation.WRITE); + } else { + checkEntity(null, device, Resource.DEVICE); + } + return tbDeviceService.save(getTenantId(), device, oldDevice, accessToken, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), device, actionType, getCurrentUser(), e); + throw handleException(e); } - return tbDeviceService.save(getTenantId(), device, oldDevice, accessToken, getCurrentUser()); } @ApiOperation(value = "Create Device (saveDevice) with credentials ", @@ -188,13 +196,19 @@ public class DeviceController extends BaseController { public Device saveDeviceWithCredentials(@ApiParam(value = "The JSON object with device and credentials. See method description above for example.") @RequestBody SaveDeviceWithCredentialsRequest deviceAndCredentials) throws ThingsboardException { Device device = checkNotNull(deviceAndCredentials.getDevice()); - DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials()); - device.setTenantId(getCurrentUser().getTenantId()); - checkEntity(device.getId(), device, Resource.DEVICE); - return tbDeviceService.saveDeviceWithCredentials(getTenantId(), device, credentials, getCurrentUser()); + try { + DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials()); + device.setTenantId(getCurrentUser().getTenantId()); + checkEntity(device.getId(), device, Resource.DEVICE); + return tbDeviceService.saveDeviceWithCredentials(getTenantId(), device, credentials, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), device, + actionType, getCurrentUser(), e); + throw handleException(e); + } } - @ApiOperation(value = "Delete device (deleteDevice)", notes = "Deletes the device, it's credentials and all the relations (from and to the device). Referencing non-existing device Id will cause an error." + TENANT_AUTHORITY_PARAGRAPH) @PreAuthorize("hasAuthority('TENANT_ADMIN')") @@ -202,12 +216,14 @@ public class DeviceController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void deleteDevice(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.DELETE); try { + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.DELETE); tbDeviceService.delete(device, getCurrentUser()).get(); } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), ActionType.DELETED, + getCurrentUser(), e, strDeviceId); throw handleException(e); } } @@ -221,13 +237,20 @@ public class DeviceController extends BaseController { @PathVariable("customerId") String strCustomerId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter("customerId", strCustomerId); - checkParameter(DEVICE_ID, strDeviceId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); - return tbDeviceService.assignDeviceToCustomer(getTenantId(), deviceId, customer, getCurrentUser()); + try { + checkParameter("customerId", strCustomerId); + checkParameter(DEVICE_ID, strDeviceId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); + return tbDeviceService.assignDeviceToCustomer(getTenantId(), deviceId, customer, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, getCurrentUser(), + e, strDeviceId, strCustomerId); + throw handleException(e); + } } @ApiOperation(value = "Unassign device from customer (unassignDeviceFromCustomer)", @@ -249,6 +272,9 @@ public class DeviceController extends BaseController { return tbDeviceService.unassignDeviceFromCustomer(device, customer, getCurrentUser()); } catch (Exception e) { + ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, + getCurrentUser(), e, strDeviceId); throw handleException(e); } } @@ -262,10 +288,17 @@ public class DeviceController extends BaseController { @ResponseBody public Device assignDeviceToPublicCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); - return tbDeviceService.assignDeviceToPublicCustomer(getTenantId(), deviceId, getCurrentUser()); + try { + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); + return tbDeviceService.assignDeviceToPublicCustomer(getTenantId(), deviceId, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, + getCurrentUser(), e, strDeviceId); + throw handleException(e); + } } @ApiOperation(value = "Get Device Credentials (getDeviceCredentialsByDeviceId)", @@ -275,10 +308,16 @@ public class DeviceController extends BaseController { @ResponseBody public DeviceCredentials getDeviceCredentialsByDeviceId(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS); - return tbDeviceService.getDeviceCredentialsByDeviceId(device, getCurrentUser()); + try { + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS); + return tbDeviceService.getDeviceCredentialsByDeviceId(device, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + ActionType.CREDENTIALS_READ, getCurrentUser(), e, strDeviceId); + throw handleException(e); + } } @ApiOperation(value = "Update device credentials (updateDeviceCredentials)", notes = "During device creation, platform generates random 'ACCESS_TOKEN' credentials. " + @@ -291,9 +330,15 @@ public class DeviceController extends BaseController { public DeviceCredentials updateDeviceCredentials( @ApiParam(value = "A JSON value representing the device credentials.") @RequestBody DeviceCredentials deviceCredentials) throws ThingsboardException { - checkNotNull(deviceCredentials); - Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); - return tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser()); + try { + checkNotNull(deviceCredentials); + Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); + return tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + ActionType.CREDENTIALS_UPDATED, getCurrentUser(), e, deviceCredentials); + throw handleException(e); + } } @ApiOperation(value = "Get Tenant Devices (getTenantDevices)", @@ -552,43 +597,47 @@ public class DeviceController extends BaseController { @PathVariable(DEVICE_NAME) String deviceName, @ApiParam(value = "Claiming request which can optionally contain secret key") @RequestBody(required = false) ClaimRequest claimRequest) throws ThingsboardException { - checkParameter(DEVICE_NAME, deviceName); - final DeferredResult deferredResult = new DeferredResult<>(); + try { + checkParameter(DEVICE_NAME, deviceName); + final DeferredResult deferredResult = new DeferredResult<>(); - SecurityUser user = getCurrentUser(); - TenantId tenantId = user.getTenantId(); - CustomerId customerId = user.getCustomerId(); - - Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); - accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, - device.getId(), device); - String secretKey = getSecretKey(claimRequest); - - ListenableFuture future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user); - - Futures.addCallback(future, new FutureCallback() { - @Override - public void onSuccess(@Nullable ClaimResult result) { - HttpStatus status; - if (result != null) { - if (result.getResponse().equals(ClaimResponse.SUCCESS)) { - status = HttpStatus.OK; - deferredResult.setResult(new ResponseEntity<>(result, status)); + SecurityUser user = getCurrentUser(); + TenantId tenantId = user.getTenantId(); + CustomerId customerId = user.getCustomerId(); + + Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); + accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, + device.getId(), device); + String secretKey = getSecretKey(claimRequest); + + ListenableFuture future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user); + + Futures.addCallback(future, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable ClaimResult result) { + HttpStatus status; + if (result != null) { + if (result.getResponse().equals(ClaimResponse.SUCCESS)) { + status = HttpStatus.OK; + deferredResult.setResult(new ResponseEntity<>(result, status)); + } else { + status = HttpStatus.BAD_REQUEST; + deferredResult.setResult(new ResponseEntity<>(result.getResponse(), status)); + } } else { - status = HttpStatus.BAD_REQUEST; - deferredResult.setResult(new ResponseEntity<>(result.getResponse(), status)); + deferredResult.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); } - } else { - deferredResult.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); } - } - @Override - public void onFailure(Throwable t) { - deferredResult.setErrorResult(t); - } - }, MoreExecutors.directExecutor()); - return deferredResult; + @Override + public void onFailure(Throwable t) { + deferredResult.setErrorResult(t); + } + }, MoreExecutors.directExecutor()); + return deferredResult; + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Reclaim device (reClaimDevice)", @@ -645,17 +694,23 @@ public class DeviceController extends BaseController { @PathVariable(TENANT_ID) String strTenantId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(TENANT_ID, strTenantId); - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT); + try { + checkParameter(TENANT_ID, strTenantId); + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT); - TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId)); - Tenant newTenant = tenantService.findTenantById(newTenantId); - if (newTenant == null) { - throw new ThingsboardException("Could not find the specified Tenant!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId)); + Tenant newTenant = tenantService.findTenantById(newTenantId); + if (newTenant == null) { + throw new ThingsboardException("Could not find the specified Tenant!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); + } + return tbDeviceService.assignDeviceToTenant(device, newTenant, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + ActionType.ASSIGNED_TO_TENANT, getCurrentUser(), e, strDeviceId); + throw handleException(e); } - return tbDeviceService.assignDeviceToTenant(device, newTenant, getCurrentUser()); } @ApiOperation(value = "Assign device to edge (assignDeviceToEdge)", @@ -672,15 +727,21 @@ public class DeviceController extends BaseController { @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DEVICE_ID, strDeviceId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DEVICE_ID, strDeviceId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.READ); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.READ); - return tbDeviceService.assignDeviceToEdge(getTenantId(), deviceId, edge, getCurrentUser()); + return tbDeviceService.assignDeviceToEdge(getTenantId(), deviceId, edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strDeviceId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Unassign device from edge (unassignDeviceFromEdge)", @@ -697,14 +758,20 @@ public class DeviceController extends BaseController { @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DEVICE_ID, strDeviceId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DEVICE_ID, strDeviceId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.READ); - return tbDeviceService.unassignDeviceFromEdge(device, edge, getCurrentUser()); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.READ); + return tbDeviceService.unassignDeviceFromEdge(device, edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), + ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strDeviceId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get devices assigned to edge (getEdgeDevices)", diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java index c9330c0a77..95961131e8 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java @@ -33,13 +33,15 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfileInfo; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.deviceProfile.TbDeviceProfileService; +import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; @@ -71,7 +73,7 @@ import static org.thingsboard.server.controller.ControllerConstants.UUID_WIKI_LI @Slf4j public class DeviceProfileController extends BaseController { - private final TbDeviceProfileService tbDeviceProfileService; + private final TbDeviceProfileService tbDeviceProfileService; @Autowired private TimeseriesService timeseriesService; @@ -200,9 +202,16 @@ public class DeviceProfileController extends BaseController { public DeviceProfile saveDeviceProfile( @ApiParam(value = "A JSON value representing the device profile.") @RequestBody DeviceProfile deviceProfile) throws ThingsboardException { - deviceProfile.setTenantId(getTenantId()); - checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE); - return tbDeviceProfileService.save(deviceProfile, getCurrentUser()); + try { + deviceProfile.setTenantId(getTenantId()); + checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE); + return tbDeviceProfileService.save(deviceProfile, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), deviceProfile, + actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Delete device profile (deleteDeviceProfile)", @@ -215,11 +224,17 @@ public class DeviceProfileController extends BaseController { public void deleteDeviceProfile( @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { - checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); - DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); - DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE); - tbDeviceProfileService.delete(deviceProfile, getCurrentUser()); - } + try { + checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); + DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); + DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE); + tbDeviceProfileService.delete(deviceProfile, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), ActionType.DELETED, + getCurrentUser(), e, strDeviceProfileId); + throw handleException(e); + } + } @ApiOperation(value = "Make Device Profile Default (setDefaultDeviceProfile)", notes = "Marks device profile as default within a tenant scope." + TENANT_AUTHORITY_PARAGRAPH, @@ -230,11 +245,17 @@ public class DeviceProfileController extends BaseController { public DeviceProfile setDefaultDeviceProfile( @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { - checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); - DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); - DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE); - DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId()); - return tbDeviceProfileService.setDefaultDeviceProfile(deviceProfile, previousDefaultDeviceProfile, getCurrentUser()); + try { + checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); + DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); + DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE); + DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId()); + return tbDeviceProfileService.setDefaultDeviceProfile(deviceProfile, previousDefaultDeviceProfile, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), ActionType.UPDATED, + getCurrentUser(), e, strDeviceProfileId); + throw handleException(e); + } } @ApiOperation(value = "Get Device Profiles (getDeviceProfiles)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java index 5d9737db23..4e66eb17e2 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java @@ -34,6 +34,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeInfo; import org.thingsboard.server.common.data.edge.EdgeSearchQuery; @@ -148,23 +150,29 @@ public class EdgeController extends BaseController { @ResponseBody public Edge saveEdge(@ApiParam(value = "A JSON value representing the edge.", required = true) @RequestBody Edge edge) throws ThingsboardException { - TenantId tenantId = getCurrentUser().getTenantId(); - edge.setTenantId(tenantId); - boolean created = edge.getId() == null; - - RuleChain edgeTemplateRootRuleChain = null; - if (created) { - edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId); - if (edgeTemplateRootRuleChain == null) { - throw new DataValidationException("Root edge rule chain is not available!"); + TenantId tenantId = getTenantId(); + try { + edge.setTenantId(tenantId); + boolean created = edge.getId() == null; + + RuleChain edgeTemplateRootRuleChain = null; + if (created) { + edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId); + if (edgeTemplateRootRuleChain == null) { + throw new DataValidationException("Root edge rule chain is not available!"); + } } - } - Operation operation = created ? Operation.CREATE : Operation.WRITE; + Operation operation = created ? Operation.CREATE : Operation.WRITE; - accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation, edge.getId(), edge); + accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation, edge.getId(), edge); - return tbEdgeService.save(edge, edgeTemplateRootRuleChain, getCurrentUser()); + return tbEdgeService.save(edge, edgeTemplateRootRuleChain, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), edge, actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Delete edge (deleteEdge)", @@ -174,10 +182,16 @@ public class EdgeController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void deleteEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.DELETE); - tbEdgeService.delete(edge, getCurrentUser()); + try { + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.DELETE); + tbEdgeService.delete(edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), ActionType.DELETED, + getCurrentUser(), e, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get Tenant Edges (getEdges)", @@ -215,13 +229,19 @@ public class EdgeController extends BaseController { @PathVariable("customerId") String strCustomerId, @ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - checkParameter("customerId", strCustomerId); - checkParameter(EDGE_ID, strEdgeId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); - return tbEdgeService.assignEdgeToCustomer(getTenantId(), edgeId, customer, getCurrentUser()); + try { + checkParameter("customerId", strCustomerId); + checkParameter(EDGE_ID, strEdgeId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); + return tbEdgeService.assignEdgeToCustomer(getTenantId(), edgeId, customer, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), + ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEdgeId, strCustomerId); + throw handleException(e); + } } @ApiOperation(value = "Unassign edge from customer (unassignEdgeFromCustomer)", @@ -232,15 +252,21 @@ public class EdgeController extends BaseController { @ResponseBody public Edge unassignEdgeFromCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER); - if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Edge isn't assigned to any customer!"); - } - Customer customer = checkCustomerId(edge.getCustomerId(), Operation.READ); + try { + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER); + if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Edge isn't assigned to any customer!"); + } + Customer customer = checkCustomerId(edge.getCustomerId(), Operation.READ); - return tbEdgeService.unassignEdgeFromCustomer(edge, customer, getCurrentUser()); + return tbEdgeService.unassignEdgeFromCustomer(edge, customer, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), + ActionType.UNASSIGNED_FROM_CUSTOMER, getCurrentUser(), e, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Make edge publicly available (assignEdgeToPublicCustomer)", @@ -253,10 +279,16 @@ public class EdgeController extends BaseController { @ResponseBody public Edge assignEdgeToPublicCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); - return tbEdgeService.assignEdgeToPublicCustomer(getTenantId(), edgeId, getCurrentUser()); + try { + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); + return tbEdgeService.assignEdgeToPublicCustomer(getTenantId(), edgeId, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), + ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get Tenant Edges (getTenantEdges)", @@ -352,14 +384,20 @@ public class EdgeController extends BaseController { @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION, required = true) @PathVariable("ruleChainId") String strRuleChainId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter("ruleChainId", strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - checkRuleChain(ruleChainId, Operation.WRITE); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); - accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge); - return tbEdgeService.setEdgeRootRuleChain(edge, ruleChainId, getCurrentUser()); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter("ruleChainId", strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + checkRuleChain(ruleChainId, Operation.WRITE); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); + accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge); + return tbEdgeService.setEdgeRootRuleChain(edge, ruleChainId, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), + ActionType.UPDATED, getCurrentUser(), e, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Get Customer Edges (getCustomerEdges)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java index 0a873aaa18..e35dd59985 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java @@ -28,6 +28,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityIdFactory; @@ -36,7 +37,7 @@ import org.thingsboard.server.common.data.relation.EntityRelationInfo; import org.thingsboard.server.common.data.relation.EntityRelationsQuery; import org.thingsboard.server.common.data.relation.RelationTypeGroup; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.entityRelation.TbEntityRelationService; +import org.thingsboard.server.service.entitiy.entity.relation.TbEntityRelationService; import org.thingsboard.server.service.security.permission.Operation; import java.util.List; @@ -54,7 +55,7 @@ import static org.thingsboard.server.controller.ControllerConstants.RELATION_TYP @RequiredArgsConstructor public class EntityRelationController extends BaseController { - private final TbEntityRelationService tbEntityRelationService; + private final TbEntityRelationService tbEntityRelationService; public static final String TO_TYPE = "toType"; public static final String FROM_ID = "fromId"; @@ -79,14 +80,22 @@ public class EntityRelationController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void saveRelation(@ApiParam(value = "A JSON value representing the relation.", required = true) @RequestBody EntityRelation relation) throws ThingsboardException { - checkNotNull(relation); - checkEntityId(relation.getFrom(), Operation.WRITE); - checkEntityId(relation.getTo(), Operation.WRITE); - if (relation.getTypeGroup() == null) { - relation.setTypeGroup(RelationTypeGroup.COMMON); - } + try { + checkNotNull(relation); + checkEntityId(relation.getFrom(), Operation.WRITE); + checkEntityId(relation.getTo(), Operation.WRITE); + if (relation.getTypeGroup() == null) { + relation.setTypeGroup(RelationTypeGroup.COMMON); + } - tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); + tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), relation.getFrom(), null, getCurrentUser().getCustomerId(), + ActionType.RELATION_ADD_OR_UPDATE, getCurrentUser(), e, relation); + notificationEntityService.logEntityAction(getTenantId(), relation.getTo(), null, getCurrentUser().getCustomerId(), + ActionType.RELATION_ADD_OR_UPDATE, getCurrentUser(), e, relation); + throw handleException(e); + } } @ApiOperation(value = "Delete Relation (deleteRelation)", @@ -111,8 +120,15 @@ public class EntityRelationController extends BaseController { checkEntityId(toId, Operation.WRITE); RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup); - - tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); + try { + tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), relation.getFrom(), null, getCurrentUser().getCustomerId(), + ActionType.RELATION_DELETED, getCurrentUser(), e, relation); + notificationEntityService.logEntityAction(getTenantId(), relation.getTo(), null, getCurrentUser().getCustomerId(), + ActionType.RELATION_DELETED, getCurrentUser(), e, relation); + throw handleException(e); + } } @ApiOperation(value = "Delete Relations (deleteRelations)", @@ -127,7 +143,13 @@ public class EntityRelationController extends BaseController { checkParameter("entityType", strType); EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId); checkEntityId(entityId, Operation.WRITE); - tbEntityRelationService.deleteRelations (getTenantId(), getCurrentUser().getCustomerId(), entityId, getCurrentUser()); + try { + tbEntityRelationService.deleteRelations(getTenantId(), getCurrentUser().getCustomerId(), entityId, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), entityId, null, getCurrentUser().getCustomerId(), + ActionType.RELATIONS_DELETED, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Get Relation (getRelation)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java index a7089969c3..ef3ced46b8 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java @@ -33,8 +33,10 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.EntityViewInfo; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -48,7 +50,7 @@ import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.exception.IncorrectParameterException; import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.entityView.TbEntityViewService; +import org.thingsboard.server.service.entitiy.entityview.TbEntityViewService; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; @@ -140,15 +142,22 @@ public class EntityViewController extends BaseController { public EntityView saveEntityView( @ApiParam(value = "A JSON object representing the entity view.") @RequestBody EntityView entityView) throws ThingsboardException { - entityView.setTenantId(getCurrentUser().getTenantId()); - EntityView existingEntityView = null; - if (entityView.getId() == null) { - accessControlService - .checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView); - } else { - existingEntityView = checkEntityViewId(entityView.getId(), Operation.WRITE); + try { + entityView.setTenantId(getCurrentUser().getTenantId()); + EntityView existingEntityView = null; + if (entityView.getId() == null) { + accessControlService + .checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView); + } else { + existingEntityView = checkEntityViewId(entityView.getId(), Operation.WRITE); + } + return tbEntityViewService.save(entityView, existingEntityView, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), entityView, + actionType, getCurrentUser(), e); + throw handleException(e); } - return tbEntityViewService.save(entityView, existingEntityView, getCurrentUser()); } @ApiOperation(value = "Delete entity view (deleteEntityView)", @@ -161,9 +170,15 @@ public class EntityViewController extends BaseController { @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); - tbEntityViewService.delete(entityView, getCurrentUser()); + try { + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); + tbEntityViewService.delete(entityView, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.DELETED, getCurrentUser(), e, strEntityViewId); + throw handleException(e); + } } @ApiOperation(value = "Get Entity View by name (getTenantEntityView)", @@ -193,16 +208,22 @@ public class EntityViewController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - checkParameter(CUSTOMER_ID, strCustomerId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + try { + checkParameter(CUSTOMER_ID, strCustomerId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); - return tbEntityViewService.assignEntityViewToCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); + return tbEntityViewService.assignEntityViewToCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEntityViewId, strCustomerId); + throw handleException(e); + } } @ApiOperation(value = "Unassign Entity View from customer (unassignEntityViewFromCustomer)", @@ -213,16 +234,22 @@ public class EntityViewController extends BaseController { public EntityView unassignEntityViewFromCustomer( @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER); - if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Entity View isn't assigned to any customer!"); - } + try { + checkParameter(ENTITY_VIEW_ID, strEntityViewId); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER); + if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Entity View isn't assigned to any customer!"); + } - Customer customer = checkCustomerId(entityView.getCustomerId(), Operation.READ); + Customer customer = checkCustomerId(entityView.getCustomerId(), Operation.READ); - return tbEntityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); + return tbEntityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.UNASSIGNED_FROM_CUSTOMER, getCurrentUser(), e, strEntityViewId); + throw handleException(e); + } } @ApiOperation(value = "Get Customer Entity Views (getCustomerEntityViews)", @@ -421,14 +448,20 @@ public class EntityViewController extends BaseController { public EntityView assignEntityViewToPublicCustomer( @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); + try { + checkParameter(ENTITY_VIEW_ID, strEntityViewId); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); - Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId()); + Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId()); - return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(), - publicCustomer, entityViewId, getCurrentUser()); + return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(), + publicCustomer, entityViewId, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEntityViewId); + throw handleException(e); + } } @ApiOperation(value = "Assign entity view to edge (assignEntityViewToEdge)", @@ -443,16 +476,23 @@ public class EntityViewController extends BaseController { @ResponseBody public EntityView assignEntityViewToEdge(@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.READ); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.READ); - return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(), entityViewId, edge, getCurrentUser()); + return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(), + entityViewId, edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strEntityViewId, strEdgeId); + throw handleException(e); + } } @ApiOperation(value = "Unassign entity view from edge (unassignEntityViewFromEdge)", @@ -467,16 +507,23 @@ public class EntityViewController extends BaseController { @ResponseBody public EntityView unassignEntityViewFromEdge(@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + try { + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.READ); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.READ); - return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView, edge, getCurrentUser()); + return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView, + edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), + ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strEntityViewId, strEdgeId); + throw handleException(e); + } } @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") diff --git a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java index ba3845127d..f311ed0cf0 100644 --- a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java +++ b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java @@ -32,9 +32,11 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.OtaPackage; import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.OtaPackageId; @@ -43,7 +45,7 @@ import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.otaPackageController.TbOtaPackageService; +import org.thingsboard.server.service.entitiy.ota.TbOtaPackageService; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; @@ -154,12 +156,17 @@ public class OtaPackageController extends BaseController { @ResponseBody public OtaPackageInfo saveOtaPackageInfo(@ApiParam(value = "A JSON value representing the OTA Package.") @RequestBody SaveOtaPackageInfoRequest otaPackageInfo) throws ThingsboardException { - otaPackageInfo.setTenantId(getTenantId()); - checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE); - - return tbOtaPackageService.save(otaPackageInfo, getCurrentUser()); - + try { + otaPackageInfo.setTenantId(getTenantId()); + checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE); + return tbOtaPackageService.save(otaPackageInfo, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = otaPackageInfo.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), otaPackageInfo, + actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Save OTA Package data (saveOtaPackageData)", @@ -177,16 +184,18 @@ public class OtaPackageController extends BaseController { @RequestParam(CHECKSUM_ALGORITHM) String checksumAlgorithmStr, @ApiParam(value = "OTA Package data.") @RequestPart MultipartFile file) throws ThingsboardException { - checkParameter(OTA_PACKAGE_ID, strOtaPackageId); - checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr); - OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); - OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ); try { + checkParameter(OTA_PACKAGE_ID, strOtaPackageId); + checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr); + OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); + OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ); ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase()); byte[] data = file.getBytes(); return tbOtaPackageService.saveOtaPackageData(otaPackageInfo, checksum, checksumAlgorithm, - data, file.getOriginalFilename(), file.getContentType(), getCurrentUser()); + data, file.getOriginalFilename(), file.getContentType(), getCurrentUser()); } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), ActionType.UPDATED, + getCurrentUser(), e, strOtaPackageId); throw handleException(e); } } @@ -257,11 +266,17 @@ public class OtaPackageController extends BaseController { @ResponseBody public void deleteOtaPackage(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION) @PathVariable("otaPackageId") String strOtaPackageId) throws ThingsboardException { - checkParameter(OTA_PACKAGE_ID, strOtaPackageId); - OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); - OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.DELETE); + try { + checkParameter(OTA_PACKAGE_ID, strOtaPackageId); + OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); + OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.DELETE); - tbOtaPackageService.delete(otaPackageInfo, getCurrentUser()); + tbOtaPackageService.delete(otaPackageInfo, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), + ActionType.DELETED, getCurrentUser(), e, strOtaPackageId); + throw handleException(e); + } } } diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java index 190d68e79e..429a573829 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java +++ b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java @@ -40,8 +40,10 @@ import org.thingsboard.rule.engine.api.ScriptEngine; import org.thingsboard.server.actors.ActorSystemContext; import org.thingsboard.server.actors.tenant.DebugTbRateLimits; import org.thingsboard.server.common.data.DataConstants; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Event; import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EdgeId; @@ -233,11 +235,17 @@ public class RuleChainController extends BaseController { public RuleChain saveRuleChain( @ApiParam(value = "A JSON value representing the rule chain.") @RequestBody RuleChain ruleChain) throws ThingsboardException { - - ruleChain.setTenantId(getCurrentUser().getTenantId()); - checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN); - return tbRuleChainService.save(ruleChain, getCurrentUser()); - } + try { + ruleChain.setTenantId(getCurrentUser().getTenantId()); + checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN); + return tbRuleChainService.save(ruleChain, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ruleChain, + actionType, getCurrentUser(), e); + throw handleException(e); + } + } @ApiOperation(value = "Create Default Rule Chain", notes = "Create rule chain from template, based on the specified name in the request. " + @@ -248,11 +256,18 @@ public class RuleChainController extends BaseController { public RuleChain saveRuleChain( @ApiParam(value = "A JSON value representing the request.") @RequestBody DefaultRuleChainCreateRequest request) throws ThingsboardException { - - checkNotNull(request); - checkParameter(request.getName(), "name"); - return tbRuleChainService.saveDefaultByName(getTenantId(), request, getCurrentUser()); - } + try { + checkNotNull(request); + checkParameter(request.getName(), "name"); + return tbRuleChainService.saveDefaultByName(getTenantId(), request, getCurrentUser()); + } catch (Exception e) { + RuleChain ruleChain = new RuleChain(); + ruleChain.setName(request.getName()); + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ruleChain, + ActionType.ADDED, getCurrentUser(), e); + throw handleException(e); + } + } @ApiOperation(value = "Set Root Rule Chain (setRootRuleChain)", notes = "Makes the rule chain to be root rule chain. Updates previous root rule chain as well. " + TENANT_AUTHORITY_PARAGRAPH) @@ -262,11 +277,16 @@ public class RuleChainController extends BaseController { public RuleChain setRootRuleChain( @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setRootRuleChain(getTenantId(),ruleChain, getCurrentUser()); - + try { + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + getCurrentUser(), e, strRuleChainId); + throw handleException(e); + } } @ApiOperation(value = "Update Rule Chain Metadata", @@ -280,19 +300,24 @@ public class RuleChainController extends BaseController { @ApiParam(value = "Update related rule nodes.") @RequestParam(value = "updateRelated", required = false, defaultValue = "true") boolean updateRelated ) throws ThingsboardException { - TenantId tenantId = getTenantId(); - if (debugPerTenantEnabled) { - ConcurrentMap debugPerTenantLimits = actorContext.getDebugPerTenantLimits(); - DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null); - if (debugTbRateLimits != null) { - debugPerTenantLimits.remove(tenantId, debugTbRateLimits); + try { + TenantId tenantId = getTenantId(); + if (debugPerTenantEnabled) { + ConcurrentMap debugPerTenantLimits = actorContext.getDebugPerTenantLimits(); + DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null); + if (debugTbRateLimits != null) { + debugPerTenantLimits.remove(tenantId, debugTbRateLimits); + } } - } - RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId(), Operation.WRITE); + RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId(), Operation.WRITE); - return tbRuleChainService.saveRuleChainMetaData(tenantId, ruleChain, ruleChainMetaData, updateRelated, - getCurrentUser()); - } + return tbRuleChainService.saveRuleChainMetaData(tenantId, ruleChain, ruleChainMetaData, updateRelated, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.ADDED, + getCurrentUser(), e, ruleChainMetaData); + throw handleException(e); + } + } @ApiOperation(value = "Get Rule Chains (getRuleChains)", notes = "Returns a page of Rule Chains owned by tenant. " + RULE_CHAIN_DESCRIPTION + PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH) @@ -334,12 +359,17 @@ public class RuleChainController extends BaseController { public void deleteRuleChain( @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE); - tbRuleChainService.delete(ruleChain, getCurrentUser()); - } + try { + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE); + tbRuleChainService.delete(ruleChain, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.DELETED, + getCurrentUser(), e, strRuleChainId); + throw handleException(e); + } + } @ApiOperation(value = "Get latest input message (getLatestRuleNodeDebugInput)", notes = "Gets the input message from the debug events for specified Rule Chain Id. " + @@ -523,16 +553,22 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain assignRuleChainToEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter("edgeId", strEdgeId); - checkParameter(RULE_CHAIN_ID, strRuleChainId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); + try { + checkParameter("edgeId", strEdgeId); + checkParameter(RULE_CHAIN_ID, strRuleChainId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); - return tbRuleChainService.assignRuleChainToEdge(getTenantId(), ruleChain, edge, getCurrentUser()); - } + return tbRuleChainService.assignRuleChainToEdge(getTenantId(), ruleChain, edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), + ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strRuleChainId, strEdgeId); + throw handleException(e); + } + } @ApiOperation(value = "Unassign rule chain from edge (unassignRuleChainFromEdge)", notes = "Clears assignment of the rule chain to the edge. " + @@ -546,15 +582,21 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain unassignRuleChainFromEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter("edgeId", strEdgeId); - checkParameter(RULE_CHAIN_ID, strRuleChainId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); + try { + checkParameter("edgeId", strEdgeId); + checkParameter(RULE_CHAIN_ID, strRuleChainId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); - return tbRuleChainService.unassignRuleChainFromEdge(getTenantId(), ruleChain, edge, getCurrentUser()); - } + return tbRuleChainService.unassignRuleChainFromEdge(getTenantId(), ruleChain, edge, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), + ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strRuleChainId, strEdgeId); + throw handleException(e); + } + } @ApiOperation(value = "Get Edge Rule Chains (getEdgeRuleChains)", notes = "Returns a page of Rule Chains assigned to the specified edge. " + RULE_CHAIN_DESCRIPTION + PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH) @@ -594,10 +636,16 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain setEdgeTemplateRootRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setEdgeTemplateRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); + try { + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setEdgeTemplateRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + getCurrentUser(), e, strRuleChainId); + throw handleException(e); + } } @ApiOperation(value = "Set Auto Assign To Edge Rule Chain (setAutoAssignToEdgeRuleChain)", @@ -608,11 +656,17 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain setAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } + try { + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + getCurrentUser(), e, strRuleChainId); + throw handleException(e); + } + } @ApiOperation(value = "Unset Auto Assign To Edge Rule Chain (unsetAutoAssignToEdgeRuleChain)", notes = "Removes the rule chain from the list of rule chains that are going to be automatically assigned for any new edge that will be created. " + @@ -622,12 +676,18 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain unsetAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + try { + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.unsetAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } + return tbRuleChainService.unsetAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + getCurrentUser(), e, strRuleChainId); + throw handleException(e); + } + } // TODO: @voba refactor this - add new config to edge rule chain to set it as auto-assign @ApiOperation(value = "Get Auto Assign To Edge Rule Chains (getAutoAssignToEdgeRuleChains)", diff --git a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java index 120449c137..08d407b736 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java @@ -31,8 +31,10 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; @@ -71,7 +73,7 @@ import static org.thingsboard.server.controller.ControllerConstants.UUID_WIKI_LI @RequiredArgsConstructor public class TbResourceController extends BaseController { - private final TbResourceService tbResourceService; + private final TbResourceService tbResourceService; public static final String RESOURCE_ID = "resourceId"; @@ -147,9 +149,16 @@ public class TbResourceController extends BaseController { @ResponseBody public TbResource saveResource(@ApiParam(value = "A JSON value representing the Resource.") @RequestBody TbResource resource) throws ThingsboardException { - resource.setTenantId(getTenantId()); - checkEntity(resource.getId(), resource, Resource.TB_RESOURCE); - return tbResourceService.save(resource, getCurrentUser()); + try { + resource.setTenantId(getTenantId()); + checkEntity(resource.getId(), resource, Resource.TB_RESOURCE); + return tbResourceService.save(resource, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = resource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.TB_RESOURCE), + resource, actionType, getCurrentUser(), e); + throw handleException(e); + } } @ApiOperation(value = "Get Resource Infos (getResources)", @@ -233,9 +242,15 @@ public class TbResourceController extends BaseController { @ResponseBody public void deleteResource(@ApiParam(value = RESOURCE_ID_PARAM_DESCRIPTION) @PathVariable("resourceId") String strResourceId) throws ThingsboardException { - checkParameter(RESOURCE_ID, strResourceId); - TbResourceId resourceId = new TbResourceId(toUUID(strResourceId)); - TbResource tbResource = checkResourceId(resourceId, Operation.DELETE); - tbResourceService.delete(tbResource, getCurrentUser()); + try { + checkParameter(RESOURCE_ID, strResourceId); + TbResourceId resourceId = new TbResourceId(toUUID(strResourceId)); + TbResource tbResource = checkResourceId(resourceId, Operation.DELETE); + tbResourceService.delete(tbResource, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.TB_RESOURCE), + ActionType.DELETED, getCurrentUser(), e, strResourceId); + throw handleException(e); + } } } \ No newline at end of file diff --git a/application/src/main/java/org/thingsboard/server/controller/TelemetryController.java b/application/src/main/java/org/thingsboard/server/controller/TelemetryController.java index 5ac3355bd4..b9c929f909 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TelemetryController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TelemetryController.java @@ -888,48 +888,29 @@ public class TelemetryController extends BaseController { } private void logTimeseriesDeleted(SecurityUser user, EntityId entityId, List keys, long startTs, long endTs, Throwable e) { - try { - logEntityAction(user, (UUIDBased & EntityId) entityId, null, null, ActionType.TIMESERIES_DELETED, toException(e), - keys, startTs, endTs); - } catch (ThingsboardException te) { - log.warn("Failed to log timeseries delete", te); - } + notificationEntityService.logEntityAction(user.getTenantId(), entityId, ActionType.TIMESERIES_DELETED, user, + toException(e), keys, startTs, endTs); } private void logTelemetryUpdated(SecurityUser user, EntityId entityId, List telemetry, Throwable e) { - try { - logEntityAction(user, (UUIDBased & EntityId) entityId, null, null, ActionType.TIMESERIES_UPDATED, toException(e), telemetry); - } catch (ThingsboardException te) { - log.warn("Failed to log telemetry update"); - } + notificationEntityService.logEntityAction(user.getTenantId(), entityId, ActionType.TIMESERIES_UPDATED, user, + toException(e), telemetry); } private void logAttributesDeleted(SecurityUser user, EntityId entityId, String scope, List keys, Throwable e) { - try { - logEntityAction(user, (UUIDBased & EntityId) entityId, null, null, ActionType.ATTRIBUTES_DELETED, toException(e), - scope, keys); - } catch (ThingsboardException te) { - log.warn("Failed to log attributes delete", te); - } + notificationEntityService.logEntityAction(user.getTenantId(), (UUIDBased & EntityId) entityId, + ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys); } private void logAttributesUpdated(SecurityUser user, EntityId entityId, String scope, List attributes, Throwable e) { - try { - logEntityAction(user, (UUIDBased & EntityId) entityId, null, null, ActionType.ATTRIBUTES_UPDATED, toException(e), - scope, attributes); - } catch (ThingsboardException te) { - log.warn("Failed to log attributes update", te); - } + notificationEntityService.logEntityAction(user.getTenantId(), entityId, ActionType.ATTRIBUTES_UPDATED, user, + toException(e), scope, attributes); } private void logAttributesRead(SecurityUser user, EntityId entityId, String scope, List keys, Throwable e) { - try { - logEntityAction(user, (UUIDBased & EntityId) entityId, null, null, ActionType.ATTRIBUTES_READ, toException(e), - scope, keys); - } catch (ThingsboardException te) { - log.warn("Failed to log attributes read", te); - } + notificationEntityService.logEntityAction(user.getTenantId(), entityId, ActionType.ATTRIBUTES_READ, user, + toException(e), scope, keys); } private ListenableFuture> mergeAllAttributesFutures(List>> futures) { diff --git a/application/src/main/java/org/thingsboard/server/controller/TenantController.java b/application/src/main/java/org/thingsboard/server/controller/TenantController.java index 5e18f1e3a5..fdfdd88f76 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TenantController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TenantController.java @@ -122,7 +122,11 @@ public class TenantController extends BaseController { public Tenant saveTenant(@ApiParam(value = "A JSON value representing the tenant.") @RequestBody Tenant tenant) throws ThingsboardException { checkEntity(tenant.getId(), tenant, Resource.TENANT); - return tbTenantService.save(tenant); + try { + return tbTenantService.save(tenant); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Delete Tenant (deleteTenant)", @@ -135,7 +139,11 @@ public class TenantController extends BaseController { checkParameter(TENANT_ID, strTenantId); TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId)); Tenant tenant = checkTenantId(tenantId, Operation.DELETE); - tbTenantService.delete(tenant); + try { + tbTenantService.delete(tenant); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Get Tenants (getTenants)", notes = "Returns a page of tenants registered in the platform. " + PAGE_DATA_PARAMETERS + SYSTEM_AUTHORITY_PARAGRAPH) diff --git a/application/src/main/java/org/thingsboard/server/controller/TenantProfileController.java b/application/src/main/java/org/thingsboard/server/controller/TenantProfileController.java index 40956d0fcc..dbdc702696 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TenantProfileController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TenantProfileController.java @@ -32,13 +32,11 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.TenantProfile; import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantProfileId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; -import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.tenant_profile.TbTenantProfileService; +import org.thingsboard.server.service.entitiy.tenant.profile.TbTenantProfileService; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; @@ -171,26 +169,18 @@ public class TenantProfileController extends BaseController { @PreAuthorize("hasAuthority('SYS_ADMIN')") @RequestMapping(value = "/tenantProfile", method = RequestMethod.POST) @ResponseBody - public TenantProfile saveTenantProfile( - @ApiParam(value = "A JSON value representing the tenant profile.") - @RequestBody TenantProfile tenantProfile) throws ThingsboardException { + public TenantProfile saveTenantProfile(@ApiParam(value = "A JSON value representing the tenant profile.") + @RequestBody TenantProfile tenantProfile) throws ThingsboardException { try { - boolean newTenantProfile = tenantProfile.getId() == null; TenantProfile oldProfile; - if (newTenantProfile) { - accessControlService - .checkPermission(getCurrentUser(), Resource.TENANT_PROFILE, Operation.CREATE); + if (tenantProfile.getId() == null) { + accessControlService.checkPermission(getCurrentUser(), Resource.TENANT_PROFILE, Operation.CREATE); oldProfile = null; } else { oldProfile = checkTenantProfileId(tenantProfile.getId(), Operation.WRITE); } - tenantProfile = checkNotNull(tbTenantProfileService.saveTenantProfile(getTenantId(), tenantProfile, oldProfile)); - tenantProfileCache.put(tenantProfile); - tbClusterService.onTenantProfileChange(tenantProfile, null); - tbClusterService.broadcastEntityStateChangeEvent(TenantId.SYS_TENANT_ID, tenantProfile.getId(), - newTenantProfile ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); - return tenantProfile; + return tbTenantProfileService.save(getTenantId(), tenantProfile, oldProfile); } catch (Exception e) { throw handleException(e); } @@ -201,15 +191,13 @@ public class TenantProfileController extends BaseController { @PreAuthorize("hasAuthority('SYS_ADMIN')") @RequestMapping(value = "/tenantProfile/{tenantProfileId}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) - public void deleteTenantProfile( - @ApiParam(value = TENANT_PROFILE_ID_PARAM_DESCRIPTION) - @PathVariable("tenantProfileId") String strTenantProfileId) throws ThingsboardException { - checkParameter("tenantProfileId", strTenantProfileId); + public void deleteTenantProfile(@ApiParam(value = TENANT_PROFILE_ID_PARAM_DESCRIPTION) + @PathVariable("tenantProfileId") String strTenantProfileId) throws ThingsboardException { try { + checkParameter("tenantProfileId", strTenantProfileId); TenantProfileId tenantProfileId = new TenantProfileId(toUUID(strTenantProfileId)); TenantProfile profile = checkTenantProfileId(tenantProfileId, Operation.DELETE); - tenantProfileService.deleteTenantProfile(getTenantId(), tenantProfileId); - tbClusterService.onTenantProfileDelete(profile, null); + tbTenantProfileService.delete(getTenantId(), profile); } catch (Exception e) { throw handleException(e); } diff --git a/application/src/main/java/org/thingsboard/server/controller/UserController.java b/application/src/main/java/org/thingsboard/server/controller/UserController.java index d6fda64d31..96067279a6 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UserController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UserController.java @@ -33,7 +33,9 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -102,9 +104,9 @@ public class UserController extends BaseController { @ApiOperation(value = "Get User (getUserById)", notes = "Fetch the User object based on the provided User Id. " + - "If the user has the authority of 'SYS_ADMIN', the server does not perform additional checks. " + - "If the user has the authority of 'TENANT_ADMIN', the server checks that the requested user is owned by the same tenant. " + - "If the user has the authority of 'CUSTOMER_USER', the server checks that the requested user is owned by the same customer.") + "If the user has the authority of 'SYS_ADMIN', the server does not perform additional checks. " + + "If the user has the authority of 'TENANT_ADMIN', the server checks that the requested user is owned by the same tenant. " + + "If the user has the authority of 'CUSTOMER_USER', the server checks that the requested user is owned by the same customer.") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/user/{userId}", method = RequestMethod.GET) @ResponseBody @@ -185,12 +187,18 @@ public class UserController extends BaseController { @RequestBody User user, @ApiParam(value = "Send activation email (or use activation link)", defaultValue = "true") @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException { - if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) { - user.setTenantId(getCurrentUser().getTenantId()); + try { + if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) { + user.setTenantId(getCurrentUser().getTenantId()); + } + checkEntity(user.getId(), user, Resource.USER); + return tbUserService.save(getTenantId(), getCurrentUser().getCustomerId(), user, sendActivationMail, request, getCurrentUser()); + } catch (Exception e) { + ActionType actionType = user.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.USER), user, actionType, getCurrentUser(), e); + throw handleException(e); } - checkEntity(user.getId(), user, Resource.USER); - return tbUserService.save(getTenantId(), getCurrentUser().getCustomerId(), user, sendActivationMail, request, getCurrentUser()); - } + } @ApiOperation(value = "Send or re-send the activation email", notes = "Force send the activation email to the user. Useful to resend the email if user has accidentally deleted it. " + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) @@ -259,13 +267,19 @@ public class UserController extends BaseController { public void deleteUser( @ApiParam(value = USER_ID_PARAM_DESCRIPTION) @PathVariable(USER_ID) String strUserId) throws ThingsboardException { - checkParameter(USER_ID, strUserId); - UserId userId = new UserId(toUUID(strUserId)); - User user = checkUserId(userId, Operation.DELETE); - if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) { - throw new ThingsboardException("Sysadmin is not allowed to delete himself", ThingsboardErrorCode.PERMISSION_DENIED); + try { + checkParameter(USER_ID, strUserId); + UserId userId = new UserId(toUUID(strUserId)); + User user = checkUserId(userId, Operation.DELETE); + if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) { + throw new ThingsboardException("Sysadmin is not allowed to delete himself", ThingsboardErrorCode.PERMISSION_DENIED); + } + tbUserService.delete(getTenantId(), getCurrentUser().getCustomerId(), user, getCurrentUser()); + } catch (Exception e) { + notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.USER), + ActionType.DELETED, getCurrentUser(), e, strUserId); + throw handleException(e); } - tbUserService.delete(getTenantId(), getCurrentUser().getCustomerId(), user, getCurrentUser()); } @ApiOperation(value = "Get Users (getUsers)", diff --git a/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java b/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java index 4a69b203ed..600c615d84 100644 --- a/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java +++ b/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java @@ -36,7 +36,7 @@ import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.widgetsBundle.TbWidgetsBundleService; +import org.thingsboard.server.service.entitiy.widgets.bundle.TbWidgetsBundleService; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; @@ -97,7 +97,7 @@ public class WidgetsBundleController extends BaseController { public WidgetsBundle saveWidgetsBundle( @ApiParam(value = "A JSON value representing the Widget Bundle.", required = true) @RequestBody WidgetsBundle widgetsBundle) throws ThingsboardException { - + try { if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { widgetsBundle.setTenantId(TenantId.SYS_TENANT_ID); } else { @@ -106,7 +106,10 @@ public class WidgetsBundleController extends BaseController { checkEntity(widgetsBundle.getId(), widgetsBundle, Resource.WIDGETS_BUNDLE); - return tbWidgetsBundleService.save(widgetsBundle, getCurrentUser()); + return tbWidgetsBundleService.save(widgetsBundle); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Delete widgets bundle (deleteWidgetsBundle)", @@ -117,10 +120,14 @@ public class WidgetsBundleController extends BaseController { public void deleteWidgetsBundle( @ApiParam(value = WIDGET_BUNDLE_ID_PARAM_DESCRIPTION, required = true) @PathVariable("widgetsBundleId") String strWidgetsBundleId) throws ThingsboardException { - checkParameter("widgetsBundleId", strWidgetsBundleId); - WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); - WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE); - tbWidgetsBundleService.delete(widgetsBundle, getCurrentUser()); + try { + checkParameter("widgetsBundleId", strWidgetsBundleId); + WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); + WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE); + tbWidgetsBundleService.delete(widgetsBundle); + } catch (Exception e) { + throw handleException(e); + } } @ApiOperation(value = "Get Widget Bundles (getWidgetsBundles)", diff --git a/application/src/main/java/org/thingsboard/server/service/action/EntityActionService.java b/application/src/main/java/org/thingsboard/server/service/action/EntityActionService.java index b8c0656bd2..2f9a1b166e 100644 --- a/application/src/main/java/org/thingsboard/server/service/action/EntityActionService.java +++ b/application/src/main/java/org/thingsboard/server/service/action/EntityActionService.java @@ -47,7 +47,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -@TbCoreComponent @Service @RequiredArgsConstructor @Slf4j diff --git a/application/src/main/java/org/thingsboard/server/service/device/ClaimDevicesServiceImpl.java b/application/src/main/java/org/thingsboard/server/service/device/ClaimDevicesServiceImpl.java index 713160d8fe..68c9e3117e 100644 --- a/application/src/main/java/org/thingsboard/server/service/device/ClaimDevicesServiceImpl.java +++ b/application/src/main/java/org/thingsboard/server/service/device/ClaimDevicesServiceImpl.java @@ -28,6 +28,7 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.RuleEngineTelemetryService; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.Customer; @@ -52,12 +53,10 @@ import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.queue.util.TbCoreComponent; import javax.annotation.Nullable; -import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.concurrent.ExecutionException; import static org.thingsboard.server.common.data.CacheConstants.CLAIM_DEVICES_CACHE; @@ -122,55 +121,57 @@ public class ClaimDevicesServiceImpl implements ClaimDevicesService { }, MoreExecutors.directExecutor()); } - private ClaimDataInfo getClaimData(Cache cache, Device device) throws ExecutionException, InterruptedException { + private ListenableFuture getClaimData(Cache cache, Device device) { List key = constructCacheKey(device.getId()); ClaimData claimDataFromCache = cache.get(key, ClaimData.class); if (claimDataFromCache != null) { - return new ClaimDataInfo(true, key, claimDataFromCache); + return Futures.immediateFuture(new ClaimDataInfo(true, key, claimDataFromCache)); } else { - Optional claimDataAttr = attributesService.find(device.getTenantId(), device.getId(), - DataConstants.SERVER_SCOPE, CLAIM_DATA_ATTRIBUTE_NAME).get(); - if (claimDataAttr.isPresent()) { - try { - ClaimData claimDataFromAttribute = mapper.readValue(claimDataAttr.get().getValueAsString(), ClaimData.class); + ListenableFuture> claimDataAttrFuture = attributesService.find(device.getTenantId(), device.getId(), + DataConstants.SERVER_SCOPE, CLAIM_DATA_ATTRIBUTE_NAME); + + return Futures.transform(claimDataAttrFuture, claimDataAttr -> { + if (claimDataAttr.isPresent()) { + ClaimData claimDataFromAttribute = JacksonUtil.fromString(claimDataAttr.get().getValueAsString(), ClaimData.class); return new ClaimDataInfo(false, key, claimDataFromAttribute); - } catch (IOException e) { - log.warn("Failed to read Claim Data [{}] from attribute!", claimDataAttr, e); } - } + return null; + }, MoreExecutors.directExecutor()); } - return null; } @Override - public ListenableFuture claimDevice(Device device, CustomerId customerId, String secretKey) throws ExecutionException, InterruptedException { + public ListenableFuture claimDevice(Device device, CustomerId customerId, String secretKey) { Cache cache = cacheManager.getCache(CLAIM_DEVICES_CACHE); - ClaimDataInfo claimData = getClaimData(cache, device); - if (claimData != null) { - long currTs = System.currentTimeMillis(); - if (currTs > claimData.getData().getExpirationTime() || !secretKeyIsEmptyOrEqual(secretKey, claimData.getData().getSecretKey())) { - log.warn("The claiming timeout occurred or wrong 'secretKey' provided for the device [{}]", device.getName()); - if (claimData.isFromCache()) { - cache.evict(claimData.getKey()); + ListenableFuture claimDataFuture = getClaimData(cache, device); + + return Futures.transformAsync(claimDataFuture, claimData -> { + if (claimData != null) { + long currTs = System.currentTimeMillis(); + if (currTs > claimData.getData().getExpirationTime() || !secretKeyIsEmptyOrEqual(secretKey, claimData.getData().getSecretKey())) { + log.warn("The claiming timeout occurred or wrong 'secretKey' provided for the device [{}]", device.getName()); + if (claimData.isFromCache()) { + cache.evict(claimData.getKey()); + } + return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.FAILURE)); + } else { + if (device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + device.setCustomerId(customerId); + Device savedDevice = deviceService.saveDevice(device); + clusterService.onDeviceUpdated(savedDevice, device); + return Futures.transform(removeClaimingSavedData(cache, claimData, device), result -> new ClaimResult(savedDevice, ClaimResponse.SUCCESS), MoreExecutors.directExecutor()); + } + return Futures.transform(removeClaimingSavedData(cache, claimData, device), result -> new ClaimResult(null, ClaimResponse.CLAIMED), MoreExecutors.directExecutor()); } - return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.FAILURE)); } else { + log.warn("Failed to find the device's claiming message![{}]", device.getName()); if (device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - device.setCustomerId(customerId); - Device savedDevice = deviceService.saveDevice(device); - clusterService.onDeviceUpdated(savedDevice, device); - return Futures.transform(removeClaimingSavedData(cache, claimData, device), result -> new ClaimResult(savedDevice, ClaimResponse.SUCCESS), MoreExecutors.directExecutor()); + return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.FAILURE)); + } else { + return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.CLAIMED)); } - return Futures.transform(removeClaimingSavedData(cache, claimData, device), result -> new ClaimResult(null, ClaimResponse.CLAIMED), MoreExecutors.directExecutor()); } - } else { - log.warn("Failed to find the device's claiming message![{}]", device.getName()); - if (device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.FAILURE)); - } else { - return Futures.immediateFuture(new ClaimResult(null, ClaimResponse.CLAIMED)); - } - } + }, MoreExecutors.directExecutor()); } private boolean secretKeyIsEmptyOrEqual(String secretKeyA, String secretKeyB) { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java index 395ebdeaac..e4bb74c129 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java @@ -23,55 +23,22 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.HasName; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.AlarmInfo; import org.thingsboard.server.common.data.alarm.AlarmQuery; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AlarmId; -import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EntityId; -import org.thingsboard.server.common.data.id.EntityIdFactory; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageDataIterableByTenantIdEntityId; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.alarm.AlarmService; -import org.thingsboard.server.dao.asset.AssetService; -import org.thingsboard.server.dao.attributes.AttributesService; import org.thingsboard.server.dao.customer.CustomerService; -import org.thingsboard.server.dao.dashboard.DashboardService; -import org.thingsboard.server.dao.device.ClaimDevicesService; -import org.thingsboard.server.dao.device.DeviceCredentialsService; -import org.thingsboard.server.dao.device.DeviceProfileService; -import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.edge.EdgeService; -import org.thingsboard.server.dao.entityview.EntityViewService; -import org.thingsboard.server.dao.exception.DataValidationException; -import org.thingsboard.server.dao.exception.IncorrectParameterException; -import org.thingsboard.server.dao.model.ModelConstants; -import org.thingsboard.server.dao.ota.OtaPackageService; -import org.thingsboard.server.dao.queue.QueueService; -import org.thingsboard.server.dao.relation.RelationService; -import org.thingsboard.server.dao.rule.RuleChainService; -import org.thingsboard.server.dao.tenant.TbTenantProfileCache; -import org.thingsboard.server.dao.tenant.TenantService; -import org.thingsboard.server.dao.user.UserService; -import org.thingsboard.server.dao.widget.WidgetsBundleService; -import org.thingsboard.server.service.action.EntityActionService; -import org.thingsboard.server.service.edge.EdgeNotificationService; import org.thingsboard.server.service.executors.DbCallbackExecutorService; -import org.thingsboard.server.service.install.InstallScripts; -import org.thingsboard.server.service.ota.OtaPackageStateService; -import org.thingsboard.server.service.resource.TbResourceService; -import org.thingsboard.server.service.rule.TbRuleChainService; -import org.thingsboard.server.service.security.permission.AccessControlService; -import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; -import javax.mail.MessagingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -99,57 +66,9 @@ public abstract class AbstractTbEntityService { @Autowired protected AlarmService alarmService; @Autowired - protected EntityActionService entityActionService; - @Autowired - protected DeviceService deviceService; - @Autowired - protected AssetService assetService; - @Autowired - protected DeviceCredentialsService deviceCredentialsService; - @Autowired - protected TenantService tenantService; - @Autowired protected CustomerService customerService; @Autowired - protected ClaimDevicesService claimDevicesService; - @Autowired - protected TbTenantProfileCache tenantProfileCache; - @Autowired - protected RuleChainService ruleChainService; - @Autowired - protected TbRuleChainService tbRuleChainService; - @Autowired - protected EdgeNotificationService edgeNotificationService; - @Autowired - protected QueueService queueService; - @Autowired - protected DashboardService dashboardService; - @Autowired - protected EntityViewService entityViewService; - @Autowired - protected TelemetrySubscriptionService tsSubService; - @Autowired - protected AttributesService attributesService; - @Autowired - protected AccessControlService accessControlService; - @Autowired - protected DeviceProfileService deviceProfileService; - @Autowired protected TbClusterService tbClusterService; - @Autowired - protected OtaPackageStateService otaPackageStateService; - @Autowired - protected RelationService relationService; - @Autowired - protected OtaPackageService otaPackageService; - @Autowired - protected InstallScripts installScripts; - @Autowired - protected UserService userService; - @Autowired - protected TbResourceService resourceService; - @Autowired - protected WidgetsBundleService widgetsBundleService; protected ListenableFuture removeAlarmsByEntityId(TenantId tenantId, EntityId entityId) { ListenableFuture> alarmsFuture = @@ -164,15 +83,6 @@ public abstract class AbstractTbEntityService { }, dbExecutor); } - protected void logEntityAction(User user, TenantId tenantId, I entityId, E entity, CustomerId customerId, - ActionType actionType, Exception e, Object... additionalInfo) throws ThingsboardException { - if (user != null) { - entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); - } else if (e == null) { - entityActionService.pushEntityActionToRuleEngine(entityId, entity, tenantId, customerId, actionType, null, additionalInfo); - } - } - protected T checkNotNull(T reference) throws ThingsboardException { return checkNotNull(reference, "Requested item wasn't found!"); } @@ -196,37 +106,6 @@ public abstract class AbstractTbEntityService { } } - protected ThingsboardException handleException(Exception exception) { - return handleException(exception, true); - } - - protected ThingsboardException handleException(Exception exception, boolean logException) { - if (logException && logControllerErrorStackTrace) { - log.error("Error [{}]", exception.getMessage(), exception); - } - - String cause = ""; - if (exception.getCause() != null) { - cause = exception.getCause().getClass().getCanonicalName(); - } - - if (exception instanceof ThingsboardException) { - return (ThingsboardException) exception; - } else if (exception instanceof IllegalArgumentException || exception instanceof IncorrectParameterException - || exception instanceof DataValidationException || cause.contains("IncorrectParameterException")) { - return new ThingsboardException(exception.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); - } else if (exception instanceof MessagingException) { - return new ThingsboardException("Unable to send mail: " + exception.getMessage(), ThingsboardErrorCode.GENERAL); - } else { - return new ThingsboardException(exception.getMessage(), exception, ThingsboardErrorCode.GENERAL); - } - } - - @SuppressWarnings("unchecked") - protected I emptyId(EntityType entityType) { - return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); - } - protected List findRelatedEdgeIds(TenantId tenantId, EntityId entityId) { if (!edgesEnabled) { return null; diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/DefaultTbNotificationEntityService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/DefaultTbNotificationEntityService.java index c7e4f2cd0b..cbe8e2af11 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/DefaultTbNotificationEntityService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/DefaultTbNotificationEntityService.java @@ -15,11 +15,10 @@ */ package org.thingsboard.server.service.entitiy; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.msg.DeviceCredentialsUpdateNotificationMsg; import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.DataConstants; @@ -27,6 +26,7 @@ import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; @@ -46,52 +46,74 @@ import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgDataType; import org.thingsboard.server.common.msg.TbMsgMetaData; -import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.action.EntityActionService; import org.thingsboard.server.service.gateway_device.GatewayNotificationsService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @Slf4j @Service -@TbCoreComponent @RequiredArgsConstructor public class DefaultTbNotificationEntityService implements TbNotificationEntityService { - private static final ObjectMapper json = new ObjectMapper(); private final EntityActionService entityActionService; private final TbClusterService tbClusterService; private final GatewayNotificationsService gatewayNotificationsService; @Override - public void notifyEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, - ActionType actionType, SecurityUser user, Exception e, - Object... additionalInfo) { - logEntityAction(tenantId, entityId, entity, customerId, actionType, user, e, additionalInfo); + public void logEntityAction(TenantId tenantId, I entityId, ActionType actionType, + User user, Exception e, Object... additionalInfo) { + logEntityAction(tenantId, entityId, null, null, actionType, user, e, additionalInfo); + } + + @Override + public void logEntityAction(TenantId tenantId, I entityId, E entity, + ActionType actionType, User user, Object... additionalInfo) { + logEntityAction(tenantId, entityId, entity, null, actionType, user, null, additionalInfo); + } + + @Override + public void logEntityAction(TenantId tenantId, I entityId, E entity, + ActionType actionType, User user, Exception e, + Object... additionalInfo) { + logEntityAction(tenantId, entityId, entity, null, actionType, user, e, additionalInfo); + } + + @Override + public void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, + ActionType actionType, User user, Object... additionalInfo) { + logEntityAction(tenantId, entityId, entity, customerId, actionType, user, null, additionalInfo); + } + + @Override + public void logEntityAction(TenantId tenantId, I entityId, E entity, + CustomerId customerId, ActionType actionType, + User user, Exception e, Object... additionalInfo) { + if (user != null) { + entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); + } else if (e == null) { + entityActionService.pushEntityActionToRuleEngine(entityId, entity, tenantId, customerId, actionType, null, additionalInfo); + } } @Override public void notifyDeleteEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, ActionType actionType, List relatedEdgeIds, - SecurityUser user, Object... additionalInfo) { + User user, Object... additionalInfo) { logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); sendDeleteNotificationMsg(tenantId, entityId, entity, relatedEdgeIds); } - public void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, - CustomerId customerId, - List relatedEdgeIds, - SecurityUser user, - String body, Object... additionalInfo) { + @Override + public void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, CustomerId customerId, + List relatedEdgeIds, User user, String body, Object... additionalInfo) { logEntityAction(tenantId, originatorId, alarm, customerId, ActionType.DELETED, user, additionalInfo); sendAlarmDeleteNotificationMsg(tenantId, alarm, relatedEdgeIds, body); } @Override - public void notifyDeleteRuleChain(TenantId tenantId, RuleChain ruleChain, - List relatedEdgeIds, SecurityUser user) { + public void notifyDeleteRuleChain(TenantId tenantId, RuleChain ruleChain, List relatedEdgeIds, User user) { RuleChainId ruleChainId = ruleChain.getId(); logEntityAction(tenantId, ruleChainId, ruleChain, null, ActionType.DELETED, user, null, ruleChainId.toString()); if (RuleChainType.EDGE.equals(ruleChain.getType())) { @@ -102,19 +124,18 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS @Override public void notifySendMsgToEdgeService(TenantId tenantId, I entityId, EdgeEventActionType edgeEventActionType) { sendEntityNotificationMsg(tenantId, entityId, edgeEventActionType); - } + } @Override public void notifyAssignOrUnassignEntityToCustomer(TenantId tenantId, I entityId, CustomerId customerId, E entity, ActionType actionType, - EdgeEventActionType edgeActionType, - SecurityUser user, boolean sendToEdge, + User user, boolean sendToEdge, Object... additionalInfo) { logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); if (sendToEdge) { - sendEntityAssignToCustomerNotificationMsg(tenantId, entityId, customerId, edgeActionType); + sendEntityAssignToCustomerNotificationMsg(tenantId, entityId, customerId, edgeTypeByActionType(actionType)); } } @@ -122,13 +143,13 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS public void notifyAssignOrUnassignEntityToEdge(TenantId tenantId, I entityId, CustomerId customerId, EdgeId edgeId, E entity, ActionType actionType, - SecurityUser user, Object... additionalInfo) { + User user, Object... additionalInfo) { logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); sendEntityAssignToEdgeNotificationMsg(tenantId, edgeId, entityId, edgeTypeByActionType(actionType)); } @Override - public void notifyCreateOruUpdateTenant(Tenant tenant, ComponentLifecycleEvent event) { + public void notifyCreateOrUpdateTenant(Tenant tenant, ComponentLifecycleEvent event) { tbClusterService.onTenantChange(tenant, null); tbClusterService.broadcastEntityStateChangeEvent(tenant.getId(), tenant.getId(), event); } @@ -142,14 +163,14 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS @Override public void notifyCreateOrUpdateDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, Device oldDevice, ActionType actionType, - SecurityUser user, Object... additionalInfo) { + User user, Object... additionalInfo) { tbClusterService.onDeviceUpdated(device, oldDevice); logEntityAction(tenantId, deviceId, device, customerId, actionType, user, additionalInfo); } @Override public void notifyDeleteDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, - List relatedEdgeIds, SecurityUser user, Object... additionalInfo) { + List relatedEdgeIds, User user, Object... additionalInfo) { gatewayNotificationsService.onDeviceDeleted(device); tbClusterService.onDeviceDeleted(device, null); @@ -158,7 +179,7 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS @Override public void notifyUpdateDeviceCredentials(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, - DeviceCredentials deviceCredentials, SecurityUser user) { + DeviceCredentials deviceCredentials, User user) { tbClusterService.pushMsgToCore(new DeviceCredentialsUpdateNotificationMsg(tenantId, deviceCredentials.getDeviceId(), deviceCredentials), null); sendEntityNotificationMsg(tenantId, deviceId, EdgeEventActionType.CREDENTIALS_UPDATED); logEntityAction(tenantId, deviceId, device, customerId, ActionType.CREDENTIALS_UPDATED, user, deviceCredentials); @@ -166,13 +187,15 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS @Override public void notifyAssignDeviceToTenant(TenantId tenantId, TenantId newTenantId, DeviceId deviceId, CustomerId customerId, - Device device, Tenant tenant, SecurityUser user, Object... additionalInfo) { + Device device, Tenant tenant, User user, Object... additionalInfo) { logEntityAction(tenantId, deviceId, device, customerId, ActionType.ASSIGNED_TO_TENANT, user, additionalInfo); pushAssignedFromNotification(tenant, newTenantId, device); } @Override - public void notifyCreateOrUpdateEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, ActionType actionType, SecurityUser user, Object... additionalInfo) { + public void notifyCreateOrUpdateEntity(TenantId tenantId, I entityId, E entity, + CustomerId customerId, ActionType actionType, + User user, Object... additionalInfo) { logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); if (actionType == ActionType.UPDATED) { sendEntityNotificationMsg(tenantId, entityId, EdgeEventActionType.UPDATED); @@ -180,8 +203,8 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS } @Override - public void notifyEdge(TenantId tenantId, EdgeId edgeId, CustomerId customerId, Edge edge, ActionType actionType, - SecurityUser user, Object... additionalInfo) { + public void notifyEdge(TenantId tenantId, EdgeId edgeId, CustomerId customerId, Edge edge, + ActionType actionType, User user, Object... additionalInfo) { ComponentLifecycleEvent lifecycleEvent; EdgeEventActionType edgeEventActionType = null; switch (actionType) { @@ -216,53 +239,34 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS } @Override - public void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, SecurityUser user, Object... additionalInfo) { + public void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, User user, Object... additionalInfo) { logEntityAction(alarm.getTenantId(), alarm.getOriginator(), alarm, alarm.getCustomerId(), actionType, user, additionalInfo); sendEntityNotificationMsg(alarm.getTenantId(), alarm.getId(), edgeTypeByActionType(actionType)); } @Override public void notifyCreateOrUpdateOrDelete(TenantId tenantId, CustomerId customerId, - I entityId, E entity, SecurityUser user, + I entityId, E entity, User user, ActionType actionType, boolean sendNotifyMsgToEdge, Exception e, Object... additionalInfo) { - notifyEntity(tenantId, entityId, entity, customerId, actionType, user, e, additionalInfo); + logEntityAction(tenantId, entityId, entity, customerId, actionType, user, e, additionalInfo); if (sendNotifyMsgToEdge) { sendEntityNotificationMsg(tenantId, entityId, edgeTypeByActionType(actionType)); } } @Override - public void notifyCreateOrUpdateOrDeleteRelation(TenantId tenantId, CustomerId customerId, - EntityRelation relation, SecurityUser user, - ActionType actionType, Exception e, - Object... additionalInfo) { - notifyEntity(tenantId, relation.getFrom(), null, customerId, actionType, user, e, additionalInfo); - notifyEntity(tenantId, relation.getTo(), null, customerId, actionType, user, e, additionalInfo); - if (e == null) { - try { - if (!relation.getFrom().getEntityType().equals(EntityType.EDGE) && - !relation.getTo().getEntityType().equals(EntityType.EDGE)) { - sendNotificationMsgToEdgeService(tenantId, null, null, json.writeValueAsString(relation), - EdgeEventType.RELATION, edgeTypeByActionType(actionType)); - } - } catch (Exception e1) { - log.warn("Failed to push relation to core: {}", relation, e1); + public void notifyCreateOrUpdateRelation(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user, + ActionType actionType, Object... additionalInfo) { + logEntityAction(tenantId, relation.getFrom(), null, customerId, actionType, user, additionalInfo); + logEntityAction(tenantId, relation.getTo(), null, customerId, actionType, user, additionalInfo); + try { + if (!relation.getFrom().getEntityType().equals(EntityType.EDGE) && !relation.getTo().getEntityType().equals(EntityType.EDGE)) { + sendNotificationMsgToEdgeService(tenantId, null, null, JacksonUtil.toString(relation), + EdgeEventType.RELATION, edgeTypeByActionType(actionType)); } - } - } - - private void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, - ActionType actionType, SecurityUser user, Object... additionalInfo) { - logEntityAction(tenantId, entityId, entity, customerId, actionType, user, null, additionalInfo); - } - - private void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, - ActionType actionType, SecurityUser user, Exception e, Object... additionalInfo) { - if (user != null) { - entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); - } else if (e == null) { - entityActionService.pushEntityActionToRuleEngine(entityId, entity, tenantId, customerId, actionType, null, additionalInfo); + } catch (Exception e) { + log.warn("Failed to push relation to core: {}", relation, e); } } @@ -272,7 +276,7 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS private void sendEntityAssignToCustomerNotificationMsg(TenantId tenantId, EntityId entityId, CustomerId customerId, EdgeEventActionType action) { try { - sendNotificationMsgToEdgeService(tenantId, null, entityId, json.writeValueAsString(customerId), null, action); + sendNotificationMsgToEdgeService(tenantId, null, entityId, JacksonUtil.toString(customerId), null, action); } catch (Exception e) { log.warn("Failed to push assign/unassign to/from customer to core: {}", customerId, e); } @@ -307,14 +311,16 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS sendNotificationMsgToEdgeService(tenantId, edgeId, entityId, null, null, action); } - private void sendNotificationMsgToEdgeService(TenantId tenantId, EdgeId edgeId, EntityId entityId, String body, EdgeEventType type, EdgeEventActionType action) { + private void sendNotificationMsgToEdgeService(TenantId tenantId, EdgeId edgeId, EntityId entityId, String body, + EdgeEventType type, EdgeEventActionType action) { tbClusterService.sendNotificationMsgToEdgeService(tenantId, edgeId, entityId, body, type, action); } private void pushAssignedFromNotification(Tenant currentTenant, TenantId newTenantId, Device assignedDevice) { - String data = entityToStr(assignedDevice); + String data = JacksonUtil.toString(JacksonUtil.valueToTree(assignedDevice)); if (data != null) { - TbMsg tbMsg = TbMsg.newMsg(DataConstants.ENTITY_ASSIGNED_FROM_TENANT, assignedDevice.getId(), assignedDevice.getCustomerId(), getMetaDataForAssignedFrom(currentTenant), TbMsgDataType.JSON, data); + TbMsg tbMsg = TbMsg.newMsg(DataConstants.ENTITY_ASSIGNED_FROM_TENANT, assignedDevice.getId(), + assignedDevice.getCustomerId(), getMetaDataForAssignedFrom(currentTenant), TbMsgDataType.JSON, data); tbClusterService.pushMsgToRuleEngine(newTenantId, assignedDevice.getId(), tbMsg, null); } } @@ -326,15 +332,6 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS return metaData; } - private String entityToStr(E entity) { - try { - return json.writeValueAsString(json.valueToTree(entity)); - } catch (JsonProcessingException e) { - log.warn("[{}] Failed to convert entity to string!", entity, e); - } - return null; - } - public static EdgeEventActionType edgeTypeByActionType(ActionType actionType) { switch (actionType) { case ADDED: @@ -355,6 +352,10 @@ public class DefaultTbNotificationEntityService implements TbNotificationEntityS return EdgeEventActionType.ASSIGNED_TO_EDGE; case UNASSIGNED_FROM_EDGE: return EdgeEventActionType.UNASSIGNED_FROM_EDGE; + case ASSIGNED_TO_CUSTOMER: + return EdgeEventActionType.ASSIGNED_TO_CUSTOMER; + case UNASSIGNED_FROM_CUSTOMER: + return EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER; default: return null; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/SimpleTbEntityService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/SimpleTbEntityService.java index ce22e8d787..49b94f4921 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/SimpleTbEntityService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/SimpleTbEntityService.java @@ -15,13 +15,17 @@ */ package org.thingsboard.server.service.entitiy; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.service.security.model.SecurityUser; public interface SimpleTbEntityService { - T save(T entity, SecurityUser user) throws ThingsboardException; + default T save(T entity) throws ThingsboardException { + return save(entity, null); + } - void delete (T entity, SecurityUser user) throws ThingsboardException; + T save(T entity, User user) throws ThingsboardException; + + void delete(T entity, User user); } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/TbNotificationEntityService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/TbNotificationEntityService.java index c1131761dc..27d58e219d 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/TbNotificationEntityService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/TbNotificationEntityService.java @@ -18,6 +18,7 @@ package org.thingsboard.server.service.entitiy; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; @@ -31,75 +32,81 @@ import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.security.DeviceCredentials; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; public interface TbNotificationEntityService { - void notifyEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, - ActionType actionType, SecurityUser user, Exception e, - Object... additionalInfo); + void logEntityAction(TenantId tenantId, I entityId, ActionType actionType, User user, + Exception e, Object... additionalInfo); + + void logEntityAction(TenantId tenantId, I entityId, E entity, ActionType actionType, + User user, Object... additionalInfo); + + void logEntityAction(TenantId tenantId, I entityId, E entity, ActionType actionType, + User user, Exception e, Object... additionalInfo); + + void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, + ActionType actionType, User user, Object... additionalInfo); + + void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, + ActionType actionType, User user, Exception e, + Object... additionalInfo); void notifyCreateOrUpdateEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, ActionType actionType, - SecurityUser user, Object... additionalInfo); + User user, Object... additionalInfo); void notifyDeleteEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, ActionType actionType, List relatedEdgeIds, - SecurityUser user, Object... additionalInfo); + User user, Object... additionalInfo); - void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, - CustomerId customerId, List relatedEdgeIds, - SecurityUser user, String body, Object... additionalInfo); + void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, CustomerId customerId, + List relatedEdgeIds, User user, String body, Object... additionalInfo); void notifyDeleteRuleChain(TenantId tenantId, RuleChain ruleChain, - List relatedEdgeIds, SecurityUser user); + List relatedEdgeIds, User user); void notifySendMsgToEdgeService(TenantId tenantId, I entityId, EdgeEventActionType edgeEventActionType); void notifyAssignOrUnassignEntityToCustomer(TenantId tenantId, I entityId, CustomerId customerId, E entity, ActionType actionType, - EdgeEventActionType edgeActionType, - SecurityUser user, boolean sendToEdge, + User user, boolean sendToEdge, Object... additionalInfo); void notifyAssignOrUnassignEntityToEdge(TenantId tenantId, I entityId, CustomerId customerId, EdgeId edgeId, E entity, ActionType actionType, - SecurityUser user, Object... additionalInfo); - - void notifyCreateOruUpdateTenant(Tenant tenant, ComponentLifecycleEvent event); + User user, Object... additionalInfo); + void notifyCreateOrUpdateTenant(Tenant tenant, ComponentLifecycleEvent event); void notifyDeleteTenant(Tenant tenant); void notifyCreateOrUpdateDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, - Device oldDevice, ActionType actionType, SecurityUser user, Object... additionalInfo); + Device oldDevice, ActionType actionType, User user, Object... additionalInfo); void notifyDeleteDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, - List relatedEdgeIds, SecurityUser user, Object... additionalInfo); + List relatedEdgeIds, User user, Object... additionalInfo); void notifyUpdateDeviceCredentials(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, - DeviceCredentials deviceCredentials, SecurityUser user); + DeviceCredentials deviceCredentials, User user); void notifyAssignDeviceToTenant(TenantId tenantId, TenantId newTenantId, DeviceId deviceId, CustomerId customerId, - Device device, Tenant tenant, SecurityUser user, Object... additionalInfo); + Device device, Tenant tenant, User user, Object... additionalInfo); void notifyEdge(TenantId tenantId, EdgeId edgeId, CustomerId customerId, Edge edge, ActionType actionType, - SecurityUser user, Object... additionalInfo); + User user, Object... additionalInfo); - void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, SecurityUser user, Object... additionalInfo); + void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, User user, Object... additionalInfo); void notifyCreateOrUpdateOrDelete(TenantId tenantId, CustomerId customerId, - I entityId, E entity, SecurityUser user, - ActionType actionType, boolean sendNotifyMsgToEdge, Exception e, - Object... additionalInfo); - - void notifyCreateOrUpdateOrDeleteRelation(TenantId tenantId, CustomerId customerId, - EntityRelation relation, SecurityUser user, - ActionType actionType, Exception e, - Object... additionalInfo); + I entityId, E entity, User user, + ActionType actionType, boolean sendNotifyMsgToEdge, + Exception e, Object... additionalInfo); + + void notifyCreateOrUpdateRelation(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user, + ActionType actionType, Object... additionalInfo); } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java index 4930f54a5d..75589a62e5 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java @@ -15,76 +15,66 @@ */ package org.thingsboard.server.service.entitiy.alarm; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.MoreExecutors; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmStatus; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.dao.alarm.AlarmOperationResult; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @Service -@TbCoreComponent @AllArgsConstructor public class DefaultTbAlarmService extends AbstractTbEntityService implements TbAlarmService { @Override - public Alarm save(Alarm alarm, SecurityUser user) throws ThingsboardException { + public Alarm save(Alarm alarm, User user) throws ThingsboardException { ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - TenantId tenantId = alarm.getTenantId(); - try { - Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); - notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); - return savedAlarm; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ALARM), alarm, null, actionType, user, e); - throw handleException(e); - } + Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); + notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); + return savedAlarm; } @Override - public void ack(Alarm alarm, SecurityUser user) throws ThingsboardException { - try { - long ackTs = System.currentTimeMillis(); - alarmService.ackAlarm(user.getTenantId(), alarm.getId(), ackTs).get(); + public ListenableFuture ack(Alarm alarm, User user) { + long ackTs = System.currentTimeMillis(); + ListenableFuture future = alarmService.ackAlarm(alarm.getTenantId(), alarm.getId(), ackTs); + return Futures.transform(future, result -> { alarm.setAckTs(ackTs); alarm.setStatus(alarm.getStatus().isCleared() ? AlarmStatus.CLEARED_ACK : AlarmStatus.ACTIVE_ACK); notificationEntityService.notifyCreateOrUpdateAlarm(alarm, ActionType.ALARM_ACK, user); - } catch (Exception e) { - throw handleException(e); - } + return null; + }, MoreExecutors.directExecutor()); } @Override - public void clear(Alarm alarm, SecurityUser user) throws ThingsboardException { - try { - long clearTs = System.currentTimeMillis(); - alarmService.clearAlarm(user.getTenantId(), alarm.getId(), null, clearTs).get(); + public ListenableFuture clear(Alarm alarm, User user) { + long clearTs = System.currentTimeMillis(); + ListenableFuture future = alarmService.clearAlarm(alarm.getTenantId(), alarm.getId(), null, clearTs); + return Futures.transform(future, result -> { alarm.setClearTs(clearTs); alarm.setStatus(alarm.getStatus().isAck() ? AlarmStatus.CLEARED_ACK : AlarmStatus.CLEARED_UNACK); notificationEntityService.notifyCreateOrUpdateAlarm(alarm, ActionType.ALARM_CLEAR, user); - } catch (Exception e) { - throw handleException(e); - } + return null; + }, MoreExecutors.directExecutor()); } @Override - public Boolean delete(Alarm alarm, SecurityUser user) throws ThingsboardException { - try { - List relatedEdgeIds = findRelatedEdgeIds(user.getTenantId(), alarm.getOriginator()); - notificationEntityService.notifyDeleteAlarm(user.getTenantId(), alarm, alarm.getOriginator(), user.getCustomerId(), - relatedEdgeIds, user, JacksonUtil.OBJECT_MAPPER.writeValueAsString(alarm)); - return alarmService.deleteAlarm(user.getTenantId(), alarm.getId()).isSuccessful(); - } catch (Exception e) { - throw handleException(e); - } + public Boolean delete(Alarm alarm, User user) { + TenantId tenantId = alarm.getTenantId(); + List relatedEdgeIds = findRelatedEdgeIds(tenantId, alarm.getOriginator()); + notificationEntityService.notifyDeleteAlarm(tenantId, alarm, alarm.getOriginator(), alarm.getCustomerId(), + relatedEdgeIds, user, JacksonUtil.toString(alarm)); + return alarmService.deleteAlarm(tenantId, alarm.getId()).isSuccessful(); } } \ No newline at end of file diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/TbAlarmService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/TbAlarmService.java index 7a6d7f6a81..8cd8d0b49d 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/TbAlarmService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/TbAlarmService.java @@ -15,17 +15,18 @@ */ package org.thingsboard.server.service.entitiy.alarm; +import com.google.common.util.concurrent.ListenableFuture; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbAlarmService { - Alarm save(Alarm entity, SecurityUser user) throws ThingsboardException; + Alarm save(Alarm entity, User user) throws ThingsboardException; - void ack(Alarm alarm, SecurityUser user) throws ThingsboardException; + ListenableFuture ack(Alarm alarm, User user); - void clear(Alarm alarm, SecurityUser user) throws ThingsboardException; + ListenableFuture clear(Alarm alarm, User user); - Boolean delete(Alarm alarm, SecurityUser user) throws ThingsboardException; + Boolean delete(Alarm alarm, User user); } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java index 492464f147..acee2912a8 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java @@ -19,147 +19,102 @@ import com.google.common.util.concurrent.ListenableFuture; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @Service -@TbCoreComponent @AllArgsConstructor public class DefaultTbAssetService extends AbstractTbEntityService implements TbAssetService { + private final AssetService assetService; + @Override - public Asset save(Asset asset, SecurityUser user) throws ThingsboardException { + public Asset save(Asset asset, User user) throws ThingsboardException { ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = asset.getTenantId(); - try { - Asset savedAsset = checkNotNull(assetService.saveAsset(asset)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), asset, savedAsset.getCustomerId(), actionType, user); - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), asset, null, actionType, user, e); - throw handleException(e); - } + Asset savedAsset = checkNotNull(assetService.saveAsset(asset)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), savedAsset, asset.getCustomerId(), actionType, user); + + return savedAsset; } @Override - public ListenableFuture delete(Asset asset, SecurityUser user) throws ThingsboardException { + public ListenableFuture delete(Asset asset, User user) { TenantId tenantId = asset.getTenantId(); AssetId assetId = asset.getId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId); - assetService.deleteAsset(tenantId, assetId); - notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(), ActionType.DELETED, - relatedEdgeIds, user, assetId.toString()); - - return removeAlarmsByEntityId(tenantId, assetId); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - ActionType.DELETED, user, e, assetId.toString()); - throw handleException(e); - } + List relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId); + assetService.deleteAsset(tenantId, assetId); + notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(), ActionType.DELETED, + relatedEdgeIds, user, assetId.toString()); + + return removeAlarmsByEntityId(tenantId, assetId); } @Override - public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, SecurityUser user) throws ThingsboardException { + public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; CustomerId customerId = customer.getId(); - try { - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); - - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - actionType, user, e, assetId.toString(), customerId.toString()); - - throw handleException(e); - } + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, + actionType, user, true, customerId.toString(), customer.getName()); + + return savedAsset; } @Override - public Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, SecurityUser user) throws ThingsboardException { + public Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - try { - Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId)); - CustomerId customerId = customer.getId(); - - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, - true, customerId.toString(), customer.getName()); - - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - actionType, user, e, assetId.toString()); - throw handleException(e); - } + Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId)); + CustomerId customerId = customer.getId(); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, + actionType, user, true, customerId.toString(), customer.getName()); + + return savedAsset; } @Override - public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, SecurityUser user) throws ThingsboardException { + public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - try { - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId())); - - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset, - actionType, null, user, false, actionType.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - actionType, user, e, assetId.toString()); - throw handleException(e); - } + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset, + actionType, user, false, actionType.toString(), publicCustomer.getId().toString(), publicCustomer.getName()); + + return savedAsset; + } @Override - public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, SecurityUser user) throws ThingsboardException { + public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; EdgeId edgeId = edge.getId(); - try { - Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(), - edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); - - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - actionType, user, e, assetId.toString(), edgeId.toString()); - throw handleException(e); - } + Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(), + edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); + + return savedAsset; } @Override - public Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, SecurityUser user) throws ThingsboardException { + public Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; AssetId assetId = asset.getId(); EdgeId edgeId = edge.getId(); - try { - Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId)); - - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, asset.getCustomerId(), - edgeId, asset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); - return savedAsset; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ASSET), null, null, - actionType, user, e, assetId.toString(), edgeId.toString()); - throw handleException(e); - } + Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId)); + + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, asset.getCustomerId(), + edgeId, asset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); + return savedAsset; } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/TbAssetService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/TbAssetService.java index 3ffb03cb7b..7c4f337abc 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/TbAssetService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/TbAssetService.java @@ -17,27 +17,27 @@ package org.thingsboard.server.service.entitiy.asset; import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbAssetService { - Asset save(Asset asset, SecurityUser user) throws ThingsboardException; + Asset save(Asset asset, User user) throws ThingsboardException; - ListenableFuture delete(Asset asset, SecurityUser user) throws ThingsboardException; + ListenableFuture delete(Asset asset, User user); - Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, SecurityUser user) throws ThingsboardException; + Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException; - Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, SecurityUser user) throws ThingsboardException; + Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException; - Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, SecurityUser user) throws ThingsboardException; + Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException; - Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, SecurityUser user) throws ThingsboardException; + Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException; - Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, SecurityUser user) throws ThingsboardException; + Asset unassignAssetFromEdge(TenantId tenantId, Asset asset, Edge edge, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java index d35cb06a85..6d4c02fb18 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java @@ -18,54 +18,39 @@ package org.thingsboard.server.service.entitiy.customer; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; -import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @Service -@TbCoreComponent @AllArgsConstructor public class DefaultTbCustomerService extends AbstractTbEntityService implements TbCustomerService { @Override - public Customer save(Customer customer, SecurityUser user) throws ThingsboardException { + public Customer save(Customer customer, User user) throws ThingsboardException { ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = customer.getTenantId(); CustomerId customerId = customer.getId(); - try { - Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedCustomer.getId(), savedCustomer, customerId, actionType, user); - return savedCustomer; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.CUSTOMER), customer, null, actionType, user, e); - throw handleException(e); - } + Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedCustomer.getId(), savedCustomer, customerId, actionType, user); + return savedCustomer; } - @Override - public void delete(Customer customer, SecurityUser user) throws ThingsboardException { + public void delete(Customer customer, User user) { TenantId tenantId = customer.getTenantId(); CustomerId customerId = customer.getId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId()); - customerService.deleteCustomer(tenantId, customerId); - notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId, - ActionType.DELETED, relatedEdgeIds, user, customerId.toString()); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.CUSTOMER), null, null, - ActionType.DELETED, user, e, customer.getId().toString()); - throw handleException(e); - } + List relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId()); + customerService.deleteCustomer(tenantId, customerId); + notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId, + ActionType.DELETED, relatedEdgeIds, user, customerId.toString()); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java index f7110c4da7..c409411b75 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java @@ -19,19 +19,18 @@ import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ShortCustomerInfo; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.HashSet; import java.util.List; @@ -42,234 +41,177 @@ import java.util.Set; @AllArgsConstructor public class DefaultTbDashboardService extends AbstractTbEntityService implements TbDashboardService { + private final DashboardService dashboardService; + @Override - public Dashboard save(Dashboard dashboard, SecurityUser user) throws ThingsboardException { + public Dashboard save(Dashboard dashboard, User user) throws ThingsboardException { ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = dashboard.getTenantId(); - try { - Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, - null, actionType, user); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), dashboard, null, actionType, user, e); - throw handleException(e); - } + Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, + null, actionType, user); + return savedDashboard; } @Override - public void delete(Dashboard dashboard, SecurityUser user) throws ThingsboardException { + public void delete(Dashboard dashboard, User user) { DashboardId dashboardId = dashboard.getId(); TenantId tenantId = dashboard.getTenantId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); - dashboardService.deleteDashboard(tenantId, dashboardId); - notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, - ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - ActionType.DELETED, user, e, dashboardId.toString()); - throw handleException(e); - } + List relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); + dashboardService.deleteDashboard(tenantId, dashboardId); + notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, + ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); } @Override - public Dashboard assignDashboardToCustomer(DashboardId dashboardId, Customer customer, SecurityUser user) throws ThingsboardException { + public Dashboard assignDashboardToCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + TenantId tenantId = dashboard.getTenantId(); CustomerId customerId = customer.getId(); - try { - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(user.getTenantId(), dashboardId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboardId, customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboardId.toString(), customerId.toString()); - throw handleException(e); - } + DashboardId dashboardId = dashboard.getId(); + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, + actionType, user, true, customerId.toString(), customer.getName()); + return savedDashboard; } @Override - public Dashboard assignDashboardToPublicCustomer(DashboardId dashboardId, SecurityUser user) throws ThingsboardException { + public Dashboard assignDashboardToPublicCustomer(Dashboard dashboard, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - try { - Customer publicCustomer = customerService.findOrCreatePublicCustomer(user.getTenantId()); - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(user.getTenantId(), dashboardId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboardId, user.getCustomerId(), savedDashboard, - actionType, null, user, false, dashboardId.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboardId.toString()); - throw handleException(e); - } + TenantId tenantId = dashboard.getTenantId(); + DashboardId dashboardId = dashboard.getId(); + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), savedDashboard, + actionType, user, false, dashboardId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedDashboard; } @Override - public Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, SecurityUser user) throws ThingsboardException { + public Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - try { - Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId()); - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(user.getTenantId(), dashboard.getId(), publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboard.getId(), user.getCustomerId(), dashboard, - actionType, null, user, false, dashboard.getId().toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboard.getId().toString()); - throw handleException(e); - } + TenantId tenantId = dashboard.getTenantId(); + DashboardId dashboardId = dashboard.getId(); + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), dashboard, + actionType, user, false, dashboardId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedDashboard; } @Override - public Dashboard updateDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException { + public Dashboard updateDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - TenantId tenantId = user.getTenantId(); - try { - Set addedCustomerIds = new HashSet<>(); - Set removedCustomerIds = new HashSet<>(); - for (CustomerId customerId : customerIds) { - if (!dashboard.isAssignedToCustomer(customerId)) { - addedCustomerIds.add(customerId); - } + TenantId tenantId = dashboard.getTenantId(); + DashboardId dashboardId = dashboard.getId(); + Set addedCustomerIds = new HashSet<>(); + Set removedCustomerIds = new HashSet<>(); + for (CustomerId customerId : customerIds) { + if (!dashboard.isAssignedToCustomer(customerId)) { + addedCustomerIds.add(customerId); } + } - Set assignedCustomers = dashboard.getAssignedCustomers(); - if (assignedCustomers != null) { - for (ShortCustomerInfo customerInfo : assignedCustomers) { - if (!customerIds.contains(customerInfo.getCustomerId())) { - removedCustomerIds.add(customerInfo.getCustomerId()); - } + Set assignedCustomers = dashboard.getAssignedCustomers(); + if (assignedCustomers != null) { + for (ShortCustomerInfo customerInfo : assignedCustomers) { + if (!customerIds.contains(customerInfo.getCustomerId())) { + removedCustomerIds.add(customerInfo.getCustomerId()); } } + } - if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : addedCustomerIds) { - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); - ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); - } - for (CustomerId customerId : removedCustomerIds) { - ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - ActionType.UNASSIGNED_FROM_CUSTOMER, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); - } - return savedDashboard; + if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : addedCustomerIds) { + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); + ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); + } + for (CustomerId customerId : removedCustomerIds) { + ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); } - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboard.getId().toString()); - throw handleException(e); + return savedDashboard; } } @Override - public Dashboard addDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException { + public Dashboard addDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - TenantId tenantId = user.getTenantId(); - try { - if (customerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : customerIds) { - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); - ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); - } - return savedDashboard; + TenantId tenantId = dashboard.getTenantId(); + if (customerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : customerIds) { + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); + ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); } - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboard.getId().toString()); - throw handleException(e); + return savedDashboard; } } @Override - public Dashboard removeDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException { + public Dashboard removeDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - TenantId tenantId = user.getTenantId(); - try { - if (customerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : customerIds) { - ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); - } - return savedDashboard; + TenantId tenantId = dashboard.getTenantId(); + if (customerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : customerIds) { + ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); } - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboard.getId().toString()); - throw handleException(e); + return savedDashboard; } } @Override - public Dashboard asignDashboardToEdge(DashboardId dashboardId, Edge edge, SecurityUser user) throws ThingsboardException { + public Dashboard asignDashboardToEdge(TenantId tenantId, DashboardId dashboardId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; - TenantId tenantId = user.getTenantId(); EdgeId edgeId = edge.getId(); - try { - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, user.getCustomerId(), - edgeId, savedDashboard, actionType, user, dashboardId.toString(), - edgeId.toString(), edge.getName()); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, dashboardId.toString(), edgeId.toString()); - throw handleException(e); - } + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, + edgeId, savedDashboard, actionType, user, dashboardId.toString(), + edgeId.toString(), edge.getName()); + return savedDashboard; } @Override - public Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, SecurityUser user) throws ThingsboardException { + public Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; TenantId tenantId = dashboard.getTenantId(); DashboardId dashboardId = dashboard.getId(); EdgeId edgeId = edge.getId(); - try { - Dashboard savedDevice = checkNotNull(dashboardService.unassignDashboardFromEdge(tenantId, dashboardId, edgeId)); + Dashboard savedDevice = checkNotNull(dashboardService.unassignDashboardFromEdge(tenantId, dashboardId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, user.getCustomerId(), - edgeId, dashboard, actionType, user, dashboardId.toString(), - edgeId.toString(), edge.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboardId.toString(), edgeId.toString()); - throw handleException(e); - } + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, + edgeId, dashboard, actionType, user, dashboardId.toString(), + edgeId.toString(), edge.getName()); + return savedDevice; } @Override - public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, SecurityUser user) throws ThingsboardException { + public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); - try { - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); - return savedDashboard; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, - actionType, user, e, dashboard.getId().toString()); - throw handleException(e); - } + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, + actionType, user, true, customer.getId().toString(), customer.getName()); + return savedDashboard; } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/TbDashboardService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/TbDashboardService.java index 84dba247ff..73d7ea5d44 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/TbDashboardService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/TbDashboardService.java @@ -17,33 +17,34 @@ package org.thingsboard.server.service.entitiy.dashboard; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.service.entitiy.SimpleTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.Set; -public interface TbDashboardService extends SimpleTbEntityService { +public interface TbDashboardService extends SimpleTbEntityService { - Dashboard assignDashboardToCustomer(DashboardId dashboardId, Customer customer, SecurityUser user) throws ThingsboardException; + Dashboard assignDashboardToCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException; - Dashboard assignDashboardToPublicCustomer(DashboardId dashboardId, SecurityUser user) throws ThingsboardException; + Dashboard assignDashboardToPublicCustomer(Dashboard dashboard, User user) throws ThingsboardException; - Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, SecurityUser user) throws ThingsboardException; + Dashboard unassignDashboardFromPublicCustomer(Dashboard dashboard, User user) throws ThingsboardException; - Dashboard updateDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException; + Dashboard updateDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException; - Dashboard addDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException; + Dashboard addDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException; - Dashboard removeDashboardCustomers(Dashboard dashboard, Set customerIds, SecurityUser user) throws ThingsboardException; + Dashboard removeDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException; - Dashboard asignDashboardToEdge(DashboardId dashboardId, Edge edge, SecurityUser user) throws ThingsboardException; + Dashboard asignDashboardToEdge(TenantId tenantId, DashboardId dashboardId, Edge edge, User user) throws ThingsboardException; - Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, SecurityUser user) throws ThingsboardException; + Dashboard unassignDashboardFromEdge(Dashboard dashboard, Edge edge, User user) throws ThingsboardException; - Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, SecurityUser user) throws ThingsboardException; + Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java index d74610a462..a8b3b4c984 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java @@ -23,23 +23,25 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; +import org.thingsboard.server.dao.device.ClaimDevicesService; +import org.thingsboard.server.dao.device.DeviceCredentialsService; +import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.claim.ClaimResponse; import org.thingsboard.server.dao.device.claim.ClaimResult; import org.thingsboard.server.dao.device.claim.ReclaimResult; +import org.thingsboard.server.dao.tenant.TenantService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; @@ -49,231 +51,163 @@ import java.util.List; @Slf4j public class DefaultTbDeviceService extends AbstractTbEntityService implements TbDeviceService { + private final DeviceService deviceService; + private final DeviceCredentialsService deviceCredentialsService; + private final ClaimDevicesService claimDevicesService; + private final TenantService tenantService; + @Override - public Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, SecurityUser user) throws ThingsboardException { + public Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException { ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - Device savedDevice = checkNotNull(deviceService.saveDeviceWithAccessToken(device, accessToken)); - notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), - savedDevice, oldDevice, actionType, user); + Device savedDevice = checkNotNull(deviceService.saveDeviceWithAccessToken(device, accessToken)); + notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), + savedDevice, oldDevice, actionType, user); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), device, null, actionType, user, e); - throw handleException(e); - } + return savedDevice; } @Override - public Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials credentials, SecurityUser user) throws ThingsboardException { + public Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials credentials, User user) throws ThingsboardException { ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - Device savedDevice = checkNotNull(deviceService.saveDeviceWithCredentials(device, credentials)); - notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), - savedDevice, device, actionType, user); + Device savedDevice = checkNotNull(deviceService.saveDeviceWithCredentials(device, credentials)); + notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), + savedDevice, device, actionType, user); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), device, null, actionType, user, e); - throw handleException(e); - } + return savedDevice; } @Override - public ListenableFuture delete(Device device, SecurityUser user) throws ThingsboardException { + public ListenableFuture delete(Device device, User user) { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId); - deviceService.deleteDevice(tenantId, deviceId); - notificationEntityService.notifyDeleteDevice(tenantId, deviceId, device.getCustomerId(), device, - relatedEdgeIds, user, deviceId.toString()); + List relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId); + deviceService.deleteDevice(tenantId, deviceId); + notificationEntityService.notifyDeleteDevice(tenantId, deviceId, device.getCustomerId(), device, + relatedEdgeIds, user, deviceId.toString()); - return removeAlarmsByEntityId(tenantId, deviceId); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - ActionType.DELETED, user, e, deviceId.toString()); - throw handleException(e); - } + return removeAlarmsByEntityId(tenantId, deviceId); } @Override - public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, SecurityUser user) throws ThingsboardException { + public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; CustomerId customerId = customer.getId(); - try { - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(user.getTenantId(), deviceId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, + actionType, user, true, customerId.toString(), customer.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString(), customerId.toString()); - throw handleException(e); - } + return savedDevice; } @Override - public Device unassignDeviceFromCustomer(Device device, Customer customer, SecurityUser user) throws ThingsboardException { + public Device unassignDeviceFromCustomer(Device device, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - try { - Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId)); - CustomerId customerId = customer.getId(); + Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId)); + CustomerId customerId = customer.getId(); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, - true, customerId.toString(), customer.getName()); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, + actionType, user, + true, customerId.toString(), customer.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString()); - throw handleException(e); - } + return savedDevice; } @Override - public Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, SecurityUser user) throws ThingsboardException { + public Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - try { - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, publicCustomer.getId())); + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, savedDevice.getCustomerId(), savedDevice, - actionType, null, user, false, deviceId.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, savedDevice.getCustomerId(), savedDevice, + actionType, user, false, deviceId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString()); - throw handleException(e); - } + return savedDevice; } @Override - public DeviceCredentials getDeviceCredentialsByDeviceId(Device device, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.CREDENTIALS_READ; + public DeviceCredentials getDeviceCredentialsByDeviceId(Device device, User user) throws ThingsboardException { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - try { - DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId)); - notificationEntityService.notifyEntity(tenantId, deviceId, device, device.getCustomerId(), - actionType, user, null, deviceId.toString()); - return deviceCredentials; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString()); - throw handleException(e); - } + DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId)); + notificationEntityService.logEntityAction(tenantId, deviceId, device, device.getCustomerId(), + ActionType.CREDENTIALS_READ, user, deviceId.toString()); + return deviceCredentials; } @Override - public DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, SecurityUser user) throws ThingsboardException { + public DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - try { - DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials)); - notificationEntityService.notifyUpdateDeviceCredentials(tenantId, deviceId, device.getCustomerId(), device, result, user); - return result; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - ActionType.CREDENTIALS_UPDATED, user, e, deviceCredentials); - throw handleException(e); - } + DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials)); + notificationEntityService.notifyUpdateDeviceCredentials(tenantId, deviceId, device.getCustomerId(), device, result, user); + return result; } @Override - public ListenableFuture claimDevice(TenantId tenantId, Device device, CustomerId customerId, String secretKey, SecurityUser user) throws ThingsboardException { - try { - ListenableFuture future = claimDevicesService.claimDevice(device, customerId, secretKey); - - return Futures.transform(future, result -> { - if (result != null && result.getResponse().equals(ClaimResponse.SUCCESS)) { - notificationEntityService.notifyEntity(tenantId, device.getId(), result.getDevice(), customerId, - ActionType.ASSIGNED_TO_CUSTOMER, user, null, device.getId().toString(), customerId.toString(), - customerService.findCustomerById(tenantId, customerId).getName()); - } - return result; - }, MoreExecutors.directExecutor()); - } catch (Exception e) { - throw handleException(e); - } + public ListenableFuture claimDevice(TenantId tenantId, Device device, CustomerId customerId, String secretKey, User user) { + ListenableFuture future = claimDevicesService.claimDevice(device, customerId, secretKey); + + return Futures.transform(future, result -> { + if (result != null && result.getResponse().equals(ClaimResponse.SUCCESS)) { + notificationEntityService.logEntityAction(tenantId, device.getId(), result.getDevice(), customerId, + ActionType.ASSIGNED_TO_CUSTOMER, user, device.getId().toString(), customerId.toString(), + customerService.findCustomerById(tenantId, customerId).getName()); + } + return result; + }, MoreExecutors.directExecutor()); } @Override - public ListenableFuture reclaimDevice(TenantId tenantId, Device device, SecurityUser user) throws ThingsboardException { - try { - ListenableFuture future = claimDevicesService.reClaimDevice(tenantId, device); - - return Futures.transform(future, result -> { - Customer unassignedCustomer = result.getUnassignedCustomer(); - if (unassignedCustomer != null) { - notificationEntityService.notifyEntity(tenantId, device.getId(), device, device.getCustomerId(), ActionType.UNASSIGNED_FROM_CUSTOMER, user, null, - device.getId().toString(), unassignedCustomer.getId().toString(), unassignedCustomer.getName()); - } - return result; - }, MoreExecutors.directExecutor()); - } catch (Exception e) { - throw handleException(e); - } + public ListenableFuture reclaimDevice(TenantId tenantId, Device device, User user) { + ListenableFuture future = claimDevicesService.reClaimDevice(tenantId, device); + + return Futures.transform(future, result -> { + Customer unassignedCustomer = result.getUnassignedCustomer(); + if (unassignedCustomer != null) { + notificationEntityService.logEntityAction(tenantId, device.getId(), device, device.getCustomerId(), + ActionType.UNASSIGNED_FROM_CUSTOMER, user, device.getId().toString(), + unassignedCustomer.getId().toString(), unassignedCustomer.getName()); + } + return result; + }, MoreExecutors.directExecutor()); } @Override - public Device assignDeviceToTenant(Device device, Tenant newTenant, SecurityUser user) throws ThingsboardException { + public Device assignDeviceToTenant(Device device, Tenant newTenant, User user) { TenantId tenantId = device.getTenantId(); TenantId newTenantId = newTenant.getId(); - try { - Tenant tenant = tenantService.findTenantById(tenantId); - Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device); + Tenant tenant = tenantService.findTenantById(tenantId); + Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device); - notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, device.getId(), - assignedDevice.getCustomerId(), assignedDevice, tenant, user, newTenantId.toString(), newTenant.getName()); + notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, device.getId(), + assignedDevice.getCustomerId(), assignedDevice, tenant, user, newTenantId.toString(), newTenant.getName()); - return assignedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - ActionType.ASSIGNED_TO_TENANT, user, e, newTenantId.toString()); - throw handleException(e); - } + return assignedDevice; } @Override - public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, SecurityUser user) throws ThingsboardException { + public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; EdgeId edgeId = edge.getId(); - try { - Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(), - edgeId, savedDevice, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString(), edgeId.toString()); - throw handleException(e); - } + Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(), + edgeId, savedDevice, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); + return savedDevice; } @Override - public Device unassignDeviceFromEdge(Device device, Edge edge, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; + public Device unassignDeviceFromEdge(Device device, Edge edge, User user) throws ThingsboardException { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); EdgeId edgeId = edge.getId(); - try { - Device savedDevice = checkNotNull(deviceService.unassignDeviceFromEdge(tenantId, deviceId, edgeId)); + Device savedDevice = checkNotNull(deviceService.unassignDeviceFromEdge(tenantId, deviceId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, device.getCustomerId(), - edgeId, device, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); - return savedDevice; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, deviceId.toString(), edgeId.toString()); - throw handleException(e); - } + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, device.getCustomerId(), + edgeId, device, ActionType.UNASSIGNED_FROM_EDGE, user, deviceId.toString(), edgeId.toString(), edge.getName()); + return savedDevice; } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java index 74e0bcfbe0..2af592d867 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java @@ -19,6 +19,7 @@ import com.google.common.util.concurrent.ListenableFuture; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -27,33 +28,32 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.device.claim.ClaimResult; import org.thingsboard.server.dao.device.claim.ReclaimResult; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbDeviceService { - Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, SecurityUser user) throws ThingsboardException; + Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException; - Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials deviceCredentials, SecurityUser user) throws ThingsboardException; + Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException; - ListenableFuture delete(Device device, SecurityUser user) throws ThingsboardException; + ListenableFuture delete(Device device, User user); - Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, SecurityUser user) throws ThingsboardException; + Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, User user) throws ThingsboardException; - Device unassignDeviceFromCustomer(Device device, Customer customer, SecurityUser user) throws ThingsboardException; + Device unassignDeviceFromCustomer(Device device, Customer customer, User user) throws ThingsboardException; - Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, SecurityUser user) throws ThingsboardException; + Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, User user) throws ThingsboardException; - DeviceCredentials getDeviceCredentialsByDeviceId(Device device, SecurityUser user) throws ThingsboardException; + DeviceCredentials getDeviceCredentialsByDeviceId(Device device, User user) throws ThingsboardException; - DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, SecurityUser user) throws ThingsboardException; + DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException; - ListenableFuture claimDevice(TenantId tenantId, Device device, CustomerId customerId, String secretKey, SecurityUser user) throws ThingsboardException; + ListenableFuture claimDevice(TenantId tenantId, Device device, CustomerId customerId, String secretKey, User user); - ListenableFuture reclaimDevice(TenantId tenantId, Device device, SecurityUser user) throws ThingsboardException; + ListenableFuture reclaimDevice(TenantId tenantId, Device device, User user); - Device assignDeviceToTenant(Device device, Tenant newTenant, SecurityUser user) throws ThingsboardException; + Device assignDeviceToTenant(Device device, Tenant newTenant, User user); - Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, SecurityUser user) throws ThingsboardException; + Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException; - Device unassignDeviceFromEdge(Device device, Edge edge, SecurityUser user) throws ThingsboardException; + Device unassignDeviceFromEdge(Device device, Edge edge, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java new file mode 100644 index 0000000000..a93e16e7b7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.entitiy.device.profile; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; +import org.thingsboard.server.service.ota.OtaPackageStateService; + +import java.util.Objects; + +@Service +@TbCoreComponent +@AllArgsConstructor +@Slf4j +public class DefaultTbDeviceProfileService extends AbstractTbEntityService implements TbDeviceProfileService { + + private final DeviceProfileService deviceProfileService; + private final OtaPackageStateService otaPackageStateService; + + @Override + public DeviceProfile save(DeviceProfile deviceProfile, User user) throws ThingsboardException { + ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + TenantId tenantId = deviceProfile.getTenantId(); + boolean isFirmwareChanged = false; + boolean isSoftwareChanged = false; + + if (actionType.equals(ActionType.UPDATED)) { + DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); + if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { + isFirmwareChanged = true; + } + if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { + isSoftwareChanged = true; + } + } + DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile)); + + tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), + actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + + otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); + + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), + savedDeviceProfile, user, actionType, true, null); + return savedDeviceProfile; + } + + @Override + public void delete(DeviceProfile deviceProfile, User user) { + DeviceProfileId deviceProfileId = deviceProfile.getId(); + TenantId tenantId = deviceProfile.getTenantId(); + deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); + + tbClusterService.onDeviceProfileDelete(deviceProfile, null); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, + user, ActionType.DELETED, true, null, deviceProfileId.toString()); + } + + @Override + public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException { + TenantId tenantId = deviceProfile.getTenantId(); + if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfile.getId())) { + if (previousDefaultDeviceProfile != null) { + previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); + notificationEntityService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, + ActionType.UPDATED, user); + } + deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); + + notificationEntityService.logEntityAction(tenantId, deviceProfile.getId(), deviceProfile, ActionType.UPDATED, user); + } + return deviceProfile; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/TbDeviceProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/TbDeviceProfileService.java similarity index 81% rename from application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/TbDeviceProfileService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/TbDeviceProfileService.java index 28b07e7d13..03ad8f75cb 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/TbDeviceProfileService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/TbDeviceProfileService.java @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.deviceProfile; +package org.thingsboard.server.service.entitiy.device.profile; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.service.entitiy.SimpleTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbDeviceProfileService extends SimpleTbEntityService { - DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, SecurityUser user) throws ThingsboardException; + DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/DefaultTbDeviceProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/DefaultTbDeviceProfileService.java deleted file mode 100644 index ca73b0cb83..0000000000 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/deviceProfile/DefaultTbDeviceProfileService.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright © 2016-2022 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.service.entitiy.deviceProfile; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.thingsboard.server.common.data.DeviceProfile; -import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.audit.ActionType; -import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.common.data.id.DeviceProfileId; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; -import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; - -import java.util.Objects; - -@Service -@TbCoreComponent -@AllArgsConstructor -@Slf4j -public class DefaultTbDeviceProfileService extends AbstractTbEntityService implements TbDeviceProfileService { - @Override - public DeviceProfile save(DeviceProfile deviceProfile, SecurityUser user) throws ThingsboardException { - ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - TenantId tenantId = deviceProfile.getTenantId(); - try { - boolean isFirmwareChanged = false; - boolean isSoftwareChanged = false; - - if (actionType.equals(ActionType.UPDATED)) { - DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); - if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { - isFirmwareChanged = true; - } - if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { - isSoftwareChanged = true; - } - } - DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile)); - - tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), - actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); - - otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); - - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), savedDeviceProfile, user, actionType, true, null); - return savedDeviceProfile; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.DEVICE_PROFILE), deviceProfile, user, actionType, false, e); - throw handleException(e); - } - } - - @Override - public void delete(DeviceProfile deviceProfile, SecurityUser user) throws ThingsboardException { - DeviceProfileId deviceProfileId = deviceProfile.getId(); - TenantId tenantId = deviceProfile.getTenantId(); - try { - deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); - - tbClusterService.onDeviceProfileDelete(deviceProfile, null); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, user, ActionType.DELETED, true, null, deviceProfileId.toString()); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.DEVICE_PROFILE), null, user, ActionType.DELETED, false, e, deviceProfileId.toString()); - throw handleException(e); - } - } - - @Override - public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, SecurityUser user) throws ThingsboardException { - TenantId tenantId = deviceProfile.getTenantId(); - try { - - if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfile.getId())) { - if (previousDefaultDeviceProfile != null) { - previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); - notificationEntityService.notifyEntity(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, null, - ActionType.UPDATED, user, null); - } - deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); - - notificationEntityService.notifyEntity(tenantId, deviceProfile.getId(), deviceProfile, null, - ActionType.UPDATED, user, null); - } - return deviceProfile; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE_PROFILE), null, null, - ActionType.UPDATED, user, e, deviceProfile.getId().toString()); - throw handleException(e); - } - } -} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java index dca6869cb9..cfd4693d4c 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java @@ -19,7 +19,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -28,9 +28,10 @@ import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.edge.EdgeNotificationService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; @AllArgsConstructor @TbCoreComponent @@ -38,113 +39,75 @@ import org.thingsboard.server.service.security.model.SecurityUser; @Slf4j public class DefaultTbEdgeService extends AbstractTbEntityService implements TbEdgeService { + private final EdgeNotificationService edgeNotificationService; + private final RuleChainService ruleChainService; + @Override - public Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, SecurityUser user) throws ThingsboardException { + public Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, User user) throws Exception { ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = edge.getTenantId(); - try { - Edge savedEdge = checkNotNull(edgeService.saveEdge(edge)); - EdgeId edgeId = savedEdge.getId(); - - if (actionType == ActionType.ADDED) { - ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId); - edgeNotificationService.setEdgeRootRuleChain(tenantId, savedEdge, edgeTemplateRootRuleChain.getId()); - edgeService.assignDefaultRuleChainsToEdge(tenantId, edgeId); - } - - notificationEntityService.notifyEdge(tenantId, edgeId, savedEdge.getCustomerId(), savedEdge, actionType, user); - - return savedEdge; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), edge, null, actionType, user, e); - throw handleException(e); + Edge savedEdge = checkNotNull(edgeService.saveEdge(edge)); + EdgeId edgeId = savedEdge.getId(); + + if (actionType == ActionType.ADDED) { + ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId); + edgeNotificationService.setEdgeRootRuleChain(tenantId, savedEdge, edgeTemplateRootRuleChain.getId()); + edgeService.assignDefaultRuleChainsToEdge(tenantId, edgeId); } + + notificationEntityService.notifyEdge(tenantId, edgeId, savedEdge.getCustomerId(), savedEdge, actionType, user); + + return savedEdge; } @Override - public void delete(Edge edge, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.DELETED; + public void delete(Edge edge, User user) { EdgeId edgeId = edge.getId(); TenantId tenantId = edge.getTenantId(); - try { - edgeService.deleteEdge(tenantId, edgeId); - notificationEntityService.notifyEdge(tenantId, edgeId, edge.getCustomerId(), edge, actionType, user, edgeId.toString()); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), edge, null, actionType, - user, e, edgeId.toString()); - throw handleException(e); - } + edgeService.deleteEdge(tenantId, edgeId); + notificationEntityService.notifyEdge(tenantId, edgeId, edge.getCustomerId(), edge, ActionType.DELETED, user, edgeId.toString()); } @Override - public Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + public Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, User user) throws ThingsboardException { CustomerId customerId = customer.getId(); - try { - Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); - - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, actionType, user, - edgeId.toString(), customerId.toString(), customer.getName()); + Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, + edgeId.toString(), customerId.toString(), customer.getName()); - return savedEdge; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), null, null, - actionType, user, e, edgeId.toString(), customerId.toString()); - throw handleException(e); - } + return savedEdge; } @Override - public Edge unassignEdgeFromCustomer(Edge edge, Customer customer, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; + public Edge unassignEdgeFromCustomer(Edge edge, Customer customer, User user) throws ThingsboardException { TenantId tenantId = edge.getTenantId(); EdgeId edgeId = edge.getId(); CustomerId customerId = customer.getId(); - try { - Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId)); - - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, actionType, user, - edgeId.toString(), customerId.toString(), customer.getName()); - return savedEdge; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), null, null, - actionType, user, e, edgeId.toString()); - throw handleException(e); - } + Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId)); + + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.UNASSIGNED_FROM_CUSTOMER, user, + edgeId.toString(), customerId.toString(), customer.getName()); + return savedEdge; } @Override - public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - try { - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - CustomerId customerId = publicCustomer.getId(); - Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); - - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, actionType, user, - edgeId.toString(), customerId.toString(), publicCustomer.getName()); - - return savedEdge; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), null, null, - actionType, user, e, edgeId.toString()); - throw handleException(e); - } + public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException { + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + CustomerId customerId = publicCustomer.getId(); + Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); + + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, + edgeId.toString(), customerId.toString(), publicCustomer.getName()); + + return savedEdge; } @Override - public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.UPDATED; + public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception { TenantId tenantId = edge.getTenantId(); EdgeId edgeId = edge.getId(); - try { - Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); - notificationEntityService.notifyEdge(tenantId, edgeId, null, updatedEdge, actionType, user); - return updatedEdge; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.EDGE), null, null, - actionType, user, e, edgeId.toString()); - throw handleException(e); - } + Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); + notificationEntityService.notifyEdge(tenantId, edgeId, null, updatedEdge, ActionType.UPDATED, user); + return updatedEdge; } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/TbEdgeService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/TbEdgeService.java index 3b4fc28283..b7cc0a5072 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/TbEdgeService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/TbEdgeService.java @@ -16,24 +16,24 @@ package org.thingsboard.server.service.entitiy.edge; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbEdgeService { - Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, SecurityUser user) throws ThingsboardException; + Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, User user) throws Exception; - void delete(Edge edge, SecurityUser user) throws ThingsboardException; + void delete(Edge edge, User user); - Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, SecurityUser user) throws ThingsboardException; + Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, User user) throws ThingsboardException; - Edge unassignEdgeFromCustomer(Edge edge, Customer customer, SecurityUser user) throws ThingsboardException; + Edge unassignEdgeFromCustomer(Edge edge, Customer customer, User user) throws ThingsboardException; - Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, SecurityUser user) throws ThingsboardException; + Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException; - Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, SecurityUser user) throws ThingsboardException; + Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java new file mode 100644 index 0000000000..2af7ea773c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java @@ -0,0 +1,63 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.entitiy.entity.relation; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.relation.EntityRelation; +import org.thingsboard.server.dao.relation.RelationService; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; + +@Service +@TbCoreComponent +@AllArgsConstructor +@Slf4j +public class DefaultTbEntityRelationService extends AbstractTbEntityService implements TbEntityRelationService { + + private final RelationService relationService; + + @Override + public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { + relationService.saveRelation(tenantId, relation); + notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, + relation, user, ActionType.RELATION_ADD_OR_UPDATE, relation); + } + + @Override + public void delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { + boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); + if (!found) { + throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); + } + notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, + relation, user, ActionType.RELATION_DELETED, relation); + } + + @Override + public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) throws ThingsboardException { + relationService.deleteEntityRelations(tenantId, entityId); + notificationEntityService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/TbEntityRelationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/TbEntityRelationService.java similarity index 69% rename from application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/TbEntityRelationService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/TbEntityRelationService.java index 52ad888dc8..09dfd35fe4 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/TbEntityRelationService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/TbEntityRelationService.java @@ -13,21 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.entityRelation; +package org.thingsboard.server.service.entitiy.entity.relation; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.relation.EntityRelation; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbEntityRelationService { - void save(TenantId tenantId, CustomerId customerId, EntityRelation entity, SecurityUser user) throws ThingsboardException; + void save(TenantId tenantId, CustomerId customerId, EntityRelation entity, User user) throws ThingsboardException; - void delete (TenantId tenantId, CustomerId customerId, EntityRelation entity, SecurityUser user) throws ThingsboardException; + void delete(TenantId tenantId, CustomerId customerId, EntityRelation entity, User user) throws ThingsboardException; - void deleteRelations (TenantId tenantId, CustomerId customerId, EntityId entityId, SecurityUser user) throws ThingsboardException; + void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/DefaultTbEntityRelationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/DefaultTbEntityRelationService.java deleted file mode 100644 index ea895683a1..0000000000 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityRelation/DefaultTbEntityRelationService.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright © 2016-2022 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.service.entitiy.entityRelation; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.thingsboard.server.common.data.audit.ActionType; -import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; -import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.common.data.id.CustomerId; -import org.thingsboard.server.common.data.id.EntityId; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.relation.EntityRelation; -import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; - -@Service -@TbCoreComponent -@AllArgsConstructor -@Slf4j -public class DefaultTbEntityRelationService extends AbstractTbEntityService implements TbEntityRelationService { - @Override - public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, SecurityUser user) throws ThingsboardException { - try { - relationService.saveRelation(tenantId, relation); - notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, - relation, user, ActionType.RELATION_ADD_OR_UPDATE, null, relation); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, - relation, user, ActionType.RELATION_ADD_OR_UPDATE, e, relation); - throw handleException(e); - } - } - - @Override - public void delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, SecurityUser user) throws ThingsboardException { - try { - Boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); - if (!found) { - throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); - } - notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, - relation, user, ActionType.RELATION_DELETED, null, relation); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDeleteRelation (tenantId, customerId, - relation, user, ActionType.RELATION_DELETED, e, relation); - throw handleException(e); - } - } - - @Override - public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, SecurityUser user) throws ThingsboardException { - try { - relationService.deleteEntityRelations(tenantId, entityId); - notificationEntityService.notifyEntity(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user, null); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user, e); - throw handleException(e); - } - } -} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java similarity index 56% rename from application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java index 878c6d32bb..962603cd37 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.entityView; +package org.thingsboard.server.service.entitiy.entityview; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; @@ -25,11 +25,10 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DataConstants; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; @@ -40,10 +39,12 @@ import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.BaseReadTsKvQuery; import org.thingsboard.server.common.data.kv.ReadTsKvQuery; import org.thingsboard.server.common.data.kv.TsKvEntry; +import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.entityview.EntityViewService; import org.thingsboard.server.dao.timeseries.TimeseriesService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import javax.annotation.Nullable; import java.util.ArrayList; @@ -61,152 +62,110 @@ import static org.apache.commons.lang3.StringUtils.isBlank; @Slf4j public class DefaultTbEntityViewService extends AbstractTbEntityService implements TbEntityViewService { + private final EntityViewService entityViewService; + private final AttributesService attributesService; + private final TelemetrySubscriptionService tsSubService; private final TimeseriesService tsService; @Override - public EntityView save(EntityView entityView, EntityView existingEntityView, SecurityUser user) throws ThingsboardException { + public EntityView save(EntityView entityView, EntityView existingEntityView, User user) throws ThingsboardException { ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - List> futures = new ArrayList<>(); - if (existingEntityView != null) { - if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); - } - List tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? - existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); - futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); + TenantId tenantId = entityView.getTenantId(); + List> futures = new ArrayList<>(); + if (existingEntityView != null) { + if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); } - EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); - if (savedEntityView.getKeys() != null) { - if (savedEntityView.getKeys().getAttributes() != null) { - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user)); - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user)); - } - futures.add(copyLatestFromEntityToEntityView(savedEntityView, user)); + List tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? + existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); + futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); + } + EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); + if (savedEntityView.getKeys() != null) { + if (savedEntityView.getKeys().getAttributes() != null) { + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user)); + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user)); } - for (ListenableFuture future : futures) { - try { - future.get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Failed to copy attributes to entity view", e); - } + futures.add(copyLatestFromEntityToEntityView(tenantId, savedEntityView)); + } + for (ListenableFuture future : futures) { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException("Failed to copy attributes to entity view", e); } + } - notificationEntityService.notifyCreateOrUpdateEntity(savedEntityView.getTenantId(), savedEntityView.getId(), savedEntityView, - null, actionType, user); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedEntityView.getId(), savedEntityView, + null, actionType, user); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.ENTITY_VIEW), entityView, null, actionType, user, e); - throw handleException(e); - } + return savedEntityView; } @Override - public void delete(EntityView entityView, SecurityUser user) throws ThingsboardException { + public void delete(EntityView entityView, User user) throws ThingsboardException { TenantId tenantId = entityView.getTenantId(); EntityViewId entityViewId = entityView.getId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); - entityViewService.deleteEntityView(tenantId, entityViewId); - notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, - relatedEdgeIds, user, entityViewId.toString()); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, - ActionType.DELETED, user, e, entityViewId.toString()); - throw handleException(e); - } + List relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); + entityViewService.deleteEntityView(tenantId, entityViewId); + notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, + relatedEdgeIds, user, entityViewId.toString()); } @Override - public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; + public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { CustomerId customerId = customer.getId(); - try { - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, - actionType, user, e, entityViewId.toString(), customerId.toString()); - throw handleException(e); - } + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, + ActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + return savedEntityView; } @Override public EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, - EntityViewId entityViewId, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - try { - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, - entityViewId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - actionType, null, user, false, savedEntityView.getEntityId().toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, - actionType, user, e, entityViewId.toString()); - throw handleException(e); - } + EntityViewId entityViewId, User user) throws ThingsboardException { + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, + entityViewId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, + ActionType.ASSIGNED_TO_CUSTOMER, user, false, savedEntityView.getEntityId().toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedEntityView; } @Override - public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.ASSIGNED_TO_EDGE; + public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, User user) throws ThingsboardException { EdgeId edgeId = edge.getId(); EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId)); - try { - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, - edgeId, savedEntityView, actionType, user, savedEntityView.getEntityId().toString(), - edgeId.toString(), edge.getName()); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DEVICE), null, null, - actionType, user, e, entityViewId.toString(), edgeId.toString()); - throw handleException(e); - } + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, + edgeId, savedEntityView, ActionType.ASSIGNED_TO_EDGE, user, savedEntityView.getEntityId().toString(), + edgeId.toString(), edge.getName()); + return savedEntityView; } @Override public EntityView unassignEntityViewFromEdge(TenantId tenantId, CustomerId customerId, EntityView entityView, - Edge edge, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; + Edge edge, User user) throws ThingsboardException { EntityViewId entityViewId = entityView.getId(); EdgeId edgeId = edge.getId(); - try { - EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, - edgeId, entityView, actionType, user, entityViewId.toString(), - edgeId.toString(), edge.getName()); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, - actionType, user, e, entityViewId.toString(), edgeId.toString()); - throw handleException(e); - } + EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, + edgeId, entityView, ActionType.UNASSIGNED_FROM_EDGE, user, entityViewId.toString(), + edgeId.toString(), edge.getName()); + return savedEntityView; } @Override - public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, SecurityUser user) throws ThingsboardException { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - try { - EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); - return savedEntityView; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, - actionType, user, e, entityViewId.toString()); - throw handleException(e); - } + public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { + EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, + ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); + return savedEntityView; } - private ListenableFuture> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection keys, SecurityUser user) throws ThingsboardException { + private ListenableFuture> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection keys, User user) throws ThingsboardException { EntityViewId entityId = entityView.getId(); if (keys != null && !keys.isEmpty()) { ListenableFuture> getAttrFuture = attributesService.find(entityView.getTenantId(), entityView.getEntityId(), scope, keys); @@ -251,7 +210,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen } } - private ListenableFuture> copyLatestFromEntityToEntityView(EntityView entityView, SecurityUser user) { + private ListenableFuture> copyLatestFromEntityToEntityView(TenantId tenantId, EntityView entityView) { EntityViewId entityId = entityView.getId(); List keys = entityView.getKeys() != null && entityView.getKeys().getTimeseries() != null ? entityView.getKeys().getTimeseries() : Collections.emptyList(); @@ -259,7 +218,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen long endTs = entityView.getEndTimeMs() == 0 ? Long.MAX_VALUE : entityView.getEndTimeMs(); ListenableFuture> keysFuture; if (keys.isEmpty()) { - keysFuture = Futures.transform(tsService.findAllLatest(user.getTenantId(), + keysFuture = Futures.transform(tsService.findAllLatest(tenantId, entityView.getEntityId()), latest -> latest.stream().map(TsKvEntry::getKey).collect(Collectors.toList()), MoreExecutors.directExecutor()); } else { keysFuture = Futures.immediateFuture(keys); @@ -267,7 +226,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen ListenableFuture> latestFuture = Futures.transformAsync(keysFuture, fetchKeys -> { List queries = fetchKeys.stream().filter(key -> !isBlank(key)).map(key -> new BaseReadTsKvQuery(key, startTs, endTs, 1, "DESC")).collect(Collectors.toList()); if (!queries.isEmpty()) { - return tsService.findAll(user.getTenantId(), entityView.getEntityId(), queries); + return tsService.findAll(tenantId, entityView.getEntityId(), queries); } else { return Futures.immediateFuture(null); } @@ -288,7 +247,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen }, MoreExecutors.directExecutor()); } - private ListenableFuture deleteAttributesFromEntityView(EntityView entityView, String scope, List keys, SecurityUser user) { + private ListenableFuture deleteAttributesFromEntityView(EntityView entityView, String scope, List keys, User user) { EntityViewId entityId = entityView.getId(); SettableFuture resultFuture = SettableFuture.create(); if (keys != null && !keys.isEmpty()) { @@ -319,7 +278,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen return resultFuture; } - private ListenableFuture deleteLatestFromEntityView(EntityView entityView, List keys, SecurityUser user) { + private ListenableFuture deleteLatestFromEntityView(EntityView entityView, List keys, User user) { EntityViewId entityId = entityView.getId(); SettableFuture resultFuture = SettableFuture.create(); if (keys != null && !keys.isEmpty()) { @@ -337,7 +296,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen @Override public void onFailure(Throwable t) { try { - logTimeseriesDeleted(entityView.getTenantId(),user, entityId, keys, t); + logTimeseriesDeleted(entityView.getTenantId(), user, entityId, keys, t); } catch (ThingsboardException e) { log.error("Failed to log timeseries delete", e); } @@ -370,16 +329,16 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen return resultFuture; } - private void logAttributesUpdated(TenantId tenantId, SecurityUser user, EntityId entityId, String scope, List attributes, Throwable e) throws ThingsboardException { - notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.ATTRIBUTES_UPDATED, user, toException(e), scope, attributes); + private void logAttributesUpdated(TenantId tenantId, User user, EntityId entityId, String scope, List attributes, Throwable e) throws ThingsboardException { + notificationEntityService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_UPDATED, user, toException(e), scope, attributes); } - private void logAttributesDeleted(TenantId tenantId, SecurityUser user, EntityId entityId, String scope, List keys, Throwable e) throws ThingsboardException { - notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys); + private void logAttributesDeleted(TenantId tenantId, User user, EntityId entityId, String scope, List keys, Throwable e) throws ThingsboardException { + notificationEntityService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys); } - private void logTimeseriesDeleted(TenantId tenantId, SecurityUser user, EntityId entityId, List keys, Throwable e) throws ThingsboardException { - notificationEntityService.notifyEntity(tenantId, entityId, null, null, ActionType.TIMESERIES_DELETED, user, toException(e), keys); + private void logTimeseriesDeleted(TenantId tenantId, User user, EntityId entityId, List keys, Throwable e) throws ThingsboardException { + notificationEntityService.logEntityAction(tenantId, entityId, ActionType.TIMESERIES_DELETED, user, toException(e), keys); } public static Exception toException(Throwable error) { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/TbEntityViewService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/TbEntityViewService.java similarity index 65% rename from application/src/main/java/org/thingsboard/server/service/entitiy/entityView/TbEntityViewService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/entityview/TbEntityViewService.java index dd5db9391b..7012e39aa6 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/TbEntityViewService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/TbEntityViewService.java @@ -13,35 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.entityView; +package org.thingsboard.server.service.entitiy.entityview; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntityView; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityViewId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.service.security.model.SecurityUser; public interface TbEntityViewService { - EntityView save(EntityView entityView, EntityView existingEntityView, SecurityUser user) throws ThingsboardException; + EntityView save(EntityView entityView, EntityView existingEntityView, User user) throws ThingsboardException; - void delete (EntityView entity, SecurityUser user) throws ThingsboardException; + void delete(EntityView entity, User user) throws ThingsboardException; - EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, - SecurityUser user) throws ThingsboardException; + EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException; EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, - EntityViewId entityViewId, SecurityUser user) throws ThingsboardException; + EntityViewId entityViewId, User user) throws ThingsboardException; - EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, - SecurityUser user) throws ThingsboardException; + EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, User user) throws ThingsboardException; - EntityView unassignEntityViewFromEdge(TenantId tenantId, CustomerId customerId, EntityView entityView, - Edge edge, SecurityUser user) throws ThingsboardException; + EntityView unassignEntityViewFromEdge(TenantId tenantId, CustomerId customerId, EntityView entityView, Edge edge, User user) throws ThingsboardException; - EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, - SecurityUser user) throws ThingsboardException; + EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java new file mode 100644 index 0000000000..78c1447d0e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java @@ -0,0 +1,91 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.entitiy.ota; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.OtaPackage; +import org.thingsboard.server.common.data.OtaPackageInfo; +import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.OtaPackageId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.ota.ChecksumAlgorithm; +import org.thingsboard.server.dao.ota.OtaPackageService; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; + +import java.nio.ByteBuffer; + +@Service +@TbCoreComponent +@AllArgsConstructor +@Slf4j +public class DefaultTbOtaPackageService extends AbstractTbEntityService implements TbOtaPackageService { + + private final OtaPackageService otaPackageService; + + @Override + public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, User user) throws ThingsboardException { + TenantId tenantId = saveOtaPackageInfoRequest.getTenantId(); + ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED; + OtaPackageInfo savedOtaPackageInfo = checkNotNull(otaPackageService.saveOtaPackageInfo( + new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl())); + notificationEntityService.logEntityAction(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, actionType, user); + return savedOtaPackageInfo; + } + + @Override + public OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm, + byte[] data, String filename, String contentType, User user) throws ThingsboardException { + TenantId tenantId = otaPackageInfo.getTenantId(); + OtaPackageId otaPackageId = otaPackageInfo.getId(); + if (StringUtils.isEmpty(checksum)) { + checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); + } + OtaPackage otaPackage = new OtaPackage(otaPackageId); + otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime()); + otaPackage.setTenantId(tenantId); + otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId()); + otaPackage.setType(otaPackageInfo.getType()); + otaPackage.setTitle(otaPackageInfo.getTitle()); + otaPackage.setVersion(otaPackageInfo.getVersion()); + otaPackage.setTag(otaPackageInfo.getTag()); + otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo()); + otaPackage.setChecksumAlgorithm(checksumAlgorithm); + otaPackage.setChecksum(checksum); + otaPackage.setFileName(filename); + otaPackage.setContentType(contentType); + otaPackage.setData(ByteBuffer.wrap(data)); + otaPackage.setDataSize((long) data.length); + OtaPackageInfo savedOtaPackage = otaPackageService.saveOtaPackage(otaPackage); + notificationEntityService.logEntityAction(tenantId, savedOtaPackage.getId(), savedOtaPackage, ActionType.UPDATED, user); + return savedOtaPackage; + } + + @Override + public void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException { + TenantId tenantId = otaPackageInfo.getTenantId(); + OtaPackageId otaPackageId = otaPackageInfo.getId(); + otaPackageService.deleteOtaPackage(tenantId, otaPackageId); + notificationEntityService.logEntityAction(tenantId, otaPackageId, otaPackageInfo, ActionType.DELETED, user, + otaPackageInfo.getId().toString()); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/TbOtaPackageService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/TbOtaPackageService.java similarity index 73% rename from application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/TbOtaPackageService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/ota/TbOtaPackageService.java index 7a7d0e79f7..aec2f20d0c 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/TbOtaPackageService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/TbOtaPackageService.java @@ -13,20 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.otaPackageController; +package org.thingsboard.server.service.entitiy.ota; import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.ota.ChecksumAlgorithm; -import org.thingsboard.server.service.security.model.SecurityUser; -public interface TbOtaPackageService { +public interface TbOtaPackageService { - OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, SecurityUser user) throws ThingsboardException; - - void delete(OtaPackageInfo otaPackageInfo, SecurityUser user) throws ThingsboardException; + OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, User user) throws ThingsboardException; OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm, - byte[] data, String filename, String contentType, SecurityUser securityUser) throws ThingsboardException; + byte[] data, String filename, String contentType, User user) throws ThingsboardException; + + void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException; + } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java deleted file mode 100644 index 555041ed8f..0000000000 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright © 2016-2022 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.service.entitiy.otaPackageController; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.thingsboard.server.common.data.StringUtils; -import org.springframework.stereotype.Service; -import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.OtaPackage; -import org.thingsboard.server.common.data.OtaPackageInfo; -import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; -import org.thingsboard.server.common.data.audit.ActionType; -import org.thingsboard.server.common.data.exception.ThingsboardException; -import org.thingsboard.server.common.data.id.OtaPackageId; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.ota.ChecksumAlgorithm; -import org.thingsboard.server.queue.util.TbCoreComponent; -import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; - -import java.nio.ByteBuffer; - -@Service -@TbCoreComponent -@AllArgsConstructor -@Slf4j -public class DefaultTbOtaPackageService extends AbstractTbEntityService implements TbOtaPackageService { - @Override - public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, SecurityUser user) throws ThingsboardException { - TenantId tenantId = saveOtaPackageInfoRequest.getTenantId(); - ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - OtaPackageInfo savedOtaPackageInfo = otaPackageService.saveOtaPackageInfo(new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl()); - notificationEntityService.notifyEntity(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, null, - actionType, user, null); - return savedOtaPackageInfo; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), saveOtaPackageInfoRequest, null, - actionType, user, e); - throw handleException(e); - } - } - - @Override - public void delete(OtaPackageInfo otaPackageInfo, SecurityUser user) throws ThingsboardException { - TenantId tenantId = otaPackageInfo.getTenantId(); - OtaPackageId otaPackageId = otaPackageInfo.getId(); - try { - otaPackageService.deleteOtaPackage(tenantId, otaPackageId); - notificationEntityService.notifyEntity(tenantId, otaPackageId, otaPackageInfo, null, - ActionType.DELETED, user, null, otaPackageInfo.getId().toString()); - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), null, null, - ActionType.DELETED, user, e, otaPackageInfo.getId().toString()); - throw handleException(e); - } - } - - @Override - public OtaPackageInfo saveOtaPackageData(OtaPackageInfo otaPackageInfo, String checksum, ChecksumAlgorithm checksumAlgorithm, - byte[] data, String filename, String contentType, SecurityUser user) throws ThingsboardException { - TenantId tenantId = otaPackageInfo.getTenantId(); - OtaPackageId otaPackageId = otaPackageInfo.getId(); - try { - if (StringUtils.isEmpty(checksum)) { - checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); - } - OtaPackage otaPackage = new OtaPackage(otaPackageId); - otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime()); - otaPackage.setTenantId(tenantId); - otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId()); - otaPackage.setType(otaPackageInfo.getType()); - otaPackage.setTitle(otaPackageInfo.getTitle()); - otaPackage.setVersion(otaPackageInfo.getVersion()); - otaPackage.setTag(otaPackageInfo.getTag()); - otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo()); - otaPackage.setChecksumAlgorithm(checksumAlgorithm); - otaPackage.setChecksum(checksum); - otaPackage.setFileName(filename); - otaPackage.setContentType(contentType); - otaPackage.setData(ByteBuffer.wrap(data)); - otaPackage.setDataSize((long) data.length); - OtaPackageInfo savedOtaPackage = otaPackageService.saveOtaPackage(otaPackage); - notificationEntityService.notifyEntity(tenantId, savedOtaPackage.getId(), savedOtaPackage, null, - ActionType.UPDATED, user, null); - return savedOtaPackage; - } catch (Exception e) { - notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.OTA_PACKAGE), null, null, - ActionType.UPDATED, user, e, otaPackageId.toString()); - throw handleException(e); - } - } -} diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/queue/DefaultTbQueueService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/queue/DefaultTbQueueService.java index 6a5778a474..3a1362c570 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/queue/DefaultTbQueueService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/queue/DefaultTbQueueService.java @@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.queue.Queue; import org.thingsboard.server.common.data.tenant.profile.TenantProfileQueueConfiguration; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.queue.QueueService; import org.thingsboard.server.queue.TbQueueAdmin; import org.thingsboard.server.queue.scheduler.SchedulerComponent; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -49,6 +50,7 @@ public class DefaultTbQueueService extends AbstractTbEntityService implements Tb private static final String MAIN = "Main"; private static final long DELETE_DELAY = 30; + private final QueueService queueService; private final TbClusterService tbClusterService; private final TbQueueAdmin tbQueueAdmin; private final DeviceProfileService deviceProfileService; diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/DefaultTbTenantService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/DefaultTbTenantService.java index 2a8fc1bf0a..50dc591a52 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/DefaultTbTenantService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/DefaultTbTenantService.java @@ -22,7 +22,9 @@ import org.thingsboard.server.common.data.TenantProfile; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.dao.tenant.TbTenantProfileCache; import org.thingsboard.server.dao.tenant.TenantProfileService; +import org.thingsboard.server.dao.tenant.TenantService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.queue.TbQueueService; @@ -35,43 +37,37 @@ import java.util.Collections; @RequiredArgsConstructor public class DefaultTbTenantService extends AbstractTbEntityService implements TbTenantService { + private final TenantService tenantService; + private final TbTenantProfileCache tenantProfileCache; private final InstallScripts installScripts; private final TbQueueService tbQueueService; private final TenantProfileService tenantProfileService; @Override - public Tenant save(Tenant tenant) throws ThingsboardException { - try { - boolean created = tenant.getId() == null; - Tenant oldTenant = !created ? tenantService.findTenantById(tenant.getId()) : null; + public Tenant save(Tenant tenant) throws Exception { + boolean created = tenant.getId() == null; + Tenant oldTenant = !created ? tenantService.findTenantById(tenant.getId()) : null; - Tenant savedTenant = checkNotNull(tenantService.saveTenant(tenant)); - if (created) { - installScripts.createDefaultRuleChains(savedTenant.getId()); - installScripts.createDefaultEdgeRuleChains(savedTenant.getId()); - } - tenantProfileCache.evict(savedTenant.getId()); - notificationEntityService.notifyCreateOruUpdateTenant(savedTenant, created ? - ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); - - TenantProfile oldTenantProfile = oldTenant != null ? tenantProfileService.findTenantProfileById(TenantId.SYS_TENANT_ID, oldTenant.getTenantProfileId()) : null; - TenantProfile newTenantProfile = tenantProfileService.findTenantProfileById(TenantId.SYS_TENANT_ID, savedTenant.getTenantProfileId()); - tbQueueService.updateQueuesByTenants(Collections.singletonList(savedTenant.getTenantId()), newTenantProfile, oldTenantProfile); - return savedTenant; - } catch (Exception e) { - throw handleException(e); + Tenant savedTenant = checkNotNull(tenantService.saveTenant(tenant)); + if (created) { + installScripts.createDefaultRuleChains(savedTenant.getId()); + installScripts.createDefaultEdgeRuleChains(savedTenant.getId()); } + tenantProfileCache.evict(savedTenant.getId()); + notificationEntityService.notifyCreateOrUpdateTenant(savedTenant, created ? + ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + + TenantProfile oldTenantProfile = oldTenant != null ? tenantProfileService.findTenantProfileById(TenantId.SYS_TENANT_ID, oldTenant.getTenantProfileId()) : null; + TenantProfile newTenantProfile = tenantProfileService.findTenantProfileById(TenantId.SYS_TENANT_ID, savedTenant.getTenantProfileId()); + tbQueueService.updateQueuesByTenants(Collections.singletonList(savedTenant.getTenantId()), newTenantProfile, oldTenantProfile); + return savedTenant; } @Override public void delete(Tenant tenant) throws ThingsboardException { - try { - TenantId tenantId = tenant.getId(); - tenantService.deleteTenant(tenantId); - tenantProfileCache.evict(tenantId); - notificationEntityService.notifyDeleteTenant(tenant); - } catch (Exception e) { - throw handleException(e); - } + TenantId tenantId = tenant.getId(); + tenantService.deleteTenant(tenantId); + tenantProfileCache.evict(tenantId); + notificationEntityService.notifyDeleteTenant(tenant); } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/TbTenantService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/TbTenantService.java index c265b568cb..20e910f7b0 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/TbTenantService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/TbTenantService.java @@ -20,7 +20,7 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; public interface TbTenantService { - Tenant save(Tenant tenant) throws ThingsboardException; + Tenant save(Tenant tenant) throws Exception; void delete(Tenant tenant) throws ThingsboardException; diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/DefaultTbTenantProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/DefaultTbTenantProfileService.java similarity index 54% rename from application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/DefaultTbTenantProfileService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/DefaultTbTenantProfileService.java index 23d9f74b8e..a25c4acad7 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/DefaultTbTenantProfileService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/DefaultTbTenantProfileService.java @@ -13,16 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.tenant_profile; +package org.thingsboard.server.service.entitiy.tenant.profile; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.TenantProfile; +import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.dao.tenant.TbTenantProfileCache; import org.thingsboard.server.dao.tenant.TenantProfileService; import org.thingsboard.server.dao.tenant.TenantService; import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.queue.TbQueueService; import java.util.List; @@ -31,20 +35,31 @@ import java.util.List; @Service @TbCoreComponent @AllArgsConstructor -public class DefaultTbTenantProfileService implements TbTenantProfileService { +public class DefaultTbTenantProfileService extends AbstractTbEntityService implements TbTenantProfileService { private final TbQueueService tbQueueService; private final TenantProfileService tenantProfileService; private final TenantService tenantService; + private final TbTenantProfileCache tenantProfileCache; @Override - public TenantProfile saveTenantProfile(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile) { - TenantProfile savedTenantProfile = tenantProfileService.saveTenantProfile(tenantId, tenantProfile); - + public TenantProfile save(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile) throws ThingsboardException { + TenantProfile savedTenantProfile = checkNotNull(tenantProfileService.saveTenantProfile(tenantId, tenantProfile)); if (oldTenantProfile != null && savedTenantProfile.isIsolatedTbRuleEngine()) { List tenantIds = tenantService.findTenantIdsByTenantProfileId(savedTenantProfile.getId()); tbQueueService.updateQueuesByTenants(tenantIds, savedTenantProfile, oldTenantProfile); } + tenantProfileCache.put(savedTenantProfile); + tbClusterService.onTenantProfileChange(savedTenantProfile, null); + tbClusterService.broadcastEntityStateChangeEvent(TenantId.SYS_TENANT_ID, savedTenantProfile.getId(), + tenantProfile.getId() == null ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + return savedTenantProfile; } + + @Override + public void delete(TenantId tenantId, TenantProfile tenantProfile) throws ThingsboardException { + tenantProfileService.deleteTenantProfile(tenantId, tenantProfile.getId()); + tbClusterService.onTenantProfileDelete(tenantProfile, null); + } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/TbTenantProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/TbTenantProfileService.java similarity index 68% rename from application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/TbTenantProfileService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/TbTenantProfileService.java index 66c3cb138c..96d18e3577 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/tenant_profile/TbTenantProfileService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/tenant/profile/TbTenantProfileService.java @@ -13,11 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.tenant_profile; +package org.thingsboard.server.service.entitiy.tenant.profile; import org.thingsboard.server.common.data.TenantProfile; +import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; public interface TbTenantProfileService { - TenantProfile saveTenantProfile(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile); + TenantProfile save(TenantId tenantId, TenantProfile tenantProfile, TenantProfile oldTenantProfile) throws ThingsboardException; + + void delete(TenantId tenantId, TenantProfile tenantProfile) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java index 592496e6f8..d323f0154c 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java @@ -19,7 +19,6 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.rule.engine.api.MailService; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -28,9 +27,9 @@ import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.security.UserCredentials; +import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.system.SystemSecurityService; import javax.servlet.http.HttpServletRequest; @@ -44,52 +43,41 @@ import static org.thingsboard.server.controller.UserController.ACTIVATE_URL_PATT @Slf4j public class DefaultUserService extends AbstractTbEntityService implements TbUserService { + private final UserService userService; private final MailService mailService; private final SystemSecurityService systemSecurityService; @Override public User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, - HttpServletRequest request, SecurityUser user) throws ThingsboardException { + HttpServletRequest request, User user) throws ThingsboardException { ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - boolean sendEmail = tbUser.getId() == null && sendActivationMail; - User savedUser = checkNotNull(userService.saveUser(tbUser)); - if (sendEmail) { - UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); - String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); - String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, - userCredentials.getActivateToken()); - String email = savedUser.getEmail(); - try { - mailService.sendActivationEmail(activateUrl, email); - } catch (ThingsboardException e) { - userService.deleteUser(tenantId, savedUser.getId()); - throw e; - } + boolean sendEmail = tbUser.getId() == null && sendActivationMail; + User savedUser = checkNotNull(userService.saveUser(tbUser)); + if (sendEmail) { + UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); + String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); + String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, + userCredentials.getActivateToken()); + String email = savedUser.getEmail(); + try { + mailService.sendActivationEmail(activateUrl, email); + } catch (ThingsboardException e) { + userService.deleteUser(tenantId, savedUser.getId()); + throw e; } - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, customerId, savedUser.getId(), - savedUser, user, actionType, true, null); - return savedUser; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.USER), - tbUser, user, actionType, false, e); - throw handleException(e); } + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, customerId, savedUser.getId(), + savedUser, user, actionType, true, null); + return savedUser; } @Override - public void delete(TenantId tenantId, CustomerId customerId, User tbUser, SecurityUser user) throws ThingsboardException { + public void delete(TenantId tenantId, CustomerId customerId, User tbUser, User user) throws ThingsboardException { UserId userId = tbUser.getId(); - try { - List relatedEdgeIds = findRelatedEdgeIds(tenantId, userId); + List relatedEdgeIds = findRelatedEdgeIds(tenantId, userId); - userService.deleteUser(tenantId, userId); - notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, - ActionType.DELETED, relatedEdgeIds, user, userId.toString()); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.USER), - null, user, ActionType.DELETED, false, e, userId.toString()); - throw handleException(e); - } + userService.deleteUser(tenantId, userId); + notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, + ActionType.DELETED, relatedEdgeIds, user, userId.toString()); } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/TbUserService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/TbUserService.java index 177aad17cc..765733ba3e 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/TbUserService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/TbUserService.java @@ -19,12 +19,11 @@ import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.service.security.model.SecurityUser; import javax.servlet.http.HttpServletRequest; public interface TbUserService { - User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, HttpServletRequest request, SecurityUser user) throws ThingsboardException; + User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, HttpServletRequest request, User user) throws ThingsboardException; - void delete (TenantId tenantId, CustomerId customerId, User tbUser, SecurityUser user) throws ThingsboardException; + void delete(TenantId tenantId, CustomerId customerId, User tbUser, User user) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/DefaultWidgetsBundleService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/DefaultWidgetsBundleService.java similarity index 55% rename from application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/DefaultWidgetsBundleService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/DefaultWidgetsBundleService.java index f3d8dfc138..496150d000 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/DefaultWidgetsBundleService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/DefaultWidgetsBundleService.java @@ -13,41 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.widgetsBundle; +package org.thingsboard.server.service.entitiy.widgets.bundle; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.widget.WidgetsBundle; +import org.thingsboard.server.dao.widget.WidgetsBundleService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; @Service @TbCoreComponent @AllArgsConstructor -public class DefaultWidgetsBundleService extends AbstractTbEntityService implements TbWidgetsBundleService{ +public class DefaultWidgetsBundleService extends AbstractTbEntityService implements TbWidgetsBundleService { + + private final WidgetsBundleService widgetsBundleService; + @Override - public WidgetsBundle save(WidgetsBundle widgetsBundle, SecurityUser user) throws ThingsboardException { - try { + public WidgetsBundle save(WidgetsBundle widgetsBundle) throws ThingsboardException { WidgetsBundle savedWidgetsBundle = checkNotNull(widgetsBundleService.saveWidgetsBundle(widgetsBundle)); - notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), savedWidgetsBundle.getId(), - widgetsBundle.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED); + notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), savedWidgetsBundle.getId(), + widgetsBundle.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED); return savedWidgetsBundle; - } catch (Exception e) { - throw handleException(e); - } } @Override - public void delete(WidgetsBundle widgetsBundle, SecurityUser user) throws ThingsboardException { - try { - widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getTenantId(), widgetsBundle.getId()); - notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), widgetsBundle.getId(), - EdgeEventActionType.DELETED); - } catch (Exception e) { - throw handleException(e); - } + public void delete(WidgetsBundle widgetsBundle) throws ThingsboardException { + widgetsBundleService.deleteWidgetsBundle(widgetsBundle.getTenantId(), widgetsBundle.getId()); + notificationEntityService.notifySendMsgToEdgeService(widgetsBundle.getTenantId(), widgetsBundle.getId(), + EdgeEventActionType.DELETED); } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/TbWidgetsBundleService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/TbWidgetsBundleService.java similarity index 68% rename from application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/TbWidgetsBundleService.java rename to application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/TbWidgetsBundleService.java index 7672db1a71..89022ad7a5 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/widgetsBundle/TbWidgetsBundleService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/widgets/bundle/TbWidgetsBundleService.java @@ -13,10 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.service.entitiy.widgetsBundle; +package org.thingsboard.server.service.entitiy.widgets.bundle; +import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.widget.WidgetsBundle; -import org.thingsboard.server.service.entitiy.SimpleTbEntityService; -public interface TbWidgetsBundleService extends SimpleTbEntityService { +public interface TbWidgetsBundleService { + WidgetsBundle save(WidgetsBundle entity) throws ThingsboardException; + + void delete(WidgetsBundle entity) throws ThingsboardException; } diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java index b6ce83a4f4..1e74daf43c 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java @@ -22,10 +22,10 @@ import org.eclipse.leshan.core.model.DefaultDDFFileValidator; import org.eclipse.leshan.core.model.InvalidDDFFileException; import org.eclipse.leshan.core.model.ObjectModel; import org.springframework.stereotype.Service; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -40,7 +40,6 @@ import org.thingsboard.server.dao.exception.DataValidationException; import org.thingsboard.server.dao.resource.ResourceService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -218,35 +217,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements } @Override - public TbResource save(TbResource tbResource, SecurityUser user) throws ThingsboardException { + public TbResource save(TbResource tbResource, User user) throws ThingsboardException { ActionType actionType = tbResource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = tbResource.getTenantId(); - try { - TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); - tbClusterService.onResourceChange(savedResource, null); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedResource.getId(), - savedResource, user, actionType, false, null); - return savedResource; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.TB_RESOURCE), - tbResource, user, actionType, false, e); - throw handleException(e); - } + TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); + tbClusterService.onResourceChange(savedResource, null); + notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user); + return savedResource; } @Override - public void delete(TbResource tbResource, SecurityUser user) throws ThingsboardException { + public void delete(TbResource tbResource, User user) { TbResourceId resourceId = tbResource.getId(); TenantId tenantId = tbResource.getTenantId(); - try { - resourceService.deleteResource(tenantId, resourceId); - tbClusterService.onResourceDeleted(tbResource, null); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, resourceId, tbResource, user, ActionType.DELETED, - false, null, resourceId.toString()); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.TB_RESOURCE), null, user, ActionType.DELETED, - false, e, resourceId.toString()); - throw handleException(e); - } - }} + resourceService.deleteResource(tenantId, resourceId); + tbClusterService.onResourceDeleted(tbResource, null); + notificationEntityService.logEntityAction(tenantId, resourceId, tbResource, ActionType.DELETED, user, resourceId.toString()); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java b/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java index ac82f78ccb..a166978df7 100644 --- a/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java +++ b/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java @@ -22,7 +22,7 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.flow.TbRuleChainInputNode; import org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration; import org.thingsboard.rule.engine.flow.TbRuleChainOutputNode; -import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEventActionType; @@ -45,8 +45,9 @@ import org.thingsboard.server.dao.relation.RelationService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.install.InstallScripts; +import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -65,6 +66,7 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement private final RuleChainService ruleChainService; private final RelationService relationService; + private final InstallScripts installScripts; @Override public Set getRuleChainOutputLabels(TenantId tenantId, RuleChainId ruleChainId) { @@ -164,238 +166,166 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement } @Override - public RuleChain save(RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public RuleChain save(RuleChain ruleChain, User user) throws ThingsboardException { TenantId tenantId = ruleChain.getTenantId(); ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - try { - RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain)); + RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain)); - if (RuleChainType.CORE.equals(savedRuleChain.getType())) { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), - actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); - } - boolean sendMsgToEdge = RuleChainType.EDGE.equals(savedRuleChain.getType()) && actionType.equals(ActionType.UPDATED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedRuleChain.getId(), - savedRuleChain, user, actionType, sendMsgToEdge, null); - return savedRuleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - ruleChain, user, actionType, false, e); - throw handleException(e); + if (RuleChainType.CORE.equals(savedRuleChain.getType())) { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), + actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); } + boolean sendMsgToEdge = RuleChainType.EDGE.equals(savedRuleChain.getType()) && actionType.equals(ActionType.UPDATED); + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedRuleChain.getId(), + savedRuleChain, user, actionType, sendMsgToEdge, null); + return savedRuleChain; } @Override - public void delete(RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public void delete(RuleChain ruleChain, User user) { TenantId tenantId = ruleChain.getTenantId(); RuleChainId ruleChainId = ruleChain.getId(); - try { - List referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId); - - Set referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet()); + List referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId); - List relatedEdgeIds = null; - if (RuleChainType.EDGE.equals(ruleChain.getType())) { - relatedEdgeIds = findRelatedEdgeIds(tenantId, ruleChainId); - } + Set referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet()); - ruleChainService.deleteRuleChainById(tenantId, ruleChainId); + List relatedEdgeIds = null; + if (RuleChainType.EDGE.equals(ruleChain.getType())) { + relatedEdgeIds = findRelatedEdgeIds(tenantId, ruleChainId); + } - referencingRuleChainIds.remove(ruleChain.getId()); + ruleChainService.deleteRuleChainById(tenantId, ruleChainId); - if (RuleChainType.CORE.equals(ruleChain.getType())) { - referencingRuleChainIds.forEach(referencingRuleChainId -> - tbClusterService.broadcastEntityStateChangeEvent(tenantId, referencingRuleChainId, ComponentLifecycleEvent.UPDATED)); + referencingRuleChainIds.remove(ruleChain.getId()); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChain.getId(), ComponentLifecycleEvent.DELETED); - } + if (RuleChainType.CORE.equals(ruleChain.getType())) { + referencingRuleChainIds.forEach(referencingRuleChainId -> + tbClusterService.broadcastEntityStateChangeEvent(tenantId, referencingRuleChainId, ComponentLifecycleEvent.UPDATED)); - notificationEntityService.notifyDeleteRuleChain(tenantId, ruleChain, relatedEdgeIds, user); - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.DELETED, false, e, ruleChainId.toString()); - throw handleException(e); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChain.getId(), ComponentLifecycleEvent.DELETED); } + + notificationEntityService.notifyDeleteRuleChain(tenantId, ruleChain, relatedEdgeIds, user); } @Override - public RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, SecurityUser user) throws ThingsboardException { - try { - RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName()); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedRuleChain.getId(), - savedRuleChain, user, ActionType.ADDED, false, null); - return savedRuleChain; - } catch (Exception e) { - RuleChain ruleChain = new RuleChain(); - ruleChain.setName(request.getName()); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - ruleChain, user, ActionType.ADDED, false, e); - throw handleException(e); - } + public RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, User user) throws IOException { + RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName()); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED); + notificationEntityService.logEntityAction(tenantId, savedRuleChain.getId(), savedRuleChain, ActionType.ADDED, user); + return savedRuleChain; } @Override - public RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); - if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) { - if (previousRootRuleChain != null) { - RuleChainId previousRootRuleChainId = previousRootRuleChain.getId(); - previousRootRuleChain = ruleChainService.findRuleChainById(tenantId, previousRootRuleChainId); - - tbClusterService.broadcastEntityStateChangeEvent(tenantId, previousRootRuleChainId, - ComponentLifecycleEvent.UPDATED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, previousRootRuleChainId, - previousRootRuleChain, user, ActionType.UPDATED, false, null); - } - ruleChain = ruleChainService.findRuleChainById(tenantId, ruleChainId); + RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); + if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) { + if (previousRootRuleChain != null) { + RuleChainId previousRootRuleChainId = previousRootRuleChain.getId(); + previousRootRuleChain = ruleChainService.findRuleChainById(tenantId, previousRootRuleChainId); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, + tbClusterService.broadcastEntityStateChangeEvent(tenantId, previousRootRuleChainId, ComponentLifecycleEvent.UPDATED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, ruleChainId, - ruleChain, user, ActionType.UPDATED, false, null); + notificationEntityService.logEntityAction(tenantId, previousRootRuleChainId, previousRootRuleChain, + ActionType.UPDATED, user); } - return ruleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - ruleChain, user, ActionType.UPDATED, false, e, ruleChainId.toString()); - throw handleException(e); + ruleChain = ruleChainService.findRuleChainById(tenantId, ruleChainId); + + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, + ComponentLifecycleEvent.UPDATED); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); } + return ruleChain; } @Override public RuleChainMetaData saveRuleChainMetaData(TenantId tenantId, RuleChain ruleChain, RuleChainMetaData ruleChainMetaData, - boolean updateRelated, SecurityUser user) throws ThingsboardException { + boolean updateRelated, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainMetaDataId = ruleChainMetaData.getRuleChainId(); - try { - RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); - checkNotNull(result.isSuccess() ? true : null); + RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); + checkNotNull(result.isSuccess() ? true : null); + + List updatedRuleChains; + if (updateRelated && result.isSuccess()) { + updatedRuleChains = updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result); + } else { + updatedRuleChains = Collections.emptyList(); + } - List updatedRuleChains; - if (updateRelated && result.isSuccess()) { - updatedRuleChains = tbRuleChainService.updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result); - } else { - updatedRuleChains = Collections.emptyList(); - } + RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId)); - RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId)); + if (RuleChainType.CORE.equals(ruleChain.getType())) { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, ComponentLifecycleEvent.UPDATED); + updatedRuleChains.forEach(updatedRuleChain -> { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, updatedRuleChain.getId(), ComponentLifecycleEvent.UPDATED); + }); + } - if (RuleChainType.CORE.equals(ruleChain.getType())) { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, ComponentLifecycleEvent.UPDATED); - updatedRuleChains.forEach(updatedRuleChain -> { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, updatedRuleChain.getId(), ComponentLifecycleEvent.UPDATED); - }); - } + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user, ruleChainMetaData); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, ruleChainId, - ruleChain, user, ActionType.UPDATED, false, null, ruleChainMetaData); + if (RuleChainType.EDGE.equals(ruleChain.getType())) { + notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED); + } + for (RuleChain updatedRuleChain : updatedRuleChains) { if (RuleChainType.EDGE.equals(ruleChain.getType())) { - notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED); - } - - for (RuleChain updatedRuleChain : updatedRuleChains) { - if (RuleChainType.EDGE.equals(ruleChain.getType())) { - notificationEntityService.notifySendMsgToEdgeService(tenantId, updatedRuleChain.getId(), EdgeEventActionType.UPDATED); - } else { - RuleChainMetaData updatedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, updatedRuleChain.getId())); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, updatedRuleChain.getId(), - updatedRuleChain, user, ActionType.UPDATED, false, null, updatedRuleChainMetaData); - } + notificationEntityService.notifySendMsgToEdgeService(tenantId, updatedRuleChain.getId(), EdgeEventActionType.UPDATED); + } else { + RuleChainMetaData updatedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, updatedRuleChain.getId())); + notificationEntityService.logEntityAction(tenantId, updatedRuleChain.getId(), updatedRuleChain, + ActionType.UPDATED, user, updatedRuleChainMetaData); } - return savedRuleChainMetaData; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.ADDED, false, e, ruleChainMetaData); - throw handleException(e); } + return savedRuleChainMetaData; } @Override - public RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, SecurityUser user) throws ThingsboardException { + public RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edge.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, - null, edge.getId(), - savedRuleChain, ActionType.ASSIGNED_TO_EDGE, - user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); - return savedRuleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.ASSIGNED_TO_EDGE, false, e, ruleChainId.toString(), edge.getId().toString()); - throw handleException(e); - } + RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edge.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, + null, edge.getId(), savedRuleChain, ActionType.ASSIGNED_TO_EDGE, + user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); + return savedRuleChain; } @Override - public RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, SecurityUser user) throws ThingsboardException { + public RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edge.getId(), false)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, - null, edge.getId(), - savedRuleChain, ActionType.UNASSIGNED_FROM_EDGE, - user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); - return savedRuleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.UNASSIGNED_FROM_EDGE, false, e, ruleChainId.toString(), edge.getId().toString()); - throw handleException(e); - } + RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edge.getId(), false)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, + null, edge.getId(), savedRuleChain, ActionType.UNASSIGNED_FROM_EDGE, + user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); + return savedRuleChain; } @Override - public RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId); - - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, ruleChainId, - ruleChain, user, ActionType.UPDATED, false, null); - return ruleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.UPDATED, false, e, ruleChainId.toString()); - throw handleException(e); - } + ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; } @Override - public RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId); - - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, ruleChainId, - ruleChain, user, ActionType.UPDATED, false, null); - return ruleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.UPDATED, false, e, ruleChainId.toString()); - throw handleException(e); - } + ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; } @Override - public RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException { + public RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - try { - ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, ruleChainId, - ruleChain, user, ActionType.UPDATED, false, null); - return ruleChain; - } catch (Exception e) { - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, emptyId(EntityType.RULE_CHAIN), - null, user, ActionType.UPDATED, false, e, ruleChainId.toString()); - throw handleException(e); - } + ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; } - public Set updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map labelsMap) { + private Set updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map labelsMap) { Set updatedRuleChains = new HashSet<>(); List usageList = getOutputLabelUsage(tenantId, ruleChainId); for (RuleChainOutputLabelsUsage usage : usageList) { diff --git a/application/src/main/java/org/thingsboard/server/service/rule/TbRuleChainService.java b/application/src/main/java/org/thingsboard/server/service/rule/TbRuleChainService.java index dbdba7d4ef..79817667f3 100644 --- a/application/src/main/java/org/thingsboard/server/service/rule/TbRuleChainService.java +++ b/application/src/main/java/org/thingsboard/server/service/rule/TbRuleChainService.java @@ -15,6 +15,7 @@ */ package org.thingsboard.server.service.rule; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.RuleChainId; @@ -25,8 +26,8 @@ import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.rule.RuleChainOutputLabelsUsage; import org.thingsboard.server.common.data.rule.RuleChainUpdateResult; import org.thingsboard.server.service.entitiy.SimpleTbEntityService; -import org.thingsboard.server.service.security.model.SecurityUser; +import java.io.IOException; import java.util.List; import java.util.Set; @@ -38,21 +39,20 @@ public interface TbRuleChainService extends SimpleTbEntityService { List updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, RuleChainUpdateResult result); - RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, SecurityUser user) throws ThingsboardException; + RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, User user) throws IOException; - RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException; + RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException; RuleChainMetaData saveRuleChainMetaData(TenantId tenantId, RuleChain ruleChain, RuleChainMetaData ruleChainMetaData, - boolean updateRelated, SecurityUser user) throws ThingsboardException; + boolean updateRelated, User user) throws ThingsboardException; - RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, - SecurityUser user) throws ThingsboardException; - RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, - SecurityUser user) throws ThingsboardException; + RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException; - RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException; + RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException; - RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException; + RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException; - RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, SecurityUser user) throws ThingsboardException; + RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException; + + RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException; } diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/ClaimDevicesService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/ClaimDevicesService.java index 72ec2eeb7f..6029e742d7 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/ClaimDevicesService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/ClaimDevicesService.java @@ -23,13 +23,11 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.dao.device.claim.ClaimResult; import org.thingsboard.server.dao.device.claim.ReclaimResult; -import java.util.concurrent.ExecutionException; - public interface ClaimDevicesService { ListenableFuture registerClaimingInfo(TenantId tenantId, DeviceId deviceId, String secretKey, long durationMs); - ListenableFuture claimDevice(Device device, CustomerId customerId, String secretKey) throws ExecutionException, InterruptedException; + ListenableFuture claimDevice(Device device, CustomerId customerId, String secretKey); ListenableFuture reClaimDevice(TenantId tenantId, Device device); From 1d3d000be214cea7fb242ffeede2b0e6a728fd3b Mon Sep 17 00:00:00 2001 From: YevhenBondarenko Date: Wed, 22 Jun 2022 00:46:13 +0200 Subject: [PATCH 3/7] refactored due to deprecated handleException --- .../server/controller/AlarmController.java | 36 +- .../server/controller/AssetController.java | 131 +++----- .../server/controller/CustomerController.java | 29 +- .../controller/DashboardController.java | 194 ++++------- .../server/controller/DeviceController.java | 310 +++++++----------- .../controller/DeviceProfileController.java | 45 +-- .../server/controller/EdgeController.java | 128 +++----- .../controller/EntityRelationController.java | 41 +-- .../controller/EntityViewController.java | 141 +++----- .../controller/OtaPackageController.java | 56 +--- .../server/controller/QueueController.java | 65 ++-- .../controller/RuleChainController.java | 167 +++------- .../controller/TbResourceController.java | 29 +- .../server/controller/TenantController.java | 14 +- .../server/controller/UserController.java | 34 +- .../controller/WidgetsBundleController.java | 30 +- .../device/DeviceBulkImportService.java | 6 +- .../entitiy/AbstractTbEntityService.java | 6 + .../entitiy/alarm/DefaultTbAlarmService.java | 13 +- .../entitiy/asset/DefaultTbAssetService.java | 116 ++++--- .../customer/DefaultTbCustomerService.java | 29 +- .../dashboard/DefaultTbDashboardService.java | 234 ++++++++----- .../device/DefaultTbDeviceService.java | 169 +++++++--- .../entitiy/device/TbDeviceService.java | 4 +- .../DefaultTbDeviceProfileService.java | 83 +++-- .../entitiy/edge/DefaultTbEdgeService.java | 96 ++++-- .../DefaultTbEntityRelationService.java | 42 ++- .../DefaultTbEntityViewService.java | 153 +++++---- .../ota/DefaultTbOtaPackageService.java | 75 +++-- .../entitiy/user/DefaultUserService.java | 52 +-- .../resource/DefaultTbResourceService.java | 28 +- .../rule/DefaultTbRuleChainService.java | 235 ++++++++----- 32 files changed, 1349 insertions(+), 1442 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java index a9d20f88a2..f53eb28e20 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java @@ -30,14 +30,12 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmInfo; import org.thingsboard.server.common.data.alarm.AlarmQuery; import org.thingsboard.server.common.data.alarm.AlarmSearchStatus; import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.alarm.AlarmStatus; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AlarmId; @@ -136,13 +134,7 @@ public class AlarmController extends BaseController { public Alarm saveAlarm(@ApiParam(value = "A JSON value representing the alarm.") @RequestBody Alarm alarm) throws ThingsboardException { alarm.setTenantId(getTenantId()); checkEntity(alarm.getId(), alarm, Resource.ALARM); - try { - return tbAlarmService.save(alarm, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ALARM), alarm, actionType, getCurrentUser(), e); - throw handleException(e); - } + return tbAlarmService.save(alarm, getCurrentUser()); } @ApiOperation(value = "Delete Alarm (deleteAlarm)", @@ -152,13 +144,9 @@ public class AlarmController extends BaseController { @ResponseBody public Boolean deleteAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException { checkParameter(ALARM_ID, strAlarmId); - try { - AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); - Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); - return tbAlarmService.delete(alarm, getCurrentUser()); - } catch (Exception e) { - throw handleException(e); - } + AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); + Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); + return tbAlarmService.delete(alarm, getCurrentUser()); } @ApiOperation(value = "Acknowledge Alarm (ackAlarm)", @@ -168,15 +156,11 @@ public class AlarmController extends BaseController { @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) - public void ackAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException { + public void ackAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws Exception { checkParameter(ALARM_ID, strAlarmId); AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); - try { - tbAlarmService.ack(alarm, getCurrentUser()).get(); - } catch (Exception e) { - throw handleException(e); - } + tbAlarmService.ack(alarm, getCurrentUser()).get(); } @ApiOperation(value = "Clear Alarm (clearAlarm)", @@ -186,15 +170,11 @@ public class AlarmController extends BaseController { @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) - public void clearAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException { + public void clearAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws Exception { checkParameter(ALARM_ID, strAlarmId); AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); - try { - tbAlarmService.clear(alarm, getCurrentUser()).get(); - } catch (Exception e) { - throw handleException(e); - } + tbAlarmService.clear(alarm, getCurrentUser()).get(); } @ApiOperation(value = "Get Alarms (getAlarms)", diff --git a/application/src/main/java/org/thingsboard/server/controller/AssetController.java b/application/src/main/java/org/thingsboard/server/controller/AssetController.java index 39a575949f..77df4100dc 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AssetController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AssetController.java @@ -34,11 +34,9 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetInfo; import org.thingsboard.server.common.data.asset.AssetSearchQuery; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -146,18 +144,12 @@ public class AssetController extends BaseController { @RequestMapping(value = "/asset", method = RequestMethod.POST) @ResponseBody public Asset saveAsset(@ApiParam(value = "A JSON value representing the asset.") @RequestBody Asset asset) throws ThingsboardException { - try { - if (TB_SERVICE_QUEUE.equals(asset.getType())) { - throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); - } - asset.setTenantId(getTenantId()); - checkEntity(asset.getId(), asset, Resource.ASSET); - return tbAssetService.save(asset, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), asset, actionType, getCurrentUser(), e); - throw handleException(e); + if (TB_SERVICE_QUEUE.equals(asset.getType())) { + throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS); } + asset.setTenantId(getTenantId()); + checkEntity(asset.getId(), asset, Resource.ASSET); + return tbAssetService.save(asset, getCurrentUser()); } @ApiOperation(value = "Delete asset (deleteAsset)", @@ -165,17 +157,11 @@ public class AssetController extends BaseController { @PreAuthorize("hasAuthority('TENANT_ADMIN')") @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) - public void deleteAsset(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { + public void deleteAsset(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws Exception { checkParameter(ASSET_ID, strAssetId); - try { - AssetId assetId = new AssetId(toUUID(strAssetId)); - Asset asset = checkAssetId(assetId, Operation.DELETE); - tbAssetService.delete(asset, getCurrentUser()).get(); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), ActionType.DELETED, - getCurrentUser(), e, strAssetId); - throw handleException(e); - } + AssetId assetId = new AssetId(toUUID(strAssetId)); + Asset asset = checkAssetId(assetId, Operation.DELETE); + tbAssetService.delete(asset, getCurrentUser()).get(); } @ApiOperation(value = "Assign asset to customer (assignAssetToCustomer)", @@ -185,21 +171,13 @@ public class AssetController extends BaseController { @ResponseBody public Asset assignAssetToCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable("customerId") String strCustomerId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - try { - checkParameter("customerId", strCustomerId); - checkParameter(ASSET_ID, strAssetId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); - return tbAssetService.assignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, - getCurrentUser(), e, strAssetId, strCustomerId); - - throw handleException(e); - } + checkParameter("customerId", strCustomerId); + checkParameter(ASSET_ID, strAssetId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); + return tbAssetService.assignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); } @ApiOperation(value = "Unassign asset from customer (unassignAssetFromCustomer)", @@ -208,21 +186,14 @@ public class AssetController extends BaseController { @RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE) @ResponseBody public Asset unassignAssetFromCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - try { - checkParameter(ASSET_ID, strAssetId); - AssetId assetId = new AssetId(toUUID(strAssetId)); - Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER); - if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Asset isn't assigned to any customer!"); - } - Customer customer = checkCustomerId(asset.getCustomerId(), Operation.READ); - return tbAssetService.unassignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, - getCurrentUser(), e, strAssetId); - throw handleException(e); + checkParameter(ASSET_ID, strAssetId); + AssetId assetId = new AssetId(toUUID(strAssetId)); + Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER); + if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Asset isn't assigned to any customer!"); } + Customer customer = checkCustomerId(asset.getCustomerId(), Operation.READ); + return tbAssetService.unassignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser()); } @ApiOperation(value = "Make asset publicly available (assignAssetToPublicCustomer)", @@ -233,16 +204,10 @@ public class AssetController extends BaseController { @RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST) @ResponseBody public Asset assignAssetToPublicCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - try { - checkParameter(ASSET_ID, strAssetId); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); - return tbAssetService.assignAssetToPublicCustomer(getTenantId(), assetId, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, getCurrentUser(), e, strAssetId); - throw handleException(e); - } + checkParameter(ASSET_ID, strAssetId); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); + return tbAssetService.assignAssetToPublicCustomer(getTenantId(), assetId, getCurrentUser()); } @ApiOperation(value = "Get Tenant Assets (getTenantAssets)", @@ -485,23 +450,16 @@ public class AssetController extends BaseController { @ResponseBody public Asset assignAssetToEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ASSET_ID, strAssetId); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ASSET_ID, strAssetId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - checkAssetId(assetId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + checkAssetId(assetId, Operation.READ); - return tbAssetService.assignAssetToEdge(getTenantId(), assetId, edge, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_EDGE; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, - getCurrentUser(), e, strAssetId, strEdgeId); - throw handleException(e); - } + return tbAssetService.assignAssetToEdge(getTenantId(), assetId, edge, getCurrentUser()); } @ApiOperation(value = "Unassign asset from edge (unassignAssetFromEdge)", @@ -516,22 +474,15 @@ public class AssetController extends BaseController { @ResponseBody public Asset unassignAssetFromEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ASSET_ID, strAssetId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ASSET_ID, strAssetId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - AssetId assetId = new AssetId(toUUID(strAssetId)); - Asset asset = checkAssetId(assetId, Operation.READ); + AssetId assetId = new AssetId(toUUID(strAssetId)); + Asset asset = checkAssetId(assetId, Operation.READ); - return tbAssetService.unassignAssetFromEdge(getTenantId(), asset, edge, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), actionType, - getCurrentUser(), e, strAssetId, strEdgeId); - throw handleException(e); - } + return tbAssetService.unassignAssetFromEdge(getTenantId(), asset, edge, getCurrentUser()); } @ApiOperation(value = "Get assets assigned to edge (getEdgeAssets)", diff --git a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java index 6979f0f0a6..6dba5584df 100644 --- a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java +++ b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java @@ -32,8 +32,6 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.TenantId; @@ -145,16 +143,9 @@ public class CustomerController extends BaseController { @RequestMapping(value = "/customer", method = RequestMethod.POST) @ResponseBody public Customer saveCustomer(@ApiParam(value = "A JSON value representing the customer.") @RequestBody Customer customer) throws ThingsboardException { - try { - customer.setTenantId(getTenantId()); - checkEntity(customer.getId(), customer, Resource.CUSTOMER); - return tbCustomerService.save(customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.CUSTOMER), customer, - actionType, getCurrentUser(), e); - throw handleException(e); - } + customer.setTenantId(getTenantId()); + checkEntity(customer.getId(), customer, Resource.CUSTOMER); + return tbCustomerService.save(customer, getCurrentUser()); } @ApiOperation(value = "Delete Customer (deleteCustomer)", @@ -166,16 +157,10 @@ public class CustomerController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void deleteCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException { - try { - checkParameter(CUSTOMER_ID, strCustomerId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.DELETE); - tbCustomerService.delete(customer, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.CUSTOMER), ActionType.DELETED, - getCurrentUser(), e, strCustomerId); - throw handleException(e); - } + checkParameter(CUSTOMER_ID, strCustomerId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.DELETE); + tbCustomerService.delete(customer, getCurrentUser()); } @ApiOperation(value = "Get Tenant Customers (getCustomers)", diff --git a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java index c8e1d6408e..05ef42017f 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java @@ -39,12 +39,10 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DashboardInfo; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.HomeDashboard; import org.thingsboard.server.common.data.HomeDashboardInfo; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -183,16 +181,9 @@ public class DashboardController extends BaseController { public Dashboard saveDashboard( @ApiParam(value = "A JSON value representing the dashboard.") @RequestBody Dashboard dashboard) throws ThingsboardException { - try { - dashboard.setTenantId(getTenantId()); - checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD); - return tbDashboardService.save(dashboard, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), dashboard, - actionType, getCurrentUser(), e); - throw handleException(e); - } + dashboard.setTenantId(getTenantId()); + checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD); + return tbDashboardService.save(dashboard, getCurrentUser()); } @ApiOperation(value = "Delete the Dashboard (deleteDashboard)", @@ -203,16 +194,10 @@ public class DashboardController extends BaseController { public void deleteDashboard( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE); - tbDashboardService.delete(dashboard, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), ActionType.DELETED, - getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE); + tbDashboardService.delete(dashboard, getCurrentUser()); } @ApiOperation(value = "Assign the Dashboard (assignDashboardToCustomer)", @@ -227,22 +212,15 @@ public class DashboardController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter(CUSTOMER_ID, strCustomerId); - checkParameter(DASHBOARD_ID, strDashboardId); + checkParameter(CUSTOMER_ID, strCustomerId); + checkParameter(DASHBOARD_ID, strDashboardId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - return tbDashboardService.assignDashboardToCustomer(dashboard, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, - getCurrentUser(), e, strDashboardId, strCustomerId); - throw handleException(e); - } + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + return tbDashboardService.assignDashboardToCustomer(dashboard, customer, getCurrentUser()); } @ApiOperation(value = "Unassign the Dashboard (unassignDashboardFromCustomer)", @@ -257,20 +235,13 @@ public class DashboardController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter("customerId", strCustomerId); - checkParameter(DASHBOARD_ID, strDashboardId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - return tbDashboardService.unassignDashboardFromCustomer(dashboard, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), - actionType, getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter("customerId", strCustomerId); + checkParameter(DASHBOARD_ID, strDashboardId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + return tbDashboardService.unassignDashboardFromCustomer(dashboard, customer, getCurrentUser()); } @ApiOperation(value = "Update the Dashboard Customers (updateDashboardCustomers)", @@ -287,18 +258,11 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids, or empty to remove all customers") @RequestBody(required = false) String[] strCustomerIds) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.updateDashboardCustomers(dashboard, customerIds, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, - getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.updateDashboardCustomers(dashboard, customerIds, getCurrentUser()); } @ApiOperation(value = "Adds the Dashboard Customers (addDashboardCustomers)", @@ -314,18 +278,11 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids") @RequestBody String[] strCustomerIds) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.addDashboardCustomers(dashboard, customerIds, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), - actionType, getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.addDashboardCustomers(dashboard, customerIds, getCurrentUser()); } @ApiOperation(value = "Remove the Dashboard Customers (removeDashboardCustomers)", @@ -341,18 +298,11 @@ public class DashboardController extends BaseController { @PathVariable(DASHBOARD_ID) String strDashboardId, @ApiParam(value = "JSON array with the list of customer ids") @RequestBody String[] strCustomerIds) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - Set customerIds = customerIdFromStr(strCustomerIds, dashboard); - return tbDashboardService.removeDashboardCustomers(dashboard, customerIds, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), - actionType, getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + Set customerIds = customerIdFromStr(strCustomerIds, dashboard); + return tbDashboardService.removeDashboardCustomers(dashboard, customerIds, getCurrentUser()); } @ApiOperation(value = "Assign the Dashboard to Public Customer (assignDashboardToPublicCustomer)", @@ -369,17 +319,10 @@ public class DashboardController extends BaseController { public Dashboard assignDashboardToPublicCustomer( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); - return tbDashboardService.assignDashboardToPublicCustomer(dashboard, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), - actionType, getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); + return tbDashboardService.assignDashboardToPublicCustomer(dashboard, getCurrentUser()); } @ApiOperation(value = "Unassign the Dashboard from Public Customer (unassignDashboardFromPublicCustomer)", @@ -392,17 +335,10 @@ public class DashboardController extends BaseController { public Dashboard unassignDashboardFromPublicCustomer( @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter(DASHBOARD_ID, strDashboardId); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); - return tbDashboardService.unassignDashboardFromPublicCustomer(dashboard, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), actionType, - getCurrentUser(), e, strDashboardId); - throw handleException(e); - } + checkParameter(DASHBOARD_ID, strDashboardId); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); + return tbDashboardService.unassignDashboardFromPublicCustomer(dashboard, getCurrentUser()); } @ApiOperation(value = "Get Tenant Dashboards by System Administrator (getTenantDashboards)", @@ -687,22 +623,15 @@ public class DashboardController extends BaseController { @ResponseBody public Dashboard assignDashboardToEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter("edgeId", strEdgeId); - checkParameter(DASHBOARD_ID, strDashboardId); + checkParameter("edgeId", strEdgeId); + checkParameter(DASHBOARD_ID, strDashboardId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - checkDashboardId(dashboardId, Operation.READ); - return tbDashboardService.asignDashboardToEdge(getTenantId(), dashboardId, edge, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_EDGE; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - actionType, getCurrentUser(), e, strDashboardId, strEdgeId); - throw handleException(e); - } + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + checkDashboardId(dashboardId, Operation.READ); + return tbDashboardService.asignDashboardToEdge(getTenantId(), dashboardId, edge, getCurrentUser()); } @ApiOperation(value = "Unassign dashboard from edge (unassignDashboardFromEdge)", @@ -718,23 +647,16 @@ public class DashboardController extends BaseController { @ResponseBody public Dashboard unassignDashboardFromEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DASHBOARD_ID, strDashboardId); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DASHBOARD_ID, strDashboardId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); - Dashboard dashboard = checkDashboardId(dashboardId, Operation.READ); + DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); + Dashboard dashboard = checkDashboardId(dashboardId, Operation.READ); - return tbDashboardService.unassignDashboardFromEdge(dashboard, edge, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DASHBOARD), - actionType, getCurrentUser(), e, strDashboardId, strEdgeId); - throw handleException(e); - } + return tbDashboardService.unassignDashboardFromEdge(dashboard, edge, getCurrentUser()); } @ApiOperation(value = "Get Edge Dashboards (getEdgeDashboards)", diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java index 04b2b31b00..86b4e3ebef 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java @@ -43,10 +43,8 @@ import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceInfo; import org.thingsboard.server.common.data.EntitySubtype; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.SaveDeviceWithCredentialsRequest; import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.device.DeviceSearchQuery; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; @@ -168,20 +166,14 @@ public class DeviceController extends BaseController { public Device saveDevice(@ApiParam(value = "A JSON value representing the device.") @RequestBody Device device, @ApiParam(value = "Optional value of the device credentials to be used during device creation. " + "If omitted, access token will be auto-generated.") @RequestParam(name = "accessToken", required = false) String accessToken) throws ThingsboardException { - try { - device.setTenantId(getCurrentUser().getTenantId()); - Device oldDevice = null; - if (device.getId() != null) { - oldDevice = checkDeviceId(device.getId(), Operation.WRITE); - } else { - checkEntity(null, device, Resource.DEVICE); - } - return tbDeviceService.save(getTenantId(), device, oldDevice, accessToken, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), device, actionType, getCurrentUser(), e); - throw handleException(e); + device.setTenantId(getCurrentUser().getTenantId()); + Device oldDevice = null; + if (device.getId() != null) { + oldDevice = checkDeviceId(device.getId(), Operation.WRITE); + } else { + checkEntity(null, device, Resource.DEVICE); } + return tbDeviceService.save(device, oldDevice, accessToken, getCurrentUser()); } @ApiOperation(value = "Create Device (saveDevice) with credentials ", @@ -196,17 +188,10 @@ public class DeviceController extends BaseController { public Device saveDeviceWithCredentials(@ApiParam(value = "The JSON object with device and credentials. See method description above for example.") @RequestBody SaveDeviceWithCredentialsRequest deviceAndCredentials) throws ThingsboardException { Device device = checkNotNull(deviceAndCredentials.getDevice()); - try { - DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials()); - device.setTenantId(getCurrentUser().getTenantId()); - checkEntity(device.getId(), device, Resource.DEVICE); - return tbDeviceService.saveDeviceWithCredentials(getTenantId(), device, credentials, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), device, - actionType, getCurrentUser(), e); - throw handleException(e); - } + DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials()); + device.setTenantId(getCurrentUser().getTenantId()); + checkEntity(device.getId(), device, Resource.DEVICE); + return tbDeviceService.saveDeviceWithCredentials(device, credentials, getCurrentUser()); } @ApiOperation(value = "Delete device (deleteDevice)", @@ -215,17 +200,11 @@ public class DeviceController extends BaseController { @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void deleteDevice(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) - @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.DELETE); - tbDeviceService.delete(device, getCurrentUser()).get(); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), ActionType.DELETED, - getCurrentUser(), e, strDeviceId); - throw handleException(e); - } + @PathVariable(DEVICE_ID) String strDeviceId) throws Exception { + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.DELETE); + tbDeviceService.delete(device, getCurrentUser()).get(); } @ApiOperation(value = "Assign device to customer (assignDeviceToCustomer)", @@ -237,20 +216,13 @@ public class DeviceController extends BaseController { @PathVariable("customerId") String strCustomerId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter("customerId", strCustomerId); - checkParameter(DEVICE_ID, strDeviceId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); - return tbDeviceService.assignDeviceToCustomer(getTenantId(), deviceId, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, getCurrentUser(), - e, strDeviceId, strCustomerId); - throw handleException(e); - } + checkParameter("customerId", strCustomerId); + checkParameter(DEVICE_ID, strDeviceId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); + return tbDeviceService.assignDeviceToCustomer(getTenantId(), deviceId, customer, getCurrentUser()); } @ApiOperation(value = "Unassign device from customer (unassignDeviceFromCustomer)", @@ -261,22 +233,15 @@ public class DeviceController extends BaseController { public Device unassignDeviceFromCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { checkParameter(DEVICE_ID, strDeviceId); - try { - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.UNASSIGN_FROM_CUSTOMER); - if (device.getCustomerId() == null || device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Device isn't assigned to any customer!"); - } + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.UNASSIGN_FROM_CUSTOMER); + if (device.getCustomerId() == null || device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Device isn't assigned to any customer!"); + } - Customer customer = checkCustomerId(device.getCustomerId(), Operation.READ); + Customer customer = checkCustomerId(device.getCustomerId(), Operation.READ); - return tbDeviceService.unassignDeviceFromCustomer(device, customer, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, - getCurrentUser(), e, strDeviceId); - throw handleException(e); - } + return tbDeviceService.unassignDeviceFromCustomer(device, customer, getCurrentUser()); } @ApiOperation(value = "Make device publicly available (assignDeviceToPublicCustomer)", @@ -288,17 +253,10 @@ public class DeviceController extends BaseController { @ResponseBody public Device assignDeviceToPublicCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); - return tbDeviceService.assignDeviceToPublicCustomer(getTenantId(), deviceId, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), actionType, - getCurrentUser(), e, strDeviceId); - throw handleException(e); - } + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); + return tbDeviceService.assignDeviceToPublicCustomer(getTenantId(), deviceId, getCurrentUser()); } @ApiOperation(value = "Get Device Credentials (getDeviceCredentialsByDeviceId)", @@ -308,16 +266,10 @@ public class DeviceController extends BaseController { @ResponseBody public DeviceCredentials getDeviceCredentialsByDeviceId(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS); - return tbDeviceService.getDeviceCredentialsByDeviceId(device, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - ActionType.CREDENTIALS_READ, getCurrentUser(), e, strDeviceId); - throw handleException(e); - } + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS); + return tbDeviceService.getDeviceCredentialsByDeviceId(device, getCurrentUser()); } @ApiOperation(value = "Update device credentials (updateDeviceCredentials)", notes = "During device creation, platform generates random 'ACCESS_TOKEN' credentials. " + @@ -330,15 +282,9 @@ public class DeviceController extends BaseController { public DeviceCredentials updateDeviceCredentials( @ApiParam(value = "A JSON value representing the device credentials.") @RequestBody DeviceCredentials deviceCredentials) throws ThingsboardException { - try { - checkNotNull(deviceCredentials); - Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); - return tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - ActionType.CREDENTIALS_UPDATED, getCurrentUser(), e, deviceCredentials); - throw handleException(e); - } + checkNotNull(deviceCredentials); + Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); + return tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser()); } @ApiOperation(value = "Get Tenant Devices (getTenantDevices)", @@ -597,47 +543,43 @@ public class DeviceController extends BaseController { @PathVariable(DEVICE_NAME) String deviceName, @ApiParam(value = "Claiming request which can optionally contain secret key") @RequestBody(required = false) ClaimRequest claimRequest) throws ThingsboardException { - try { - checkParameter(DEVICE_NAME, deviceName); - final DeferredResult deferredResult = new DeferredResult<>(); - - SecurityUser user = getCurrentUser(); - TenantId tenantId = user.getTenantId(); - CustomerId customerId = user.getCustomerId(); + checkParameter(DEVICE_NAME, deviceName); + final DeferredResult deferredResult = new DeferredResult<>(); - Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); - accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, - device.getId(), device); - String secretKey = getSecretKey(claimRequest); - - ListenableFuture future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user); - - Futures.addCallback(future, new FutureCallback<>() { - @Override - public void onSuccess(@Nullable ClaimResult result) { - HttpStatus status; - if (result != null) { - if (result.getResponse().equals(ClaimResponse.SUCCESS)) { - status = HttpStatus.OK; - deferredResult.setResult(new ResponseEntity<>(result, status)); - } else { - status = HttpStatus.BAD_REQUEST; - deferredResult.setResult(new ResponseEntity<>(result.getResponse(), status)); - } + SecurityUser user = getCurrentUser(); + TenantId tenantId = user.getTenantId(); + CustomerId customerId = user.getCustomerId(); + + Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); + accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, + device.getId(), device); + String secretKey = getSecretKey(claimRequest); + + ListenableFuture future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user); + + Futures.addCallback(future, new FutureCallback<>() { + @Override + public void onSuccess(@Nullable ClaimResult result) { + HttpStatus status; + if (result != null) { + if (result.getResponse().equals(ClaimResponse.SUCCESS)) { + status = HttpStatus.OK; + deferredResult.setResult(new ResponseEntity<>(result, status)); } else { - deferredResult.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); + status = HttpStatus.BAD_REQUEST; + deferredResult.setResult(new ResponseEntity<>(result.getResponse(), status)); } + } else { + deferredResult.setResult(new ResponseEntity<>(HttpStatus.BAD_REQUEST)); } + } - @Override - public void onFailure(Throwable t) { - deferredResult.setErrorResult(t); - } - }, MoreExecutors.directExecutor()); - return deferredResult; - } catch (Exception e) { - throw handleException(e); - } + @Override + public void onFailure(Throwable t) { + deferredResult.setErrorResult(t); + } + }, MoreExecutors.directExecutor()); + return deferredResult; } @ApiOperation(value = "Reclaim device (reClaimDevice)", @@ -649,32 +591,28 @@ public class DeviceController extends BaseController { public DeferredResult reClaimDevice(@ApiParam(value = "Unique name of the device which is going to be reclaimed") @PathVariable(DEVICE_NAME) String deviceName) throws ThingsboardException { checkParameter(DEVICE_NAME, deviceName); - try { - final DeferredResult deferredResult = new DeferredResult<>(); + final DeferredResult deferredResult = new DeferredResult<>(); - SecurityUser user = getCurrentUser(); - TenantId tenantId = user.getTenantId(); + SecurityUser user = getCurrentUser(); + TenantId tenantId = user.getTenantId(); - Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); - accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, - device.getId(), device); + Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); + accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, + device.getId(), device); - ListenableFuture result = tbDeviceService.reclaimDevice(tenantId, device, user); - Futures.addCallback(result, new FutureCallback<>() { - @Override - public void onSuccess(ReclaimResult reclaimResult) { - deferredResult.setResult(new ResponseEntity(HttpStatus.OK)); - } + ListenableFuture result = tbDeviceService.reclaimDevice(tenantId, device, user); + Futures.addCallback(result, new FutureCallback<>() { + @Override + public void onSuccess(ReclaimResult reclaimResult) { + deferredResult.setResult(new ResponseEntity(HttpStatus.OK)); + } - @Override - public void onFailure(Throwable t) { - deferredResult.setErrorResult(t); - } - }, MoreExecutors.directExecutor()); - return deferredResult; - } catch (Exception e) { - throw handleException(e); - } + @Override + public void onFailure(Throwable t) { + deferredResult.setErrorResult(t); + } + }, MoreExecutors.directExecutor()); + return deferredResult; } private String getSecretKey(ClaimRequest claimRequest) { @@ -694,23 +632,17 @@ public class DeviceController extends BaseController { @PathVariable(TENANT_ID) String strTenantId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(TENANT_ID, strTenantId); - checkParameter(DEVICE_ID, strDeviceId); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT); - - TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId)); - Tenant newTenant = tenantService.findTenantById(newTenantId); - if (newTenant == null) { - throw new ThingsboardException("Could not find the specified Tenant!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); - } - return tbDeviceService.assignDeviceToTenant(device, newTenant, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - ActionType.ASSIGNED_TO_TENANT, getCurrentUser(), e, strDeviceId); - throw handleException(e); + checkParameter(TENANT_ID, strTenantId); + checkParameter(DEVICE_ID, strDeviceId); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT); + + TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId)); + Tenant newTenant = tenantService.findTenantById(newTenantId); + if (newTenant == null) { + throw new ThingsboardException("Could not find the specified Tenant!", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } + return tbDeviceService.assignDeviceToTenant(device, newTenant, getCurrentUser()); } @ApiOperation(value = "Assign device to edge (assignDeviceToEdge)", @@ -727,21 +659,15 @@ public class DeviceController extends BaseController { @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DEVICE_ID, strDeviceId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DEVICE_ID, strDeviceId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - checkDeviceId(deviceId, Operation.READ); + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + checkDeviceId(deviceId, Operation.READ); - return tbDeviceService.assignDeviceToEdge(getTenantId(), deviceId, edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strDeviceId, strEdgeId); - throw handleException(e); - } + return tbDeviceService.assignDeviceToEdge(getTenantId(), deviceId, edge, getCurrentUser()); } @ApiOperation(value = "Unassign device from edge (unassignDeviceFromEdge)", @@ -758,20 +684,14 @@ public class DeviceController extends BaseController { @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(DEVICE_ID, strDeviceId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(DEVICE_ID, strDeviceId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); - Device device = checkDeviceId(deviceId, Operation.READ); - return tbDeviceService.unassignDeviceFromEdge(device, edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), - ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strDeviceId, strEdgeId); - throw handleException(e); - } + DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); + Device device = checkDeviceId(deviceId, Operation.READ); + return tbDeviceService.unassignDeviceFromEdge(device, edge, getCurrentUser()); } @ApiOperation(value = "Get devices assigned to edge (getEdgeDevices)", diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java index 95961131e8..72d9b1c654 100644 --- a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java +++ b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java @@ -33,8 +33,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfileInfo; -import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.page.PageData; @@ -202,16 +200,9 @@ public class DeviceProfileController extends BaseController { public DeviceProfile saveDeviceProfile( @ApiParam(value = "A JSON value representing the device profile.") @RequestBody DeviceProfile deviceProfile) throws ThingsboardException { - try { - deviceProfile.setTenantId(getTenantId()); - checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE); - return tbDeviceProfileService.save(deviceProfile, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), deviceProfile, - actionType, getCurrentUser(), e); - throw handleException(e); - } + deviceProfile.setTenantId(getTenantId()); + checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE); + return tbDeviceProfileService.save(deviceProfile, getCurrentUser()); } @ApiOperation(value = "Delete device profile (deleteDeviceProfile)", @@ -224,16 +215,10 @@ public class DeviceProfileController extends BaseController { public void deleteDeviceProfile( @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { - try { - checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); - DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); - DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE); - tbDeviceProfileService.delete(deviceProfile, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), ActionType.DELETED, - getCurrentUser(), e, strDeviceProfileId); - throw handleException(e); - } + checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); + DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); + DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE); + tbDeviceProfileService.delete(deviceProfile, getCurrentUser()); } @ApiOperation(value = "Make Device Profile Default (setDefaultDeviceProfile)", @@ -245,17 +230,11 @@ public class DeviceProfileController extends BaseController { public DeviceProfile setDefaultDeviceProfile( @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { - try { - checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); - DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); - DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE); - DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId()); - return tbDeviceProfileService.setDefaultDeviceProfile(deviceProfile, previousDefaultDeviceProfile, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE_PROFILE), ActionType.UPDATED, - getCurrentUser(), e, strDeviceProfileId); - throw handleException(e); - } + checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); + DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); + DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE); + DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId()); + return tbDeviceProfileService.setDefaultDeviceProfile(deviceProfile, previousDefaultDeviceProfile, getCurrentUser()); } @ApiOperation(value = "Get Device Profiles (getDeviceProfiles)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java index 4e66eb17e2..9cecf86885 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java @@ -34,8 +34,6 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; -import org.thingsboard.server.common.data.EntityType; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeInfo; import org.thingsboard.server.common.data.edge.EdgeSearchQuery; @@ -149,30 +147,24 @@ public class EdgeController extends BaseController { @RequestMapping(value = "/edge", method = RequestMethod.POST) @ResponseBody public Edge saveEdge(@ApiParam(value = "A JSON value representing the edge.", required = true) - @RequestBody Edge edge) throws ThingsboardException { + @RequestBody Edge edge) throws Exception { TenantId tenantId = getTenantId(); - try { - edge.setTenantId(tenantId); - boolean created = edge.getId() == null; - - RuleChain edgeTemplateRootRuleChain = null; - if (created) { - edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId); - if (edgeTemplateRootRuleChain == null) { - throw new DataValidationException("Root edge rule chain is not available!"); - } + edge.setTenantId(tenantId); + boolean created = edge.getId() == null; + + RuleChain edgeTemplateRootRuleChain = null; + if (created) { + edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId); + if (edgeTemplateRootRuleChain == null) { + throw new DataValidationException("Root edge rule chain is not available!"); } + } - Operation operation = created ? Operation.CREATE : Operation.WRITE; + Operation operation = created ? Operation.CREATE : Operation.WRITE; - accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation, edge.getId(), edge); + accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation, edge.getId(), edge); - return tbEdgeService.save(edge, edgeTemplateRootRuleChain, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), edge, actionType, getCurrentUser(), e); - throw handleException(e); - } + return tbEdgeService.save(edge, edgeTemplateRootRuleChain, getCurrentUser()); } @ApiOperation(value = "Delete edge (deleteEdge)", @@ -182,16 +174,10 @@ public class EdgeController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void deleteEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.DELETE); - tbEdgeService.delete(edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), ActionType.DELETED, - getCurrentUser(), e, strEdgeId); - throw handleException(e); - } + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.DELETE); + tbEdgeService.delete(edge, getCurrentUser()); } @ApiOperation(value = "Get Tenant Edges (getEdges)", @@ -229,19 +215,13 @@ public class EdgeController extends BaseController { @PathVariable("customerId") String strCustomerId, @ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - try { - checkParameter("customerId", strCustomerId); - checkParameter(EDGE_ID, strEdgeId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); - return tbEdgeService.assignEdgeToCustomer(getTenantId(), edgeId, customer, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), - ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEdgeId, strCustomerId); - throw handleException(e); - } + checkParameter("customerId", strCustomerId); + checkParameter(EDGE_ID, strEdgeId); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); + return tbEdgeService.assignEdgeToCustomer(getTenantId(), edgeId, customer, getCurrentUser()); } @ApiOperation(value = "Unassign edge from customer (unassignEdgeFromCustomer)", @@ -252,21 +232,15 @@ public class EdgeController extends BaseController { @ResponseBody public Edge unassignEdgeFromCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER); - if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Edge isn't assigned to any customer!"); - } - Customer customer = checkCustomerId(edge.getCustomerId(), Operation.READ); - - return tbEdgeService.unassignEdgeFromCustomer(edge, customer, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), - ActionType.UNASSIGNED_FROM_CUSTOMER, getCurrentUser(), e, strEdgeId); - throw handleException(e); + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER); + if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Edge isn't assigned to any customer!"); } + Customer customer = checkCustomerId(edge.getCustomerId(), Operation.READ); + + return tbEdgeService.unassignEdgeFromCustomer(edge, customer, getCurrentUser()); } @ApiOperation(value = "Make edge publicly available (assignEdgeToPublicCustomer)", @@ -279,16 +253,10 @@ public class EdgeController extends BaseController { @ResponseBody public Edge assignEdgeToPublicCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); - return tbEdgeService.assignEdgeToPublicCustomer(getTenantId(), edgeId, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), - ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEdgeId); - throw handleException(e); - } + checkParameter(EDGE_ID, strEdgeId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); + return tbEdgeService.assignEdgeToPublicCustomer(getTenantId(), edgeId, getCurrentUser()); } @ApiOperation(value = "Get Tenant Edges (getTenantEdges)", @@ -383,21 +351,15 @@ public class EdgeController extends BaseController { public Edge setEdgeRootRuleChain(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @PathVariable(EDGE_ID) String strEdgeId, @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION, required = true) - @PathVariable("ruleChainId") String strRuleChainId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter("ruleChainId", strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - checkRuleChain(ruleChainId, Operation.WRITE); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); - accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge); - return tbEdgeService.setEdgeRootRuleChain(edge, ruleChainId, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.EDGE), - ActionType.UPDATED, getCurrentUser(), e, strEdgeId); - throw handleException(e); - } + @PathVariable("ruleChainId") String strRuleChainId) throws Exception { + checkParameter(EDGE_ID, strEdgeId); + checkParameter("ruleChainId", strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + checkRuleChain(ruleChainId, Operation.WRITE); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); + accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge); + return tbEdgeService.setEdgeRootRuleChain(edge, ruleChainId, getCurrentUser()); } @ApiOperation(value = "Get Customer Edges (getCustomerEdges)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java index e35dd59985..50b82847ac 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java @@ -28,7 +28,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityIdFactory; @@ -80,22 +79,14 @@ public class EntityRelationController extends BaseController { @ResponseStatus(value = HttpStatus.OK) public void saveRelation(@ApiParam(value = "A JSON value representing the relation.", required = true) @RequestBody EntityRelation relation) throws ThingsboardException { - try { - checkNotNull(relation); - checkEntityId(relation.getFrom(), Operation.WRITE); - checkEntityId(relation.getTo(), Operation.WRITE); - if (relation.getTypeGroup() == null) { - relation.setTypeGroup(RelationTypeGroup.COMMON); - } - - tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), relation.getFrom(), null, getCurrentUser().getCustomerId(), - ActionType.RELATION_ADD_OR_UPDATE, getCurrentUser(), e, relation); - notificationEntityService.logEntityAction(getTenantId(), relation.getTo(), null, getCurrentUser().getCustomerId(), - ActionType.RELATION_ADD_OR_UPDATE, getCurrentUser(), e, relation); - throw handleException(e); + checkNotNull(relation); + checkEntityId(relation.getFrom(), Operation.WRITE); + checkEntityId(relation.getTo(), Operation.WRITE); + if (relation.getTypeGroup() == null) { + relation.setTypeGroup(RelationTypeGroup.COMMON); } + + tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); } @ApiOperation(value = "Delete Relation (deleteRelation)", @@ -120,15 +111,7 @@ public class EntityRelationController extends BaseController { checkEntityId(toId, Operation.WRITE); RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup); - try { - tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), relation.getFrom(), null, getCurrentUser().getCustomerId(), - ActionType.RELATION_DELETED, getCurrentUser(), e, relation); - notificationEntityService.logEntityAction(getTenantId(), relation.getTo(), null, getCurrentUser().getCustomerId(), - ActionType.RELATION_DELETED, getCurrentUser(), e, relation); - throw handleException(e); - } + tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser()); } @ApiOperation(value = "Delete Relations (deleteRelations)", @@ -143,13 +126,7 @@ public class EntityRelationController extends BaseController { checkParameter("entityType", strType); EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId); checkEntityId(entityId, Operation.WRITE); - try { - tbEntityRelationService.deleteRelations(getTenantId(), getCurrentUser().getCustomerId(), entityId, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), entityId, null, getCurrentUser().getCustomerId(), - ActionType.RELATIONS_DELETED, getCurrentUser(), e); - throw handleException(e); - } + tbEntityRelationService.deleteRelations(getTenantId(), getCurrentUser().getCustomerId(), entityId, getCurrentUser()); } @ApiOperation(value = "Get Relation (getRelation)", diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java index ef3ced46b8..f7aeeb08b1 100644 --- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java +++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java @@ -33,10 +33,8 @@ import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.EntityViewInfo; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -142,22 +140,15 @@ public class EntityViewController extends BaseController { public EntityView saveEntityView( @ApiParam(value = "A JSON object representing the entity view.") @RequestBody EntityView entityView) throws ThingsboardException { - try { - entityView.setTenantId(getCurrentUser().getTenantId()); - EntityView existingEntityView = null; - if (entityView.getId() == null) { - accessControlService - .checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView); - } else { - existingEntityView = checkEntityViewId(entityView.getId(), Operation.WRITE); - } - return tbEntityViewService.save(entityView, existingEntityView, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), entityView, - actionType, getCurrentUser(), e); - throw handleException(e); + entityView.setTenantId(getCurrentUser().getTenantId()); + EntityView existingEntityView = null; + if (entityView.getId() == null) { + accessControlService + .checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView); + } else { + existingEntityView = checkEntityViewId(entityView.getId(), Operation.WRITE); } + return tbEntityViewService.save(entityView, existingEntityView, getCurrentUser()); } @ApiOperation(value = "Delete entity view (deleteEntityView)", @@ -170,15 +161,9 @@ public class EntityViewController extends BaseController { @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { checkParameter(ENTITY_VIEW_ID, strEntityViewId); - try { - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); - tbEntityViewService.delete(entityView, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.DELETED, getCurrentUser(), e, strEntityViewId); - throw handleException(e); - } + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); + tbEntityViewService.delete(entityView, getCurrentUser()); } @ApiOperation(value = "Get Entity View by name (getTenantEntityView)", @@ -208,22 +193,16 @@ public class EntityViewController extends BaseController { @PathVariable(CUSTOMER_ID) String strCustomerId, @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - try { - checkParameter(CUSTOMER_ID, strCustomerId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + checkParameter(CUSTOMER_ID, strCustomerId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - CustomerId customerId = new CustomerId(toUUID(strCustomerId)); - Customer customer = checkCustomerId(customerId, Operation.READ); + CustomerId customerId = new CustomerId(toUUID(strCustomerId)); + Customer customer = checkCustomerId(customerId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); - return tbEntityViewService.assignEntityViewToCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEntityViewId, strCustomerId); - throw handleException(e); - } + return tbEntityViewService.assignEntityViewToCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); } @ApiOperation(value = "Unassign Entity View from customer (unassignEntityViewFromCustomer)", @@ -234,22 +213,16 @@ public class EntityViewController extends BaseController { public EntityView unassignEntityViewFromCustomer( @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - try { - checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER); - if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { - throw new IncorrectParameterException("Entity View isn't assigned to any customer!"); - } + checkParameter(ENTITY_VIEW_ID, strEntityViewId); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER); + if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { + throw new IncorrectParameterException("Entity View isn't assigned to any customer!"); + } - Customer customer = checkCustomerId(entityView.getCustomerId(), Operation.READ); + Customer customer = checkCustomerId(entityView.getCustomerId(), Operation.READ); - return tbEntityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.UNASSIGNED_FROM_CUSTOMER, getCurrentUser(), e, strEntityViewId); - throw handleException(e); - } + return tbEntityViewService.unassignEntityViewFromCustomer(getTenantId(), entityViewId, customer, getCurrentUser()); } @ApiOperation(value = "Get Customer Entity Views (getCustomerEntityViews)", @@ -448,20 +421,14 @@ public class EntityViewController extends BaseController { public EntityView assignEntityViewToPublicCustomer( @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - try { - checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); - Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId()); + Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId()); - return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(), - publicCustomer, entityViewId, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.ASSIGNED_TO_CUSTOMER, getCurrentUser(), e, strEntityViewId); - throw handleException(e); - } + return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(), + publicCustomer, entityViewId, getCurrentUser()); } @ApiOperation(value = "Assign entity view to edge (assignEntityViewToEdge)", @@ -476,23 +443,17 @@ public class EntityViewController extends BaseController { @ResponseBody public EntityView assignEntityViewToEdge(@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - checkEntityViewId(entityViewId, Operation.READ); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + checkEntityViewId(entityViewId, Operation.READ); - return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(), - entityViewId, edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strEntityViewId, strEdgeId); - throw handleException(e); - } + return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(), + entityViewId, edge, getCurrentUser()); } @ApiOperation(value = "Unassign entity view from edge (unassignEntityViewFromEdge)", @@ -507,23 +468,17 @@ public class EntityViewController extends BaseController { @ResponseBody public EntityView unassignEntityViewFromEdge(@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { - try { - checkParameter(EDGE_ID, strEdgeId); - checkParameter(ENTITY_VIEW_ID, strEntityViewId); + checkParameter(EDGE_ID, strEdgeId); + checkParameter(ENTITY_VIEW_ID, strEntityViewId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.READ); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.READ); - EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); - EntityView entityView = checkEntityViewId(entityViewId, Operation.READ); + EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); + EntityView entityView = checkEntityViewId(entityViewId, Operation.READ); - return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView, - edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ENTITY_VIEW), - ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strEntityViewId, strEdgeId); - throw handleException(e); - } + return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView, + edge, getCurrentUser()); } @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") diff --git a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java index f311ed0cf0..0040187f02 100644 --- a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java +++ b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java @@ -32,11 +32,9 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.OtaPackage; import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.OtaPackageId; @@ -49,6 +47,8 @@ import org.thingsboard.server.service.entitiy.ota.TbOtaPackageService; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; +import java.io.IOException; + import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_PROFILE_ID_PARAM_DESCRIPTION; @@ -156,17 +156,10 @@ public class OtaPackageController extends BaseController { @ResponseBody public OtaPackageInfo saveOtaPackageInfo(@ApiParam(value = "A JSON value representing the OTA Package.") @RequestBody SaveOtaPackageInfoRequest otaPackageInfo) throws ThingsboardException { - try { - otaPackageInfo.setTenantId(getTenantId()); - checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE); + otaPackageInfo.setTenantId(getTenantId()); + checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE); - return tbOtaPackageService.save(otaPackageInfo, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = otaPackageInfo.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), otaPackageInfo, - actionType, getCurrentUser(), e); - throw handleException(e); - } + return tbOtaPackageService.save(otaPackageInfo, getCurrentUser()); } @ApiOperation(value = "Save OTA Package data (saveOtaPackageData)", @@ -183,21 +176,15 @@ public class OtaPackageController extends BaseController { @ApiParam(value = "OTA Package checksum algorithm.", allowableValues = OTA_PACKAGE_CHECKSUM_ALGORITHM_ALLOWABLE_VALUES) @RequestParam(CHECKSUM_ALGORITHM) String checksumAlgorithmStr, @ApiParam(value = "OTA Package data.") - @RequestPart MultipartFile file) throws ThingsboardException { - try { - checkParameter(OTA_PACKAGE_ID, strOtaPackageId); - checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr); - OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); - OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ); - ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase()); - byte[] data = file.getBytes(); - return tbOtaPackageService.saveOtaPackageData(otaPackageInfo, checksum, checksumAlgorithm, - data, file.getOriginalFilename(), file.getContentType(), getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), ActionType.UPDATED, - getCurrentUser(), e, strOtaPackageId); - throw handleException(e); - } + @RequestPart MultipartFile file) throws ThingsboardException, IOException { + checkParameter(OTA_PACKAGE_ID, strOtaPackageId); + checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr); + OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); + OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ); + ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase()); + byte[] data = file.getBytes(); + return tbOtaPackageService.saveOtaPackageData(otaPackageInfo, checksum, checksumAlgorithm, + data, file.getOriginalFilename(), file.getContentType(), getCurrentUser()); } @ApiOperation(value = "Get OTA Package Infos (getOtaPackages)", @@ -266,17 +253,10 @@ public class OtaPackageController extends BaseController { @ResponseBody public void deleteOtaPackage(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION) @PathVariable("otaPackageId") String strOtaPackageId) throws ThingsboardException { - try { - checkParameter(OTA_PACKAGE_ID, strOtaPackageId); - OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); - OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.DELETE); - - tbOtaPackageService.delete(otaPackageInfo, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.OTA_PACKAGE), - ActionType.DELETED, getCurrentUser(), e, strOtaPackageId); - throw handleException(e); - } + checkParameter(OTA_PACKAGE_ID, strOtaPackageId); + OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); + OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.DELETE); + tbOtaPackageService.delete(otaPackageInfo, getCurrentUser()); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/QueueController.java b/application/src/main/java/org/thingsboard/server/controller/QueueController.java index 39a971e6ed..644bee9ff0 100644 --- a/application/src/main/java/org/thingsboard/server/controller/QueueController.java +++ b/application/src/main/java/org/thingsboard/server/controller/QueueController.java @@ -55,17 +55,13 @@ public class QueueController extends BaseController { @RequestParam(required = false) String sortProperty, @RequestParam(required = false) String sortOrder) throws ThingsboardException { checkParameter("serviceType", serviceType); - try { - PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); - ServiceType type = ServiceType.valueOf(serviceType); - switch (type) { - case TB_RULE_ENGINE: - return queueService.findQueuesByTenantId(getTenantId(), pageLink); - default: - return new PageData<>(); - } - } catch (Exception e) { - throw handleException(e); + PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); + ServiceType type = ServiceType.valueOf(serviceType); + switch (type) { + case TB_RULE_ENGINE: + return queueService.findQueuesByTenantId(getTenantId(), pageLink); + default: + return new PageData<>(); } } @@ -74,14 +70,9 @@ public class QueueController extends BaseController { @ResponseBody public Queue getQueueById(@PathVariable("queueId") String queueIdStr) throws ThingsboardException { checkParameter("queueId", queueIdStr); - try { - QueueId queueId = new QueueId(UUID.fromString(queueIdStr)); - checkQueueId(queueId, Operation.READ); - return checkNotNull(queueService.findQueueById(getTenantId(), queueId)); - } catch ( - Exception e) { - throw handleException(e); - } + QueueId queueId = new QueueId(UUID.fromString(queueIdStr)); + checkQueueId(queueId, Operation.READ); + return checkNotNull(queueService.findQueueById(getTenantId(), queueId)); } @PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @@ -90,23 +81,19 @@ public class QueueController extends BaseController { public Queue saveQueue(@RequestBody Queue queue, @RequestParam String serviceType) throws ThingsboardException { checkParameter("serviceType", serviceType); - try { - queue.setTenantId(getCurrentUser().getTenantId()); + queue.setTenantId(getCurrentUser().getTenantId()); - checkEntity(queue.getId(), queue, Resource.QUEUE); + checkEntity(queue.getId(), queue, Resource.QUEUE); - ServiceType type = ServiceType.valueOf(serviceType); - switch (type) { - case TB_RULE_ENGINE: - queue.setTenantId(getTenantId()); - Queue savedQueue = tbQueueService.saveQueue(queue); - checkNotNull(savedQueue); - return savedQueue; - default: - return null; - } - } catch (Exception e) { - throw handleException(e); + ServiceType type = ServiceType.valueOf(serviceType); + switch (type) { + case TB_RULE_ENGINE: + queue.setTenantId(getTenantId()); + Queue savedQueue = tbQueueService.saveQueue(queue); + checkNotNull(savedQueue); + return savedQueue; + default: + return null; } } @@ -115,12 +102,8 @@ public class QueueController extends BaseController { @ResponseBody public void deleteQueue(@PathVariable("queueId") String queueIdStr) throws ThingsboardException { checkParameter("queueId", queueIdStr); - try { - QueueId queueId = new QueueId(toUUID(queueIdStr)); - checkQueueId(queueId, Operation.DELETE); - tbQueueService.deleteQueue(getTenantId(), queueId); - } catch (Exception e) { - throw handleException(e); - } + QueueId queueId = new QueueId(toUUID(queueIdStr)); + checkQueueId(queueId, Operation.DELETE); + tbQueueService.deleteQueue(getTenantId(), queueId); } } diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java index 429a573829..2db9386373 100644 --- a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java +++ b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java @@ -40,10 +40,8 @@ import org.thingsboard.rule.engine.api.ScriptEngine; import org.thingsboard.server.actors.ActorSystemContext; import org.thingsboard.server.actors.tenant.DebugTbRateLimits; import org.thingsboard.server.common.data.DataConstants; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Event; import org.thingsboard.server.common.data.StringUtils; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.EdgeId; @@ -72,6 +70,7 @@ import org.thingsboard.server.service.script.RuleNodeJsScriptEngine; import org.thingsboard.server.service.security.permission.Operation; import org.thingsboard.server.service.security.permission.Resource; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -235,16 +234,9 @@ public class RuleChainController extends BaseController { public RuleChain saveRuleChain( @ApiParam(value = "A JSON value representing the rule chain.") @RequestBody RuleChain ruleChain) throws ThingsboardException { - try { - ruleChain.setTenantId(getCurrentUser().getTenantId()); - checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN); - return tbRuleChainService.save(ruleChain, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ruleChain, - actionType, getCurrentUser(), e); - throw handleException(e); - } + ruleChain.setTenantId(getCurrentUser().getTenantId()); + checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN); + return tbRuleChainService.save(ruleChain, getCurrentUser()); } @ApiOperation(value = "Create Default Rule Chain", @@ -255,18 +247,10 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain saveRuleChain( @ApiParam(value = "A JSON value representing the request.") - @RequestBody DefaultRuleChainCreateRequest request) throws ThingsboardException { - try { - checkNotNull(request); - checkParameter(request.getName(), "name"); - return tbRuleChainService.saveDefaultByName(getTenantId(), request, getCurrentUser()); - } catch (Exception e) { - RuleChain ruleChain = new RuleChain(); - ruleChain.setName(request.getName()); - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ruleChain, - ActionType.ADDED, getCurrentUser(), e); - throw handleException(e); - } + @RequestBody DefaultRuleChainCreateRequest request) throws ThingsboardException, IOException { + checkNotNull(request); + checkParameter(request.getName(), "name"); + return tbRuleChainService.saveDefaultByName(getTenantId(), request, getCurrentUser()); } @ApiOperation(value = "Set Root Rule Chain (setRootRuleChain)", @@ -277,16 +261,10 @@ public class RuleChainController extends BaseController { public RuleChain setRootRuleChain( @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, - getCurrentUser(), e, strRuleChainId); - throw handleException(e); - } + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); } @ApiOperation(value = "Update Rule Chain Metadata", @@ -300,23 +278,17 @@ public class RuleChainController extends BaseController { @ApiParam(value = "Update related rule nodes.") @RequestParam(value = "updateRelated", required = false, defaultValue = "true") boolean updateRelated ) throws ThingsboardException { - try { - TenantId tenantId = getTenantId(); - if (debugPerTenantEnabled) { - ConcurrentMap debugPerTenantLimits = actorContext.getDebugPerTenantLimits(); - DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null); - if (debugTbRateLimits != null) { - debugPerTenantLimits.remove(tenantId, debugTbRateLimits); - } + TenantId tenantId = getTenantId(); + if (debugPerTenantEnabled) { + ConcurrentMap debugPerTenantLimits = actorContext.getDebugPerTenantLimits(); + DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null); + if (debugTbRateLimits != null) { + debugPerTenantLimits.remove(tenantId, debugTbRateLimits); } - RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId(), Operation.WRITE); - - return tbRuleChainService.saveRuleChainMetaData(tenantId, ruleChain, ruleChainMetaData, updateRelated, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.ADDED, - getCurrentUser(), e, ruleChainMetaData); - throw handleException(e); } + RuleChain ruleChain = checkRuleChain(ruleChainMetaData.getRuleChainId(), Operation.WRITE); + + return tbRuleChainService.saveRuleChainMetaData(tenantId, ruleChain, ruleChainMetaData, updateRelated, getCurrentUser()); } @ApiOperation(value = "Get Rule Chains (getRuleChains)", @@ -359,16 +331,10 @@ public class RuleChainController extends BaseController { public void deleteRuleChain( @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE); - tbRuleChainService.delete(ruleChain, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.DELETED, - getCurrentUser(), e, strRuleChainId); - throw handleException(e); - } + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE); + tbRuleChainService.delete(ruleChain, getCurrentUser()); } @ApiOperation(value = "Get latest input message (getLatestRuleNodeDebugInput)", @@ -553,21 +519,15 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain assignRuleChainToEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter("edgeId", strEdgeId); - checkParameter(RULE_CHAIN_ID, strRuleChainId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); + checkParameter("edgeId", strEdgeId); + checkParameter(RULE_CHAIN_ID, strRuleChainId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); - return tbRuleChainService.assignRuleChainToEdge(getTenantId(), ruleChain, edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), - ActionType.ASSIGNED_TO_EDGE, getCurrentUser(), e, strRuleChainId, strEdgeId); - throw handleException(e); - } + return tbRuleChainService.assignRuleChainToEdge(getTenantId(), ruleChain, edge, getCurrentUser()); } @ApiOperation(value = "Unassign rule chain from edge (unassignRuleChainFromEdge)", @@ -582,20 +542,14 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain unassignRuleChainFromEdge(@PathVariable("edgeId") String strEdgeId, @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter("edgeId", strEdgeId); - checkParameter(RULE_CHAIN_ID, strRuleChainId); - EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); - Edge edge = checkEdgeId(edgeId, Operation.WRITE); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); + checkParameter("edgeId", strEdgeId); + checkParameter(RULE_CHAIN_ID, strRuleChainId); + EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); + Edge edge = checkEdgeId(edgeId, Operation.WRITE); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); - return tbRuleChainService.unassignRuleChainFromEdge(getTenantId(), ruleChain, edge, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), - ActionType.UNASSIGNED_FROM_EDGE, getCurrentUser(), e, strRuleChainId, strEdgeId); - throw handleException(e); - } + return tbRuleChainService.unassignRuleChainFromEdge(getTenantId(), ruleChain, edge, getCurrentUser()); } @ApiOperation(value = "Get Edge Rule Chains (getEdgeRuleChains)", @@ -636,16 +590,10 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain setEdgeTemplateRootRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setEdgeTemplateRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, - getCurrentUser(), e, strRuleChainId); - throw handleException(e); - } + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setEdgeTemplateRootRuleChain(getTenantId(), ruleChain, getCurrentUser()); } @ApiOperation(value = "Set Auto Assign To Edge Rule Chain (setAutoAssignToEdgeRuleChain)", @@ -656,16 +604,10 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain setAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - return tbRuleChainService.setAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, - getCurrentUser(), e, strRuleChainId); - throw handleException(e); - } + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.setAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); } @ApiOperation(value = "Unset Auto Assign To Edge Rule Chain (unsetAutoAssignToEdgeRuleChain)", @@ -676,17 +618,10 @@ public class RuleChainController extends BaseController { @ResponseBody public RuleChain unsetAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { - try { - checkParameter(RULE_CHAIN_ID, strRuleChainId); - RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); - RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); - - return tbRuleChainService.unsetAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, - getCurrentUser(), e, strRuleChainId); - throw handleException(e); - } + checkParameter(RULE_CHAIN_ID, strRuleChainId); + RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); + RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); + return tbRuleChainService.unsetAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser()); } // TODO: @voba refactor this - add new config to edge rule chain to set it as auto-assign diff --git a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java index 08d407b736..bc0fa376b1 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TbResourceController.java @@ -31,10 +31,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; @@ -149,16 +147,9 @@ public class TbResourceController extends BaseController { @ResponseBody public TbResource saveResource(@ApiParam(value = "A JSON value representing the Resource.") @RequestBody TbResource resource) throws ThingsboardException { - try { - resource.setTenantId(getTenantId()); - checkEntity(resource.getId(), resource, Resource.TB_RESOURCE); - return tbResourceService.save(resource, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = resource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.TB_RESOURCE), - resource, actionType, getCurrentUser(), e); - throw handleException(e); - } + resource.setTenantId(getTenantId()); + checkEntity(resource.getId(), resource, Resource.TB_RESOURCE); + return tbResourceService.save(resource, getCurrentUser()); } @ApiOperation(value = "Get Resource Infos (getResources)", @@ -242,15 +233,9 @@ public class TbResourceController extends BaseController { @ResponseBody public void deleteResource(@ApiParam(value = RESOURCE_ID_PARAM_DESCRIPTION) @PathVariable("resourceId") String strResourceId) throws ThingsboardException { - try { - checkParameter(RESOURCE_ID, strResourceId); - TbResourceId resourceId = new TbResourceId(toUUID(strResourceId)); - TbResource tbResource = checkResourceId(resourceId, Operation.DELETE); - tbResourceService.delete(tbResource, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.TB_RESOURCE), - ActionType.DELETED, getCurrentUser(), e, strResourceId); - throw handleException(e); - } + checkParameter(RESOURCE_ID, strResourceId); + TbResourceId resourceId = new TbResourceId(toUUID(strResourceId)); + TbResource tbResource = checkResourceId(resourceId, Operation.DELETE); + tbResourceService.delete(tbResource, getCurrentUser()); } } \ No newline at end of file diff --git a/application/src/main/java/org/thingsboard/server/controller/TenantController.java b/application/src/main/java/org/thingsboard/server/controller/TenantController.java index fdfdd88f76..320fdc73bc 100644 --- a/application/src/main/java/org/thingsboard/server/controller/TenantController.java +++ b/application/src/main/java/org/thingsboard/server/controller/TenantController.java @@ -120,13 +120,9 @@ public class TenantController extends BaseController { @RequestMapping(value = "/tenant", method = RequestMethod.POST) @ResponseBody public Tenant saveTenant(@ApiParam(value = "A JSON value representing the tenant.") - @RequestBody Tenant tenant) throws ThingsboardException { + @RequestBody Tenant tenant) throws Exception { checkEntity(tenant.getId(), tenant, Resource.TENANT); - try { - return tbTenantService.save(tenant); - } catch (Exception e) { - throw handleException(e); - } + return tbTenantService.save(tenant); } @ApiOperation(value = "Delete Tenant (deleteTenant)", @@ -139,11 +135,7 @@ public class TenantController extends BaseController { checkParameter(TENANT_ID, strTenantId); TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId)); Tenant tenant = checkTenantId(tenantId, Operation.DELETE); - try { - tbTenantService.delete(tenant); - } catch (Exception e) { - throw handleException(e); - } + tbTenantService.delete(tenant); } @ApiOperation(value = "Get Tenants (getTenants)", notes = "Returns a page of tenants registered in the platform. " + PAGE_DATA_PARAMETERS + SYSTEM_AUTHORITY_PARAGRAPH) diff --git a/application/src/main/java/org/thingsboard/server/controller/UserController.java b/application/src/main/java/org/thingsboard/server/controller/UserController.java index 96067279a6..e9375665bb 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UserController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UserController.java @@ -33,9 +33,7 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.rule.engine.api.MailService; -import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -187,17 +185,11 @@ public class UserController extends BaseController { @RequestBody User user, @ApiParam(value = "Send activation email (or use activation link)", defaultValue = "true") @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException { - try { - if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) { - user.setTenantId(getCurrentUser().getTenantId()); - } - checkEntity(user.getId(), user, Resource.USER); - return tbUserService.save(getTenantId(), getCurrentUser().getCustomerId(), user, sendActivationMail, request, getCurrentUser()); - } catch (Exception e) { - ActionType actionType = user.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.USER), user, actionType, getCurrentUser(), e); - throw handleException(e); + if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) { + user.setTenantId(getCurrentUser().getTenantId()); } + checkEntity(user.getId(), user, Resource.USER); + return tbUserService.save(getTenantId(), getCurrentUser().getCustomerId(), user, sendActivationMail, request, getCurrentUser()); } @ApiOperation(value = "Send or re-send the activation email", @@ -267,19 +259,13 @@ public class UserController extends BaseController { public void deleteUser( @ApiParam(value = USER_ID_PARAM_DESCRIPTION) @PathVariable(USER_ID) String strUserId) throws ThingsboardException { - try { - checkParameter(USER_ID, strUserId); - UserId userId = new UserId(toUUID(strUserId)); - User user = checkUserId(userId, Operation.DELETE); - if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) { - throw new ThingsboardException("Sysadmin is not allowed to delete himself", ThingsboardErrorCode.PERMISSION_DENIED); - } - tbUserService.delete(getTenantId(), getCurrentUser().getCustomerId(), user, getCurrentUser()); - } catch (Exception e) { - notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.USER), - ActionType.DELETED, getCurrentUser(), e, strUserId); - throw handleException(e); + checkParameter(USER_ID, strUserId); + UserId userId = new UserId(toUUID(strUserId)); + User user = checkUserId(userId, Operation.DELETE); + if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) { + throw new ThingsboardException("Sysadmin is not allowed to delete himself", ThingsboardErrorCode.PERMISSION_DENIED); } + tbUserService.delete(getTenantId(), getCurrentUser().getCustomerId(), user, getCurrentUser()); } @ApiOperation(value = "Get Users (getUsers)", diff --git a/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java b/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java index 600c615d84..68a9b489f7 100644 --- a/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java +++ b/application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java @@ -97,19 +97,15 @@ public class WidgetsBundleController extends BaseController { public WidgetsBundle saveWidgetsBundle( @ApiParam(value = "A JSON value representing the Widget Bundle.", required = true) @RequestBody WidgetsBundle widgetsBundle) throws ThingsboardException { - try { - if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { - widgetsBundle.setTenantId(TenantId.SYS_TENANT_ID); - } else { - widgetsBundle.setTenantId(getCurrentUser().getTenantId()); - } + if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { + widgetsBundle.setTenantId(TenantId.SYS_TENANT_ID); + } else { + widgetsBundle.setTenantId(getCurrentUser().getTenantId()); + } - checkEntity(widgetsBundle.getId(), widgetsBundle, Resource.WIDGETS_BUNDLE); + checkEntity(widgetsBundle.getId(), widgetsBundle, Resource.WIDGETS_BUNDLE); - return tbWidgetsBundleService.save(widgetsBundle); - } catch (Exception e) { - throw handleException(e); - } + return tbWidgetsBundleService.save(widgetsBundle); } @ApiOperation(value = "Delete widgets bundle (deleteWidgetsBundle)", @@ -120,14 +116,10 @@ public class WidgetsBundleController extends BaseController { public void deleteWidgetsBundle( @ApiParam(value = WIDGET_BUNDLE_ID_PARAM_DESCRIPTION, required = true) @PathVariable("widgetsBundleId") String strWidgetsBundleId) throws ThingsboardException { - try { - checkParameter("widgetsBundleId", strWidgetsBundleId); - WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); - WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE); - tbWidgetsBundleService.delete(widgetsBundle); - } catch (Exception e) { - throw handleException(e); - } + checkParameter("widgetsBundleId", strWidgetsBundleId); + WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); + WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE); + tbWidgetsBundleService.delete(widgetsBundle); } @ApiOperation(value = "Get Widget Bundles (getWidgetsBundles)", diff --git a/application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java b/application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java index 34c30d5225..25a3a2d156 100644 --- a/application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java +++ b/application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java @@ -121,7 +121,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService { } entity.setDeviceProfileId(deviceProfile.getId()); - return tbDeviceService.saveDeviceWithCredentials(user.getTenantId(), entity, deviceCredentials, user); + return tbDeviceService.saveDeviceWithCredentials(entity, deviceCredentials, user); } @Override @@ -176,7 +176,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService { ObjectNode lwm2mCredentials = JacksonUtil.newObjectNode(); Set.of(BulkImportColumnType.LWM2M_CLIENT_SECURITY_CONFIG_MODE, BulkImportColumnType.LWM2M_BOOTSTRAP_SERVER_SECURITY_MODE, - BulkImportColumnType.LWM2M_SERVER_SECURITY_MODE).stream() + BulkImportColumnType.LWM2M_SERVER_SECURITY_MODE).stream() .map(fields::get) .filter(Objects::nonNull) .forEach(securityMode -> { @@ -233,7 +233,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService { Lwm2mDeviceProfileTransportConfiguration transportConfiguration = new Lwm2mDeviceProfileTransportConfiguration(); transportConfiguration.setBootstrap(Collections.emptyList()); - transportConfiguration.setClientLwM2mSettings(new OtherConfiguration(1,1,1, PowerMode.DRX, null, null, null, null, null)); + transportConfiguration.setClientLwM2mSettings(new OtherConfiguration(1, 1, 1, PowerMode.DRX, null, null, null, null, null)); transportConfiguration.setObserveAttr(new TelemetryMappingConfiguration(Collections.emptyMap(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptyMap())); DeviceProfileData deviceProfileData = new DeviceProfileData(); diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java index e4bb74c129..55f55d54eb 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java @@ -30,6 +30,7 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AlarmId; import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.EntityIdFactory; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageDataIterableByTenantIdEntityId; @@ -37,6 +38,7 @@ import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.dao.alarm.AlarmService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.service.executors.DbCallbackExecutorService; import java.util.ArrayList; @@ -121,4 +123,8 @@ public abstract class AbstractTbEntityService { } return result; } + + protected I emptyId(EntityType entityType) { + return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); + } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java index 75589a62e5..4f2b7fd5bc 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java @@ -21,6 +21,7 @@ import com.google.common.util.concurrent.MoreExecutors; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmStatus; @@ -40,9 +41,15 @@ public class DefaultTbAlarmService extends AbstractTbEntityService implements Tb @Override public Alarm save(Alarm alarm, User user) throws ThingsboardException { ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); - notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); - return savedAlarm; + TenantId tenantId = alarm.getTenantId(); + try { + Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); + notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); + return savedAlarm; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ALARM), alarm, actionType, user, e); + throw e; + } } @Override diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java index acee2912a8..8b56ed0bc2 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java @@ -19,6 +19,7 @@ import com.google.common.util.concurrent.ListenableFuture; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.audit.ActionType; @@ -43,67 +44,99 @@ public class DefaultTbAssetService extends AbstractTbEntityService implements Tb public Asset save(Asset asset, User user) throws ThingsboardException { ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = asset.getTenantId(); - Asset savedAsset = checkNotNull(assetService.saveAsset(asset)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), savedAsset, asset.getCustomerId(), actionType, user); - - return savedAsset; + try { + Asset savedAsset = checkNotNull(assetService.saveAsset(asset)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), savedAsset, + asset.getCustomerId(), actionType, user); + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), asset, actionType, user, e); + throw e; + } } @Override public ListenableFuture delete(Asset asset, User user) { TenantId tenantId = asset.getTenantId(); AssetId assetId = asset.getId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId); - assetService.deleteAsset(tenantId, assetId); - notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(), ActionType.DELETED, - relatedEdgeIds, user, assetId.toString()); - - return removeAlarmsByEntityId(tenantId, assetId); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId); + assetService.deleteAsset(tenantId, assetId); + notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(), + ActionType.DELETED, relatedEdgeIds, user, assetId.toString()); + + return removeAlarmsByEntityId(tenantId, assetId); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), ActionType.DELETED, user, e, + assetId.toString()); + throw e; + } } @Override public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; CustomerId customerId = customer.getId(); - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, user, true, customerId.toString(), customer.getName()); - - return savedAsset; + try { + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, + actionType, user, true, customerId.toString(), customer.getName()); + + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, + assetId.toString(), customerId.toString()); + throw e; + } } @Override public Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; - Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId)); - CustomerId customerId = customer.getId(); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, user, true, customerId.toString(), customer.getName()); - - return savedAsset; + try { + Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId)); + CustomerId customerId = customer.getId(); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, + actionType, user, true, customerId.toString(), customer.getName()); + + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, assetId.toString()); + throw e; + } } @Override public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset, - actionType, user, false, actionType.toString(), publicCustomer.getId().toString(), publicCustomer.getName()); - - return savedAsset; - + try { + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset, + actionType, user, false, actionType.toString(), publicCustomer.getId().toString(), publicCustomer.getName()); + + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, assetId.toString()); + throw e; + } } @Override public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; EdgeId edgeId = edge.getId(); - Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(), - edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); - - return savedAsset; + try { + Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(), + edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); + + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, + user, e, assetId.toString(), edgeId.toString()); + throw e; + } } @Override @@ -111,10 +144,17 @@ public class DefaultTbAssetService extends AbstractTbEntityService implements Tb ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; AssetId assetId = asset.getId(); EdgeId edgeId = edge.getId(); - Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId)); - - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, asset.getCustomerId(), - edgeId, asset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); - return savedAsset; + try { + Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId)); + + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, asset.getCustomerId(), + edgeId, asset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); + + return savedAsset; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, + user, e, assetId.toString(), edgeId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java index 6d4c02fb18..2e7ab54a23 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java @@ -18,6 +18,7 @@ package org.thingsboard.server.service.entitiy.customer; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -38,19 +39,31 @@ public class DefaultTbCustomerService extends AbstractTbEntityService implements ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = customer.getTenantId(); CustomerId customerId = customer.getId(); - Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedCustomer.getId(), savedCustomer, customerId, actionType, user); - return savedCustomer; + try { + Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedCustomer.getId(), savedCustomer, customerId, actionType, user); + + return savedCustomer; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), customer, actionType, user, e); + throw e; + } } @Override public void delete(Customer customer, User user) { TenantId tenantId = customer.getTenantId(); CustomerId customerId = customer.getId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId()); - customerService.deleteCustomer(tenantId, customerId); - notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId, - ActionType.DELETED, relatedEdgeIds, user, customerId.toString()); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId()); + customerService.deleteCustomer(tenantId, customerId); + notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId, + ActionType.DELETED, relatedEdgeIds, user, customerId.toString()); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.CUSTOMER), ActionType.DELETED, + user, e, customerId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java index c409411b75..f815be7f36 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java @@ -19,6 +19,7 @@ import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ShortCustomerInfo; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; @@ -47,20 +48,30 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement public Dashboard save(Dashboard dashboard, User user) throws ThingsboardException { ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = dashboard.getTenantId(); - Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, - null, actionType, user); - return savedDashboard; + try { + Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, + null, actionType, user); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), dashboard, actionType, user, e); + throw e; + } } @Override public void delete(Dashboard dashboard, User user) { DashboardId dashboardId = dashboard.getId(); TenantId tenantId = dashboard.getTenantId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); - dashboardService.deleteDashboard(tenantId, dashboardId); - notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, - ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); + dashboardService.deleteDashboard(tenantId, dashboardId); + notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, + ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), ActionType.DELETED, user, e, dashboardId.toString()); + throw e; + } } @Override @@ -69,10 +80,16 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement TenantId tenantId = dashboard.getTenantId(); CustomerId customerId = customer.getId(); DashboardId dashboardId = dashboard.getId(); - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, - actionType, user, true, customerId.toString(), customer.getName()); - return savedDashboard; + try { + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, + actionType, user, true, customerId.toString(), customer.getName()); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, + user, e, dashboardId.toString(), customerId.toString()); + throw e; + } } @Override @@ -80,12 +97,17 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); DashboardId dashboardId = dashboard.getId(); - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), savedDashboard, - actionType, user, false, dashboardId.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDashboard; + try { + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), savedDashboard, + actionType, user, false, dashboardId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; + } } @Override @@ -93,12 +115,17 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); DashboardId dashboardId = dashboard.getId(); - Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), dashboard, - actionType, user, false, dashboardId.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDashboard; + try { + Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), dashboard, + actionType, user, false, dashboardId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; + } } @Override @@ -106,40 +133,45 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); DashboardId dashboardId = dashboard.getId(); - Set addedCustomerIds = new HashSet<>(); - Set removedCustomerIds = new HashSet<>(); - for (CustomerId customerId : customerIds) { - if (!dashboard.isAssignedToCustomer(customerId)) { - addedCustomerIds.add(customerId); + try { + Set addedCustomerIds = new HashSet<>(); + Set removedCustomerIds = new HashSet<>(); + for (CustomerId customerId : customerIds) { + if (!dashboard.isAssignedToCustomer(customerId)) { + addedCustomerIds.add(customerId); + } } - } - Set assignedCustomers = dashboard.getAssignedCustomers(); - if (assignedCustomers != null) { - for (ShortCustomerInfo customerInfo : assignedCustomers) { - if (!customerIds.contains(customerInfo.getCustomerId())) { - removedCustomerIds.add(customerInfo.getCustomerId()); + Set assignedCustomers = dashboard.getAssignedCustomers(); + if (assignedCustomers != null) { + for (ShortCustomerInfo customerInfo : assignedCustomers) { + if (!customerIds.contains(customerInfo.getCustomerId())) { + removedCustomerIds.add(customerInfo.getCustomerId()); + } } } - } - if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : addedCustomerIds) { - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); - ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, user, true, customerInfo.getTitle()); - } - for (CustomerId customerId : removedCustomerIds) { - ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); + if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : addedCustomerIds) { + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); + ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); + } + for (CustomerId customerId : removedCustomerIds) { + ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, + ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); + } + return savedDashboard; } - return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; } } @@ -147,17 +179,23 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement public Dashboard addDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); - if (customerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : customerIds) { - savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); - ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, user, true, customerInfo.getTitle()); + DashboardId dashboardId = dashboard.getId(); + try { + if (customerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : customerIds) { + savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); + ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); + } + return savedDashboard; } - return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; } } @@ -165,17 +203,23 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement public Dashboard removeDashboardCustomers(Dashboard dashboard, Set customerIds, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); - if (customerIds.isEmpty()) { - return dashboard; - } else { - Dashboard savedDashboard = null; - for (CustomerId customerId : customerIds) { - ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); - savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, user, true, customerInfo.getTitle()); + DashboardId dashboardId = dashboard.getId(); + try { + if (customerIds.isEmpty()) { + return dashboard; + } else { + Dashboard savedDashboard = null; + for (CustomerId customerId : customerIds) { + ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); + savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, + actionType, user, true, customerInfo.getTitle()); + } + return savedDashboard; } - return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; } } @@ -183,11 +227,17 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement public Dashboard asignDashboardToEdge(TenantId tenantId, DashboardId dashboardId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; EdgeId edgeId = edge.getId(); - Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, - edgeId, savedDashboard, actionType, user, dashboardId.toString(), - edgeId.toString(), edge.getName()); - return savedDashboard; + try { + Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, + edgeId, savedDashboard, actionType, user, dashboardId.toString(), + edgeId.toString(), edge.getName()); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + actionType, user, e, dashboardId.toString(), edgeId); + throw e; + } } @Override @@ -196,22 +246,34 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement TenantId tenantId = dashboard.getTenantId(); DashboardId dashboardId = dashboard.getId(); EdgeId edgeId = edge.getId(); - Dashboard savedDevice = checkNotNull(dashboardService.unassignDashboardFromEdge(tenantId, dashboardId, edgeId)); + try { + Dashboard savedDevice = checkNotNull(dashboardService.unassignDashboardFromEdge(tenantId, dashboardId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, - edgeId, dashboard, actionType, user, dashboardId.toString(), - edgeId.toString(), edge.getName()); - return savedDevice; + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, + edgeId, dashboard, actionType, user, dashboardId.toString(), + edgeId.toString(), edge.getName()); + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, + dashboardId.toString(), edgeId.toString()); + throw e; + } } @Override public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = dashboard.getTenantId(); - Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, - actionType, user, true, customer.getId().toString(), customer.getName()); - return savedDashboard; + DashboardId dashboardId = dashboard.getId(); + try { + Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customer.getId(), savedDashboard, + actionType, user, true, customer.getId().toString(), customer.getName()); + return savedDashboard; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java index a8b3b4c984..43c22b53a3 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java @@ -23,6 +23,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; @@ -57,46 +58,71 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T private final TenantService tenantService; @Override - public Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException { + public Device save(Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException { ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - Device savedDevice = checkNotNull(deviceService.saveDeviceWithAccessToken(device, accessToken)); - notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), - savedDevice, oldDevice, actionType, user); + TenantId tenantId = device.getTenantId(); + try { + Device savedDevice = checkNotNull(deviceService.saveDeviceWithAccessToken(device, accessToken)); + notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), + savedDevice, oldDevice, actionType, user); - return savedDevice; + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), device, actionType, user, e); + throw e; + } } @Override - public Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials credentials, User user) throws ThingsboardException { + public Device saveDeviceWithCredentials(Device device, DeviceCredentials credentials, User user) throws ThingsboardException { ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - Device savedDevice = checkNotNull(deviceService.saveDeviceWithCredentials(device, credentials)); - notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), - savedDevice, device, actionType, user); + TenantId tenantId = device.getTenantId(); + try { + Device savedDevice = checkNotNull(deviceService.saveDeviceWithCredentials(device, credentials)); + notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), + savedDevice, device, actionType, user); - return savedDevice; + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), device, + actionType, user, e); + throw e; + } } @Override public ListenableFuture delete(Device device, User user) { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId); - deviceService.deleteDevice(tenantId, deviceId); - notificationEntityService.notifyDeleteDevice(tenantId, deviceId, device.getCustomerId(), device, - relatedEdgeIds, user, deviceId.toString()); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId); + deviceService.deleteDevice(tenantId, deviceId); + notificationEntityService.notifyDeleteDevice(tenantId, deviceId, device.getCustomerId(), device, + relatedEdgeIds, user, deviceId.toString()); - return removeAlarmsByEntityId(tenantId, deviceId); + return removeAlarmsByEntityId(tenantId, deviceId); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), ActionType.DELETED, + user, e, deviceId.toString()); + throw e; + } } @Override public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; CustomerId customerId = customer.getId(); - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, user, true, customerId.toString(), customer.getName()); + try { + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, + actionType, user, true, customerId.toString(), customer.getName()); - return savedDevice; + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), actionType, user, + e, deviceId.toString(), customerId.toString()); + throw e; + } } @Override @@ -104,46 +130,70 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId)); - CustomerId customerId = customer.getId(); + try { + Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId)); + CustomerId customerId = customer.getId(); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, user, - true, customerId.toString(), customer.getName()); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, + actionType, user, + true, customerId.toString(), customer.getName()); - return savedDevice; + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), actionType, + user, e, deviceId.toString()); + throw e; + } } @Override public Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); - Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, publicCustomer.getId())); + try { + Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, savedDevice.getCustomerId(), savedDevice, - actionType, user, false, deviceId.toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, savedDevice.getCustomerId(), savedDevice, + actionType, user, false, deviceId.toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); - return savedDevice; + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), actionType, + user, e, deviceId.toString()); + throw e; + } } @Override public DeviceCredentials getDeviceCredentialsByDeviceId(Device device, User user) throws ThingsboardException { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId)); - notificationEntityService.logEntityAction(tenantId, deviceId, device, device.getCustomerId(), - ActionType.CREDENTIALS_READ, user, deviceId.toString()); - return deviceCredentials; + try { + DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId)); + notificationEntityService.logEntityAction(tenantId, deviceId, device, device.getCustomerId(), + ActionType.CREDENTIALS_READ, user, deviceId.toString()); + return deviceCredentials; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + ActionType.CREDENTIALS_READ, user, e, deviceId.toString()); + throw e; + } } @Override public DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException { TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); - DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials)); - notificationEntityService.notifyUpdateDeviceCredentials(tenantId, deviceId, device.getCustomerId(), device, result, user); - return result; + try { + DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials)); + notificationEntityService.notifyUpdateDeviceCredentials(tenantId, deviceId, device.getCustomerId(), device, result, user); + return result; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + ActionType.CREDENTIALS_UPDATED, user, e, deviceCredentials); + throw e; + } } @Override @@ -179,23 +229,36 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T public Device assignDeviceToTenant(Device device, Tenant newTenant, User user) { TenantId tenantId = device.getTenantId(); TenantId newTenantId = newTenant.getId(); - Tenant tenant = tenantService.findTenantById(tenantId); - Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device); + DeviceId deviceId = device.getId(); + try { + Tenant tenant = tenantService.findTenantById(tenantId); + Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device); - notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, device.getId(), - assignedDevice.getCustomerId(), assignedDevice, tenant, user, newTenantId.toString(), newTenant.getName()); + notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, deviceId, + assignedDevice.getCustomerId(), assignedDevice, tenant, user, newTenantId.toString(), newTenant.getName()); - return assignedDevice; + return assignedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + ActionType.ASSIGNED_TO_TENANT, user, e, deviceId.toString()); + throw e; + } } @Override public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException { ActionType actionType = ActionType.ASSIGNED_TO_EDGE; EdgeId edgeId = edge.getId(); - Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(), - edgeId, savedDevice, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); - return savedDevice; + try { + Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(), + edgeId, savedDevice, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + ActionType.ASSIGNED_TO_EDGE, user, e, deviceId.toString(), edgeId.toString()); + throw e; + } } @Override @@ -203,11 +266,17 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T TenantId tenantId = device.getTenantId(); DeviceId deviceId = device.getId(); EdgeId edgeId = edge.getId(); - Device savedDevice = checkNotNull(deviceService.unassignDeviceFromEdge(tenantId, deviceId, edgeId)); + try { + Device savedDevice = checkNotNull(deviceService.unassignDeviceFromEdge(tenantId, deviceId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, device.getCustomerId(), - edgeId, device, ActionType.UNASSIGNED_FROM_EDGE, user, deviceId.toString(), edgeId.toString(), edge.getName()); - return savedDevice; + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, device.getCustomerId(), + edgeId, device, ActionType.UNASSIGNED_FROM_EDGE, user, deviceId.toString(), edgeId.toString(), edge.getName()); + return savedDevice; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE), + ActionType.UNASSIGNED_FROM_EDGE, user, e, deviceId.toString(), edgeId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java index 2af592d867..fd51caacf5 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java @@ -31,9 +31,9 @@ import org.thingsboard.server.dao.device.claim.ReclaimResult; public interface TbDeviceService { - Device save(TenantId tenantId, Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException; + Device save(Device device, Device oldDevice, String accessToken, User user) throws ThingsboardException; - Device saveDeviceWithCredentials(TenantId tenantId, Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException; + Device saveDeviceWithCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException; ListenableFuture delete(Device device, User user); diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java index a93e16e7b7..0d6b870e21 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java @@ -19,6 +19,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -45,56 +46,74 @@ public class DefaultTbDeviceProfileService extends AbstractTbEntityService imple public DeviceProfile save(DeviceProfile deviceProfile, User user) throws ThingsboardException { ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = deviceProfile.getTenantId(); - boolean isFirmwareChanged = false; - boolean isSoftwareChanged = false; + try { + boolean isFirmwareChanged = false; + boolean isSoftwareChanged = false; - if (actionType.equals(ActionType.UPDATED)) { - DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); - if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { - isFirmwareChanged = true; + if (actionType.equals(ActionType.UPDATED)) { + DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); + if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { + isFirmwareChanged = true; + } + if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { + isSoftwareChanged = true; + } } - if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { - isSoftwareChanged = true; - } - } - DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile)); + DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile)); - tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), - actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), + actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); - otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); + otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), - savedDeviceProfile, user, actionType, true, null); - return savedDeviceProfile; + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), + savedDeviceProfile, user, actionType, true, null); + return savedDeviceProfile; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), deviceProfile, actionType, user, e); + throw e; + } } @Override public void delete(DeviceProfile deviceProfile, User user) { DeviceProfileId deviceProfileId = deviceProfile.getId(); TenantId tenantId = deviceProfile.getTenantId(); - deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); + try { + deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); - tbClusterService.onDeviceProfileDelete(deviceProfile, null); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, - user, ActionType.DELETED, true, null, deviceProfileId.toString()); + tbClusterService.onDeviceProfileDelete(deviceProfile, null); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, + user, ActionType.DELETED, true, null, deviceProfileId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), ActionType.DELETED, + user, e, deviceProfileId.toString()); + throw e; + } } @Override public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException { TenantId tenantId = deviceProfile.getTenantId(); - if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfile.getId())) { - if (previousDefaultDeviceProfile != null) { - previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); - notificationEntityService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, - ActionType.UPDATED, user); - } - deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); + DeviceProfileId deviceProfileId = deviceProfile.getId(); + try { + if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfileId)) { + if (previousDefaultDeviceProfile != null) { + previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); + notificationEntityService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, + ActionType.UPDATED, user); + } + deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfileId); - notificationEntityService.logEntityAction(tenantId, deviceProfile.getId(), deviceProfile, ActionType.UPDATED, user); + notificationEntityService.logEntityAction(tenantId, deviceProfileId, deviceProfile, ActionType.UPDATED, user); + } + return deviceProfile; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), ActionType.UPDATED, + user, e, deviceProfileId.toString()); + throw e; } - return deviceProfile; } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java index cfd4693d4c..b06466b01f 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java @@ -19,6 +19,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; @@ -46,36 +47,53 @@ public class DefaultTbEdgeService extends AbstractTbEntityService implements TbE public Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, User user) throws Exception { ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = edge.getTenantId(); - Edge savedEdge = checkNotNull(edgeService.saveEdge(edge)); - EdgeId edgeId = savedEdge.getId(); - - if (actionType == ActionType.ADDED) { - ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId); - edgeNotificationService.setEdgeRootRuleChain(tenantId, savedEdge, edgeTemplateRootRuleChain.getId()); - edgeService.assignDefaultRuleChainsToEdge(tenantId, edgeId); + try { + Edge savedEdge = checkNotNull(edgeService.saveEdge(edge)); + EdgeId edgeId = savedEdge.getId(); + + if (actionType == ActionType.ADDED) { + ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId); + edgeNotificationService.setEdgeRootRuleChain(tenantId, savedEdge, edgeTemplateRootRuleChain.getId()); + edgeService.assignDefaultRuleChainsToEdge(tenantId, edgeId); + } + + notificationEntityService.notifyEdge(tenantId, edgeId, savedEdge.getCustomerId(), savedEdge, actionType, user); + + return savedEdge; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), edge, actionType, user, e); + throw e; } - - notificationEntityService.notifyEdge(tenantId, edgeId, savedEdge.getCustomerId(), savedEdge, actionType, user); - - return savedEdge; } @Override public void delete(Edge edge, User user) { EdgeId edgeId = edge.getId(); TenantId tenantId = edge.getTenantId(); - edgeService.deleteEdge(tenantId, edgeId); - notificationEntityService.notifyEdge(tenantId, edgeId, edge.getCustomerId(), edge, ActionType.DELETED, user, edgeId.toString()); + try { + edgeService.deleteEdge(tenantId, edgeId); + notificationEntityService.notifyEdge(tenantId, edgeId, edge.getCustomerId(), edge, ActionType.DELETED, user, edgeId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), ActionType.DELETED, + user, e, edgeId.toString()); + throw e; + } } @Override public Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, User user) throws ThingsboardException { CustomerId customerId = customer.getId(); - Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, - edgeId.toString(), customerId.toString(), customer.getName()); - - return savedEdge; + try { + Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, + edgeId.toString(), customerId.toString(), customer.getName()); + + return savedEdge; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), + ActionType.ASSIGNED_TO_CUSTOMER, user, e, edgeId.toString(), customerId.toString()); + throw e; + } } @Override @@ -83,31 +101,49 @@ public class DefaultTbEdgeService extends AbstractTbEntityService implements TbE TenantId tenantId = edge.getTenantId(); EdgeId edgeId = edge.getId(); CustomerId customerId = customer.getId(); - Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId)); - - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.UNASSIGNED_FROM_CUSTOMER, user, - edgeId.toString(), customerId.toString(), customer.getName()); - return savedEdge; + try { + Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId)); + + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.UNASSIGNED_FROM_CUSTOMER, user, + edgeId.toString(), customerId.toString(), customer.getName()); + return savedEdge; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), + ActionType.UNASSIGNED_FROM_CUSTOMER, user, e, edgeId.toString()); + throw e; + } } @Override public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException { Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); CustomerId customerId = publicCustomer.getId(); - Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); + try { + Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); - notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, - edgeId.toString(), customerId.toString(), publicCustomer.getName()); + notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, + edgeId.toString(), customerId.toString(), publicCustomer.getName()); - return savedEdge; + return savedEdge; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), + ActionType.ASSIGNED_TO_CUSTOMER, user, e, edgeId.toString()); + throw e; + } } @Override public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception { TenantId tenantId = edge.getTenantId(); EdgeId edgeId = edge.getId(); - Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); - notificationEntityService.notifyEdge(tenantId, edgeId, null, updatedEdge, ActionType.UPDATED, user); - return updatedEdge; + try { + Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); + notificationEntityService.notifyEdge(tenantId, edgeId, null, updatedEdge, ActionType.UPDATED, user); + return updatedEdge; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE), + ActionType.UPDATED, user, e, edgeId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java index 2af7ea773c..515f707c25 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java @@ -40,24 +40,46 @@ public class DefaultTbEntityRelationService extends AbstractTbEntityService impl @Override public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { - relationService.saveRelation(tenantId, relation); - notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, - relation, user, ActionType.RELATION_ADD_OR_UPDATE, relation); + try { + relationService.saveRelation(tenantId, relation); + notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, + relation, user, ActionType.RELATION_ADD_OR_UPDATE, relation); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, relation.getFrom(), null, customerId, + ActionType.RELATION_ADD_OR_UPDATE, user, e, relation); + notificationEntityService.logEntityAction(tenantId, relation.getTo(), null, customerId, + ActionType.RELATION_ADD_OR_UPDATE, user, e, relation); + throw e; + } } @Override public void delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { - boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); - if (!found) { - throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); + try { + boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup()); + if (!found) { + throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); + } + notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, + relation, user, ActionType.RELATION_DELETED, relation); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, relation.getFrom(), null, customerId, + ActionType.RELATION_DELETED, user, e, relation); + notificationEntityService.logEntityAction(tenantId, relation.getTo(), null, customerId, + ActionType.RELATION_DELETED, user, e, relation); + throw e; } - notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, - relation, user, ActionType.RELATION_DELETED, relation); } @Override public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) throws ThingsboardException { - relationService.deleteEntityRelations(tenantId, entityId); - notificationEntityService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user); + try { + relationService.deleteEntityRelations(tenantId, entityId); + notificationEntityService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, entityId, null, customerId, + ActionType.RELATIONS_DELETED, user, e); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java index 962603cd37..a49b17ee51 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java @@ -25,6 +25,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DataConstants; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; @@ -71,78 +72,108 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen public EntityView save(EntityView entityView, EntityView existingEntityView, User user) throws ThingsboardException { ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = entityView.getTenantId(); - List> futures = new ArrayList<>(); - if (existingEntityView != null) { - if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + try { + List> futures = new ArrayList<>(); + if (existingEntityView != null) { + if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); + } + List tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? + existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); + futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); } - List tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? - existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); - futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); - } - EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); - if (savedEntityView.getKeys() != null) { - if (savedEntityView.getKeys().getAttributes() != null) { - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user)); - futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user)); + EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); + if (savedEntityView.getKeys() != null) { + if (savedEntityView.getKeys().getAttributes() != null) { + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user)); + futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user)); + } + futures.add(copyLatestFromEntityToEntityView(tenantId, savedEntityView)); } - futures.add(copyLatestFromEntityToEntityView(tenantId, savedEntityView)); - } - for (ListenableFuture future : futures) { - try { - future.get(); - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException("Failed to copy attributes to entity view", e); + for (ListenableFuture future : futures) { + try { + future.get(); + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException("Failed to copy attributes to entity view", e); + } } - } - notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedEntityView.getId(), savedEntityView, - null, actionType, user); + notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedEntityView.getId(), savedEntityView, + null, actionType, user); - return savedEntityView; + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), entityView, + actionType, user, e); + throw e; + } } @Override public void delete(EntityView entityView, User user) throws ThingsboardException { TenantId tenantId = entityView.getTenantId(); EntityViewId entityViewId = entityView.getId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); - entityViewService.deleteEntityView(tenantId, entityViewId); - notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, - relatedEdgeIds, user, entityViewId.toString()); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); + entityViewService.deleteEntityView(tenantId, entityViewId); + notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, + relatedEdgeIds, user, entityViewId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.DELETED, user, e, entityViewId.toString()); + throw e; + } } @Override public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { CustomerId customerId = customer.getId(); - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - ActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); - return savedEntityView; + try { + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, + ActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_CUSTOMER, user, e, entityViewId.toString(), customerId.toString()); + throw e; + } } @Override public EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, EntityViewId entityViewId, User user) throws ThingsboardException { - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, - entityViewId, publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - ActionType.ASSIGNED_TO_CUSTOMER, user, false, savedEntityView.getEntityId().toString(), - publicCustomer.getId().toString(), publicCustomer.getName()); - return savedEntityView; + try { + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, + entityViewId, publicCustomer.getId())); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, + ActionType.ASSIGNED_TO_CUSTOMER, user, false, savedEntityView.getEntityId().toString(), + publicCustomer.getId().toString(), publicCustomer.getName()); + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_CUSTOMER, user, e, entityViewId.toString()); + throw e; + } } @Override public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, User user) throws ThingsboardException { EdgeId edgeId = edge.getId(); - EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, - edgeId, savedEntityView, ActionType.ASSIGNED_TO_EDGE, user, savedEntityView.getEntityId().toString(), - edgeId.toString(), edge.getName()); - return savedEntityView; + try { + EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, + edgeId, savedEntityView, ActionType.ASSIGNED_TO_EDGE, user, savedEntityView.getEntityId().toString(), + edgeId.toString(), edge.getName()); + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.ASSIGNED_TO_EDGE, user, e, entityViewId.toString(), edgeId.toString()); + throw e; + } } @Override @@ -150,19 +181,31 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen Edge edge, User user) throws ThingsboardException { EntityViewId entityViewId = entityView.getId(); EdgeId edgeId = edge.getId(); - EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, - edgeId, entityView, ActionType.UNASSIGNED_FROM_EDGE, user, entityViewId.toString(), - edgeId.toString(), edge.getName()); - return savedEntityView; + try { + EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, + edgeId, entityView, ActionType.UNASSIGNED_FROM_EDGE, user, entityViewId.toString(), + edgeId.toString(), edge.getName()); + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.UNASSIGNED_FROM_EDGE, user, e, entityViewId.toString(), edgeId.toString()); + throw e; + } } @Override public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { - EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, - ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); - return savedEntityView; + try { + EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, + ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); + return savedEntityView; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), + ActionType.UNASSIGNED_FROM_CUSTOMER, user, e, entityViewId.toString()); + throw e; + } } private ListenableFuture> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection keys, User user) throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java index 78c1447d0e..68b115e70a 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java @@ -18,6 +18,7 @@ package org.thingsboard.server.service.entitiy.ota; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.OtaPackage; import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; @@ -44,12 +45,18 @@ public class DefaultTbOtaPackageService extends AbstractTbEntityService implemen @Override public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, User user) throws ThingsboardException { - TenantId tenantId = saveOtaPackageInfoRequest.getTenantId(); ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - OtaPackageInfo savedOtaPackageInfo = checkNotNull(otaPackageService.saveOtaPackageInfo( - new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl())); - notificationEntityService.logEntityAction(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, actionType, user); - return savedOtaPackageInfo; + TenantId tenantId = saveOtaPackageInfoRequest.getTenantId(); + try { + OtaPackageInfo savedOtaPackageInfo = checkNotNull(otaPackageService.saveOtaPackageInfo( + new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl())); + notificationEntityService.logEntityAction(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, actionType, user); + return savedOtaPackageInfo; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.OTA_PACKAGE), saveOtaPackageInfoRequest, + actionType, user, e); + throw e; + } } @Override @@ -57,35 +64,47 @@ public class DefaultTbOtaPackageService extends AbstractTbEntityService implemen byte[] data, String filename, String contentType, User user) throws ThingsboardException { TenantId tenantId = otaPackageInfo.getTenantId(); OtaPackageId otaPackageId = otaPackageInfo.getId(); - if (StringUtils.isEmpty(checksum)) { - checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); + try { + if (StringUtils.isEmpty(checksum)) { + checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); + } + OtaPackage otaPackage = new OtaPackage(otaPackageId); + otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime()); + otaPackage.setTenantId(tenantId); + otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId()); + otaPackage.setType(otaPackageInfo.getType()); + otaPackage.setTitle(otaPackageInfo.getTitle()); + otaPackage.setVersion(otaPackageInfo.getVersion()); + otaPackage.setTag(otaPackageInfo.getTag()); + otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo()); + otaPackage.setChecksumAlgorithm(checksumAlgorithm); + otaPackage.setChecksum(checksum); + otaPackage.setFileName(filename); + otaPackage.setContentType(contentType); + otaPackage.setData(ByteBuffer.wrap(data)); + otaPackage.setDataSize((long) data.length); + OtaPackageInfo savedOtaPackage = otaPackageService.saveOtaPackage(otaPackage); + notificationEntityService.logEntityAction(tenantId, savedOtaPackage.getId(), savedOtaPackage, ActionType.UPDATED, user); + return savedOtaPackage; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.OTA_PACKAGE), ActionType.UPDATED, + user, e, otaPackageId.toString()); + throw e; } - OtaPackage otaPackage = new OtaPackage(otaPackageId); - otaPackage.setCreatedTime(otaPackageInfo.getCreatedTime()); - otaPackage.setTenantId(tenantId); - otaPackage.setDeviceProfileId(otaPackageInfo.getDeviceProfileId()); - otaPackage.setType(otaPackageInfo.getType()); - otaPackage.setTitle(otaPackageInfo.getTitle()); - otaPackage.setVersion(otaPackageInfo.getVersion()); - otaPackage.setTag(otaPackageInfo.getTag()); - otaPackage.setAdditionalInfo(otaPackageInfo.getAdditionalInfo()); - otaPackage.setChecksumAlgorithm(checksumAlgorithm); - otaPackage.setChecksum(checksum); - otaPackage.setFileName(filename); - otaPackage.setContentType(contentType); - otaPackage.setData(ByteBuffer.wrap(data)); - otaPackage.setDataSize((long) data.length); - OtaPackageInfo savedOtaPackage = otaPackageService.saveOtaPackage(otaPackage); - notificationEntityService.logEntityAction(tenantId, savedOtaPackage.getId(), savedOtaPackage, ActionType.UPDATED, user); - return savedOtaPackage; } @Override public void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException { TenantId tenantId = otaPackageInfo.getTenantId(); OtaPackageId otaPackageId = otaPackageInfo.getId(); - otaPackageService.deleteOtaPackage(tenantId, otaPackageId); - notificationEntityService.logEntityAction(tenantId, otaPackageId, otaPackageInfo, ActionType.DELETED, user, - otaPackageInfo.getId().toString()); + try { + otaPackageService.deleteOtaPackage(tenantId, otaPackageId); + notificationEntityService.logEntityAction(tenantId, otaPackageId, otaPackageInfo, ActionType.DELETED, user, + otaPackageInfo.getId().toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.OTA_PACKAGE), + ActionType.DELETED, user, e, otaPackageId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java index d323f0154c..e465e70ad7 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java @@ -19,6 +19,7 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; @@ -51,33 +52,44 @@ public class DefaultUserService extends AbstractTbEntityService implements TbUse public User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail, HttpServletRequest request, User user) throws ThingsboardException { ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED; - boolean sendEmail = tbUser.getId() == null && sendActivationMail; - User savedUser = checkNotNull(userService.saveUser(tbUser)); - if (sendEmail) { - UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); - String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); - String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, - userCredentials.getActivateToken()); - String email = savedUser.getEmail(); - try { - mailService.sendActivationEmail(activateUrl, email); - } catch (ThingsboardException e) { - userService.deleteUser(tenantId, savedUser.getId()); - throw e; + try { + boolean sendEmail = tbUser.getId() == null && sendActivationMail; + User savedUser = checkNotNull(userService.saveUser(tbUser)); + if (sendEmail) { + UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); + String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); + String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, + userCredentials.getActivateToken()); + String email = savedUser.getEmail(); + try { + mailService.sendActivationEmail(activateUrl, email); + } catch (ThingsboardException e) { + userService.deleteUser(tenantId, savedUser.getId()); + throw e; + } } + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, customerId, savedUser.getId(), + savedUser, user, actionType, true, null); + return savedUser; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.USER), user, actionType, user, e); + throw e; } - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, customerId, savedUser.getId(), - savedUser, user, actionType, true, null); - return savedUser; } @Override public void delete(TenantId tenantId, CustomerId customerId, User tbUser, User user) throws ThingsboardException { UserId userId = tbUser.getId(); - List relatedEdgeIds = findRelatedEdgeIds(tenantId, userId); - userService.deleteUser(tenantId, userId); - notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, - ActionType.DELETED, relatedEdgeIds, user, userId.toString()); + try { + List relatedEdgeIds = findRelatedEdgeIds(tenantId, userId); + userService.deleteUser(tenantId, userId); + notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, + ActionType.DELETED, relatedEdgeIds, user, userId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.USER), + ActionType.DELETED, user, e, userId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java index 1e74daf43c..a0799a2786 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java @@ -22,6 +22,7 @@ import org.eclipse.leshan.core.model.DefaultDDFFileValidator; import org.eclipse.leshan.core.model.InvalidDDFFileException; import org.eclipse.leshan.core.model.ObjectModel; import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; @@ -220,19 +221,30 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements public TbResource save(TbResource tbResource, User user) throws ThingsboardException { ActionType actionType = tbResource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = tbResource.getTenantId(); - - TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); - tbClusterService.onResourceChange(savedResource, null); - notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user); - return savedResource; + try { + TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); + tbClusterService.onResourceChange(savedResource, null); + notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user); + return savedResource; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.TB_RESOURCE), + tbResource, actionType, user, e); + throw e; + } } @Override public void delete(TbResource tbResource, User user) { TbResourceId resourceId = tbResource.getId(); TenantId tenantId = tbResource.getTenantId(); - resourceService.deleteResource(tenantId, resourceId); - tbClusterService.onResourceDeleted(tbResource, null); - notificationEntityService.logEntityAction(tenantId, resourceId, tbResource, ActionType.DELETED, user, resourceId.toString()); + try { + resourceService.deleteResource(tenantId, resourceId); + tbClusterService.onResourceDeleted(tbResource, null); + notificationEntityService.logEntityAction(tenantId, resourceId, tbResource, ActionType.DELETED, user, resourceId.toString()); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.TB_RESOURCE), + ActionType.DELETED, user, e, resourceId.toString()); + throw e; + } } } diff --git a/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java b/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java index a166978df7..1687922f06 100644 --- a/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java +++ b/application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java @@ -22,6 +22,7 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.flow.TbRuleChainInputNode; import org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration; import org.thingsboard.rule.engine.flow.TbRuleChainOutputNode; +import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; @@ -170,73 +171,97 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement TenantId tenantId = ruleChain.getTenantId(); ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED; RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain)); - - if (RuleChainType.CORE.equals(savedRuleChain.getType())) { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), - actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + try { + if (RuleChainType.CORE.equals(savedRuleChain.getType())) { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), + actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); + } + boolean sendMsgToEdge = RuleChainType.EDGE.equals(savedRuleChain.getType()) && actionType.equals(ActionType.UPDATED); + notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedRuleChain.getId(), + savedRuleChain, user, actionType, sendMsgToEdge, null); + return savedRuleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ruleChain, actionType, user, e); + throw e; } - boolean sendMsgToEdge = RuleChainType.EDGE.equals(savedRuleChain.getType()) && actionType.equals(ActionType.UPDATED); - notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedRuleChain.getId(), - savedRuleChain, user, actionType, sendMsgToEdge, null); - return savedRuleChain; } @Override public void delete(RuleChain ruleChain, User user) { TenantId tenantId = ruleChain.getTenantId(); RuleChainId ruleChainId = ruleChain.getId(); - List referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId); + try { + List referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId); - Set referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet()); + Set referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet()); - List relatedEdgeIds = null; - if (RuleChainType.EDGE.equals(ruleChain.getType())) { - relatedEdgeIds = findRelatedEdgeIds(tenantId, ruleChainId); - } + List relatedEdgeIds = null; + if (RuleChainType.EDGE.equals(ruleChain.getType())) { + relatedEdgeIds = findRelatedEdgeIds(tenantId, ruleChainId); + } - ruleChainService.deleteRuleChainById(tenantId, ruleChainId); + ruleChainService.deleteRuleChainById(tenantId, ruleChainId); - referencingRuleChainIds.remove(ruleChain.getId()); + referencingRuleChainIds.remove(ruleChain.getId()); - if (RuleChainType.CORE.equals(ruleChain.getType())) { - referencingRuleChainIds.forEach(referencingRuleChainId -> - tbClusterService.broadcastEntityStateChangeEvent(tenantId, referencingRuleChainId, ComponentLifecycleEvent.UPDATED)); + if (RuleChainType.CORE.equals(ruleChain.getType())) { + referencingRuleChainIds.forEach(referencingRuleChainId -> + tbClusterService.broadcastEntityStateChangeEvent(tenantId, referencingRuleChainId, ComponentLifecycleEvent.UPDATED)); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChain.getId(), ComponentLifecycleEvent.DELETED); - } + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChain.getId(), ComponentLifecycleEvent.DELETED); + } - notificationEntityService.notifyDeleteRuleChain(tenantId, ruleChain, relatedEdgeIds, user); + notificationEntityService.notifyDeleteRuleChain(tenantId, ruleChain, relatedEdgeIds, user); + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.DELETED, + user, e, ruleChainId.toString()); + throw e; + } } @Override public RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, User user) throws IOException { - RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName()); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED); - notificationEntityService.logEntityAction(tenantId, savedRuleChain.getId(), savedRuleChain, ActionType.ADDED, user); - return savedRuleChain; + try { + RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName()); + tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED); + notificationEntityService.logEntityAction(tenantId, savedRuleChain.getId(), savedRuleChain, ActionType.ADDED, user); + return savedRuleChain; + } catch (Exception e) { + RuleChain ruleChain = new RuleChain(); + ruleChain.setName(request.getName()); + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ruleChain, + ActionType.ADDED, user, e); + throw e; + } } @Override public RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); - if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) { - if (previousRootRuleChain != null) { - RuleChainId previousRootRuleChainId = previousRootRuleChain.getId(); - previousRootRuleChain = ruleChainService.findRuleChainById(tenantId, previousRootRuleChainId); + try { + RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); + if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) { + if (previousRootRuleChain != null) { + RuleChainId previousRootRuleChainId = previousRootRuleChain.getId(); + previousRootRuleChain = ruleChainService.findRuleChainById(tenantId, previousRootRuleChainId); + + tbClusterService.broadcastEntityStateChangeEvent(tenantId, previousRootRuleChainId, + ComponentLifecycleEvent.UPDATED); + notificationEntityService.logEntityAction(tenantId, previousRootRuleChainId, previousRootRuleChain, + ActionType.UPDATED, user); + } + ruleChain = ruleChainService.findRuleChainById(tenantId, ruleChainId); - tbClusterService.broadcastEntityStateChangeEvent(tenantId, previousRootRuleChainId, + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, ComponentLifecycleEvent.UPDATED); - notificationEntityService.logEntityAction(tenantId, previousRootRuleChainId, previousRootRuleChain, - ActionType.UPDATED, user); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); } - ruleChain = ruleChainService.findRuleChainById(tenantId, ruleChainId); - - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, - ComponentLifecycleEvent.UPDATED); - notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + user, e, ruleChainId.toString()); + throw e; } - return ruleChain; } @Override @@ -244,85 +269,123 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement boolean updateRelated, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainMetaDataId = ruleChainMetaData.getRuleChainId(); - RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); - checkNotNull(result.isSuccess() ? true : null); - - List updatedRuleChains; - if (updateRelated && result.isSuccess()) { - updatedRuleChains = updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result); - } else { - updatedRuleChains = Collections.emptyList(); - } + try { + RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); + checkNotNull(result.isSuccess() ? true : null); - RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId)); + List updatedRuleChains; + if (updateRelated && result.isSuccess()) { + updatedRuleChains = updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result); + } else { + updatedRuleChains = Collections.emptyList(); + } - if (RuleChainType.CORE.equals(ruleChain.getType())) { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, ComponentLifecycleEvent.UPDATED); - updatedRuleChains.forEach(updatedRuleChain -> { - tbClusterService.broadcastEntityStateChangeEvent(tenantId, updatedRuleChain.getId(), ComponentLifecycleEvent.UPDATED); - }); - } + RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId)); - notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user, ruleChainMetaData); + if (RuleChainType.CORE.equals(ruleChain.getType())) { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, ComponentLifecycleEvent.UPDATED); + updatedRuleChains.forEach(updatedRuleChain -> { + tbClusterService.broadcastEntityStateChangeEvent(tenantId, updatedRuleChain.getId(), ComponentLifecycleEvent.UPDATED); + }); + } - if (RuleChainType.EDGE.equals(ruleChain.getType())) { - notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED); - } + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user, ruleChainMetaData); - for (RuleChain updatedRuleChain : updatedRuleChains) { if (RuleChainType.EDGE.equals(ruleChain.getType())) { - notificationEntityService.notifySendMsgToEdgeService(tenantId, updatedRuleChain.getId(), EdgeEventActionType.UPDATED); - } else { - RuleChainMetaData updatedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, updatedRuleChain.getId())); - notificationEntityService.logEntityAction(tenantId, updatedRuleChain.getId(), updatedRuleChain, - ActionType.UPDATED, user, updatedRuleChainMetaData); + notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED); } + + for (RuleChain updatedRuleChain : updatedRuleChains) { + if (RuleChainType.EDGE.equals(ruleChain.getType())) { + notificationEntityService.notifySendMsgToEdgeService(tenantId, updatedRuleChain.getId(), EdgeEventActionType.UPDATED); + } else { + RuleChainMetaData updatedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, updatedRuleChain.getId())); + notificationEntityService.logEntityAction(tenantId, updatedRuleChain.getId(), updatedRuleChain, + ActionType.UPDATED, user, updatedRuleChainMetaData); + } + } + return savedRuleChainMetaData; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.ADDED, + user, e, ruleChainMetaData); + throw e; } - return savedRuleChainMetaData; } @Override public RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edge.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, - null, edge.getId(), savedRuleChain, ActionType.ASSIGNED_TO_EDGE, - user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); - return savedRuleChain; + EdgeId edgeId = edge.getId(); + try { + RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edgeId)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, + null, edgeId, savedRuleChain, ActionType.ASSIGNED_TO_EDGE, + user, ruleChainId.toString(), edgeId.toString(), edge.getName()); + return savedRuleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), + ActionType.ASSIGNED_TO_EDGE, user, e, ruleChainId.toString(), edgeId.toString()); + throw e; + } } @Override public RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edge.getId(), false)); - notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, - null, edge.getId(), savedRuleChain, ActionType.UNASSIGNED_FROM_EDGE, - user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); - return savedRuleChain; + EdgeId edgeId = edge.getId(); + try { + RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edgeId, false)); + notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, + null, edgeId, savedRuleChain, ActionType.UNASSIGNED_FROM_EDGE, + user, ruleChainId.toString(), edgeId.toString(), edge.getName()); + return savedRuleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), + ActionType.UNASSIGNED_FROM_EDGE, user, e, ruleChainId, edgeId); + throw e; + } } @Override public RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId); - notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); - return ruleChain; + try { + ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + user, e, ruleChainId.toString()); + throw e; + } } @Override public RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId); - notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); - return ruleChain; + try { + ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + user, e, ruleChainId.toString()); + throw e; + } } @Override public RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { RuleChainId ruleChainId = ruleChain.getId(); - ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId); - notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); - return ruleChain; + try { + ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId); + notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); + return ruleChain; + } catch (Exception e) { + notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED, + user, e, ruleChainId.toString()); + throw e; + } } private Set updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map labelsMap) { From 475fa7e9f5b6f7025dff3bfd88bc1fce8581ddfd Mon Sep 17 00:00:00 2001 From: ivankozka Date: Wed, 22 Jun 2022 17:39:30 +0300 Subject: [PATCH 4/7] fix mapping api endpoints in swagger --- application/src/main/resources/thingsboard.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 07233bb241..33e575606a 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -499,6 +499,9 @@ spring.mvc.cors: # The default timeout for asynchronous requests in milliseconds spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" +# For endpoints matching in Swagger +spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" + # spring serve gzip compressed static resources spring.resources.chain: compressed: "true" From 3d3d29e905a8965285b11294ce1baf02a459d9f4 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 23 Jun 2022 12:21:11 +0300 Subject: [PATCH 5/7] fix bug: additionalInfo Asset, Alarm, Customer --- .../entitiy/asset/DefaultTbAssetService.java | 7 +++--- .../customer/DefaultTbCustomerService.java | 2 +- .../dashboard/DefaultTbDashboardService.java | 23 ++++++++++++------- .../device/DefaultTbDeviceService.java | 8 ++++--- .../DefaultTbEntityViewService.java | 6 ++--- .../server/controller/AbstractWebTest.java | 6 ++--- .../controller/BaseAssetControllerTest.java | 11 ++++++--- .../BaseCustomerControllerTest.java | 7 ++++++ 8 files changed, 46 insertions(+), 24 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java index e118346588..89d64d5443 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java @@ -81,7 +81,8 @@ public class DefaultTbAssetService extends AbstractTbEntityService implements Tb try { Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, edgeTypeByActionType(actionType), user, true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, assetId.toString(), + customerId.toString(), customer.getName()); return savedAsset; } catch (Exception e) { @@ -100,8 +101,8 @@ public class DefaultTbAssetService extends AbstractTbEntityService implements Tb CustomerId customerId = customer.getId(); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, - actionType, edgeTypeByActionType(actionType), user, - true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, assetId.toString(), + customerId.toString(), customer.getName()); return savedAsset; } catch (Exception e) { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java index 536e1be976..29d1e6dadd 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java @@ -64,7 +64,7 @@ public class DefaultTbCustomerService extends AbstractTbEntityService implements tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); } catch (Exception e) { notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.CUSTOMER), null, null, - ActionType.DELETED, user, e, customer.getId().toString()); + ActionType.DELETED, user, e, customerId.toString()); throw handleException(e); } } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java index a475ff77da..957ff5a1d0 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java @@ -23,7 +23,6 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.ShortCustomerInfo; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; @@ -37,6 +36,8 @@ import java.util.HashSet; import java.util.List; import java.util.Set; +import static org.thingsboard.server.service.entitiy.DefaultTbNotificationEntityService.edgeTypeByActionType; + @Service @TbCoreComponent @AllArgsConstructor @@ -81,7 +82,7 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement try { Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(user.getTenantId(), dashboardId, customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboardId, customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, dashboardId.toString(), customerId.toString(), customer.getName()); return savedDashboard; } catch (Exception e) { notificationEntityService.notifyEntity(user.getTenantId(), emptyId(EntityType.DASHBOARD), null, null, @@ -113,7 +114,7 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement try { Customer publicCustomer = customerService.findOrCreatePublicCustomer(dashboard.getTenantId()); Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(user.getTenantId(), dashboard.getId(), publicCustomer.getId())); - notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboard.getId(), user.getCustomerId(), dashboard, + notificationEntityService.notifyAssignOrUnassignEntityToCustomer(user.getTenantId(), dashboard.getId(), user.getCustomerId(), savedDashboard, actionType, null, user, false, dashboard.getId().toString(), publicCustomer.getId().toString(), publicCustomer.getName()); return savedDashboard; @@ -154,13 +155,16 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); + actionType, edgeTypeByActionType(actionType), user, true, dashboard.getId().toString(), + customerId.toString(), customerInfo.getTitle()); } + actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; for (CustomerId customerId : removedCustomerIds) { ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - ActionType.UNASSIGNED_FROM_CUSTOMER, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); + actionType, edgeTypeByActionType(actionType), user, true, dashboard.getId().toString(), + customerId.toString(), customerInfo.getTitle()); } return savedDashboard; } @@ -184,7 +188,8 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerInfo.getTitle()); + actionType, edgeTypeByActionType(actionType), user, true, dashboard.getId().toString(), + customerId.toString(), customerInfo.getTitle()); } return savedDashboard; } @@ -208,7 +213,8 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); + actionType, edgeTypeByActionType(actionType), user, true, dashboard.getId().toString(), + customerId.toString(), customerInfo.getTitle()); } return savedDashboard; } @@ -264,7 +270,8 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement try { Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, dashboard.getId().toString(), customer.getId().toString(), + customer.getName()); return savedDashboard; } catch (Exception e) { notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.DASHBOARD), null, null, diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java index 5199887940..dccc506db1 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java @@ -43,6 +43,8 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; +import static org.thingsboard.server.service.entitiy.DefaultTbNotificationEntityService.edgeTypeByActionType; + @AllArgsConstructor @TbCoreComponent @Service @@ -105,7 +107,7 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T try { Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(user.getTenantId(), deviceId, customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, deviceId.toString(), customerId.toString(), customer.getName()); return savedDevice; } catch (Exception e) { @@ -125,8 +127,8 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T CustomerId customerId = customer.getId(); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, - true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, + true, deviceId.toString(), customerId.toString(), customer.getName()); return savedDevice; } catch (Exception e) { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java index cd30276fab..c990e99cd6 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java @@ -30,7 +30,6 @@ import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.edge.Edge; -import org.thingsboard.server.common.data.edge.EdgeEventActionType; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EdgeId; @@ -58,6 +57,7 @@ import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static org.apache.commons.lang3.StringUtils.isBlank; +import static org.thingsboard.server.service.entitiy.DefaultTbNotificationEntityService.edgeTypeByActionType; @Service @AllArgsConstructor @@ -147,7 +147,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen try { EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - actionType, EdgeEventActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, customerId.toString(), customer.getName()); return savedEntityView; } catch (Exception e) { notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, @@ -216,7 +216,7 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen try { EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, - actionType, EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, customer.getId().toString(), customer.getName()); return savedEntityView; } catch (Exception e) { notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java index 8b17c9baf3..1939c75673 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java @@ -278,7 +278,8 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { login(userName, password); } - private Tenant savedDifferentTenant; + protected Tenant savedDifferentTenant; + protected User savedDifferentTenantUser; private Customer savedDifferentCustomer; protected void loginDifferentTenant() throws Exception { @@ -296,8 +297,7 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { differentTenantAdmin.setAuthority(Authority.TENANT_ADMIN); differentTenantAdmin.setTenantId(savedDifferentTenant.getId()); differentTenantAdmin.setEmail(DIFFERENT_TENANT_ADMIN_EMAIL); - - createUserAndLogin(differentTenantAdmin, DIFFERENT_TENANT_ADMIN_PASSWORD); + savedDifferentTenantUser = createUserAndLogin(differentTenantAdmin, DIFFERENT_TENANT_ADMIN_PASSWORD); } } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java index 0f8f2d11be..0423d08edd 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java @@ -163,6 +163,11 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest { testNotifyEntityNever(savedAsset.getId(), savedAsset); + doDelete("/api/asset" + savedAsset.getId().getId().toString()) + .andExpect(status().isNotFound()); + + testNotifyEntityNever(savedAsset.getId(), savedAsset); + deleteDifferentTenant(); } @@ -329,7 +334,7 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest { testNotifyEntityAllOneTime(assignedAsset, assignedAsset.getId(), assignedAsset.getId(), savedTenant.getId(), savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), - ActionType.ASSIGNED_TO_CUSTOMER, savedCustomer.getId().toString(), savedCustomer.getTitle()); + ActionType.ASSIGNED_TO_CUSTOMER, assignedAsset.getId().toString(), savedCustomer.getId().toString(), savedCustomer.getTitle()); Asset foundAsset = doGet("/api/asset/" + savedAsset.getId().getId().toString(), Asset.class); Assert.assertEquals(savedCustomer.getId(), foundAsset.getCustomerId()); @@ -342,7 +347,7 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest { testNotifyEntityAllOneTime(savedAsset, savedAsset.getId(), savedAsset.getId(), savedTenant.getId(), savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), - ActionType.UNASSIGNED_FROM_CUSTOMER, savedCustomer.getId().toString(), savedCustomer.getTitle()); + ActionType.UNASSIGNED_FROM_CUSTOMER, savedAsset.getId().toString(), savedCustomer.getId().toString(), savedCustomer.getTitle()); foundAsset = doGet("/api/asset/" + savedAsset.getId().getId().toString(), Asset.class); Assert.assertEquals(ModelConstants.NULL_UUID, foundAsset.getCustomerId().getId()); @@ -381,7 +386,7 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest { tenantAdmin2.setFirstName("Joe"); tenantAdmin2.setLastName("Downs"); - tenantAdmin2 = createUserAndLogin(tenantAdmin2, "testPassword1"); + createUserAndLogin(tenantAdmin2, "testPassword1"); Customer customer = new Customer(); customer.setTitle("Different customer"); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java index 1e2349985f..bbba51bd60 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java @@ -194,9 +194,16 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest testNotifyEntityNever(savedCustomer.getId(), savedCustomer); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) + .andExpect(status().isForbidden()); + + testNotifyEntityNever(savedCustomer.getId(), savedCustomer); + deleteDifferentTenant(); login(tenantAdmin.getName(), "testPassword1"); + Mockito.reset(tbClusterService, auditLogService); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) .andExpect(status().isOk()); From d80452ef400a35dacf46331dcf7eeb911d3c3cf4 Mon Sep 17 00:00:00 2001 From: nickAS21 Date: Thu, 23 Jun 2022 15:13:25 +0300 Subject: [PATCH 6/7] fix bug: EntityView, otaPackage --- .../service/entitiy/entityView/DefaultTbEntityViewService.java | 3 ++- .../otaPackageController/DefaultTbOtaPackageService.java | 2 -- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java index c990e99cd6..d38410563e 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/entityView/DefaultTbEntityViewService.java @@ -147,7 +147,8 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen try { EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, - actionType, edgeTypeByActionType(actionType), user, true, customerId.toString(), customer.getName()); + actionType, edgeTypeByActionType(actionType), user, true, entityViewId.toString(), customerId.toString(), + customer.getName()); return savedEntityView; } catch (Exception e) { notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ENTITY_VIEW), null, null, diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java index ffa13d1e63..5d32cdce95 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/otaPackageController/DefaultTbOtaPackageService.java @@ -63,8 +63,6 @@ public class DefaultTbOtaPackageService extends AbstractTbEntityService implemen OtaPackageId otaPackageId = otaPackageInfo.getId(); try { otaPackageService.deleteOtaPackage(tenantId, otaPackageId); -// notificationEntityService.notifyEntity(tenantId, otaPackageId, otaPackageInfo, null, -// ActionType.DELETED, user, null, otaPackageInfo.getId().toString()); notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, otaPackageId, otaPackageInfo, user, ActionType.DELETED, true, null, otaPackageInfo.getId().toString()); From faa07360d52d62b40c9aba655c613c0f6e02765f Mon Sep 17 00:00:00 2001 From: YevhenBondarenko Date: Mon, 27 Jun 2022 15:06:37 +0200 Subject: [PATCH 7/7] fixed alarn tests and refactored tb resource service --- .../resource/DefaultTbResourceService.java | 79 +++++++++---------- .../service/resource/TbResourceService.java | 3 - .../controller/BaseAlarmControllerTest.java | 2 +- .../sql/BaseTbResourceServiceTest.java | 35 ++++---- 4 files changed, 57 insertions(+), 62 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java index a0799a2786..d83508220b 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java @@ -69,45 +69,6 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements this.ddfFileParser = new DDFFileParser(new DefaultDDFFileValidator()); } - @Override - public TbResource saveResourceInternal(TbResource resource) throws ThingsboardException { - log.trace("Executing saveResource [{}]", resource); - if (StringUtils.isEmpty(resource.getData())) { - throw new DataValidationException("Resource data should be specified!"); - } - if (ResourceType.LWM2M_MODEL.equals(resource.getResourceType())) { - try { - List objectModels = - ddfFileParser.parse(new ByteArrayInputStream(Base64.getDecoder().decode(resource.getData())), resource.getSearchText()); - if (!objectModels.isEmpty()) { - ObjectModel objectModel = objectModels.get(0); - - String resourceKey = objectModel.id + LWM2M_SEPARATOR_KEY + objectModel.version; - String name = objectModel.name; - resource.setResourceKey(resourceKey); - if (resource.getId() == null) { - resource.setTitle(name + " id=" + objectModel.id + " v" + objectModel.version); - } - resource.setSearchText(resourceKey + LWM2M_SEPARATOR_SEARCH_TEXT + name); - } else { - throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText())); - } - } catch (InvalidDDFFileException e) { - log.error("Failed to parse file {}", resource.getFileName(), e); - throw new DataValidationException("Failed to parse file " + resource.getFileName()); - } catch (IOException e) { - throw new ThingsboardException(e, ThingsboardErrorCode.GENERAL); - } - if (resource.getResourceType().equals(ResourceType.LWM2M_MODEL) && toLwM2mObject(resource, true) == null) { - throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText())); - } - } else { - resource.setResourceKey(resource.getFileName()); - } - - return resourceService.saveResource(resource); - } - @Override public TbResource getResource(TenantId tenantId, ResourceType resourceType, String resourceId) { return resourceService.getResource(tenantId, resourceType, resourceId); @@ -222,7 +183,7 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements ActionType actionType = tbResource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; TenantId tenantId = tbResource.getTenantId(); try { - TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); + TbResource savedResource = checkNotNull(doSave(tbResource)); tbClusterService.onResourceChange(savedResource, null); notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user); return savedResource; @@ -247,4 +208,42 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements throw e; } } + + private TbResource doSave(TbResource resource) throws ThingsboardException { + log.trace("Executing saveResource [{}]", resource); + if (StringUtils.isEmpty(resource.getData())) { + throw new DataValidationException("Resource data should be specified!"); + } + if (ResourceType.LWM2M_MODEL.equals(resource.getResourceType())) { + try { + List objectModels = + ddfFileParser.parse(new ByteArrayInputStream(Base64.getDecoder().decode(resource.getData())), resource.getSearchText()); + if (!objectModels.isEmpty()) { + ObjectModel objectModel = objectModels.get(0); + + String resourceKey = objectModel.id + LWM2M_SEPARATOR_KEY + objectModel.version; + String name = objectModel.name; + resource.setResourceKey(resourceKey); + if (resource.getId() == null) { + resource.setTitle(name + " id=" + objectModel.id + " v" + objectModel.version); + } + resource.setSearchText(resourceKey + LWM2M_SEPARATOR_SEARCH_TEXT + name); + } else { + throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText())); + } + } catch (InvalidDDFFileException e) { + log.error("Failed to parse file {}", resource.getFileName(), e); + throw new DataValidationException("Failed to parse file " + resource.getFileName()); + } catch (IOException e) { + throw new ThingsboardException(e, ThingsboardErrorCode.GENERAL); + } + if (resource.getResourceType().equals(ResourceType.LWM2M_MODEL) && toLwM2mObject(resource, true) == null) { + throw new DataValidationException(String.format("Could not parse the XML of objectModel with name %s", resource.getSearchText())); + } + } else { + resource.setResourceKey(resource.getFileName()); + } + + return resourceService.saveResource(resource); + } } diff --git a/application/src/main/java/org/thingsboard/server/service/resource/TbResourceService.java b/application/src/main/java/org/thingsboard/server/service/resource/TbResourceService.java index 3bcb7f0722..6fd95660fc 100644 --- a/application/src/main/java/org/thingsboard/server/service/resource/TbResourceService.java +++ b/application/src/main/java/org/thingsboard/server/service/resource/TbResourceService.java @@ -18,7 +18,6 @@ package org.thingsboard.server.service.resource; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; -import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.lwm2m.LwM2mObject; @@ -30,8 +29,6 @@ import java.util.List; public interface TbResourceService extends SimpleTbEntityService { - TbResource saveResourceInternal(TbResource resource) throws ThingsboardException; - TbResource getResource(TenantId tenantId, ResourceType resourceType, String resourceKey); TbResource findResourceById(TenantId tenantId, TbResourceId resourceId); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java index 7f1943d8bd..95c90dea30 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java @@ -175,7 +175,7 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest { doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isOk()); testNotifyEntityOneTimeMsgToEdgeServiceNever(alarm, alarm.getId(), alarm.getOriginator(), - tenantId, tenantAdminCustomerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.DELETED); + tenantId, customerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.DELETED); } @Test diff --git a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java index 31349ebec4..982fc3483b 100644 --- a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java @@ -30,7 +30,6 @@ import org.thingsboard.server.common.data.TbResourceInfo; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TenantProfile; import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; @@ -149,7 +148,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { } @Test - public void sumDataSizeByTenantId() throws ThingsboardException { + public void sumDataSizeByTenantId() throws Exception { Assert.assertEquals(0, resourceService.sumDataSizeByTenantId(tenantId)); createResource("test", DEFAULT_FILE_NAME); @@ -165,14 +164,14 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { Assert.assertEquals(maxSumDataSize, resourceService.sumDataSizeByTenantId(tenantId)); } - private TbResource createResource(String title, String filename) throws ThingsboardException { + private TbResource createResource(String title, String filename) throws Exception { TbResource resource = new TbResource(); resource.setTenantId(tenantId); resource.setTitle(title); resource.setResourceType(ResourceType.JKS); resource.setFileName(filename); resource.setData("1"); - return resourceService.saveResourceInternal(resource); + return resourceService.save(resource); } @Test @@ -184,7 +183,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); Assert.assertNotNull(savedResource); Assert.assertNotNull(savedResource.getId()); @@ -196,7 +195,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { savedResource.setTitle("My new resource"); - resourceService.saveResourceInternal(savedResource); + resourceService.save(savedResource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertEquals(foundResource.getTitle(), savedResource.getTitle()); @@ -211,7 +210,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName("test_model.xml"); resource.setData(Base64.getEncoder().encodeToString(LWM2M_TEST_MODEL.getBytes())); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); Assert.assertNotNull(savedResource); Assert.assertNotNull(savedResource.getId()); @@ -231,7 +230,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); Assert.assertEquals(TenantId.SYS_TENANT_ID, savedResource.getTenantId()); @@ -247,7 +246,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); TbResource resource2 = new TbResource(); resource.setTenantId(tenantId); @@ -257,7 +256,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setData("Test Data"); try { - resourceService.saveResourceInternal(resource2); + resourceService.save(resource2); } finally { resourceService.delete(savedResource, null); } @@ -270,7 +269,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - resourceService.saveResourceInternal(resource); + resourceService.save(resource); } @Test(expected = DataValidationException.class) @@ -281,7 +280,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - resourceService.saveResourceInternal(resource); + resourceService.save(resource); } @Test @@ -291,7 +290,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertNotNull(foundResource); @@ -307,7 +306,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); TbResource foundResource = resourceService.getResource(tenantId, savedResource.getResourceType(), savedResource.getResourceKey()); Assert.assertNotNull(foundResource); @@ -322,7 +321,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResourceInternal(resource); + TbResource savedResource = resourceService.save(resource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertNotNull(foundResource); @@ -348,7 +347,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - resources.add(new TbResourceInfo(resourceService.saveResourceInternal(resource))); + resources.add(new TbResourceInfo(resourceService.save(resource))); } List loadedResources = new ArrayList<>(); @@ -396,7 +395,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResourceInfo tbResourceInfo = new TbResourceInfo(resourceService.saveResourceInternal(resource)); + TbResourceInfo tbResourceInfo = new TbResourceInfo(resourceService.save(resource)); if (i >= 50) { resources.add(tbResourceInfo); } @@ -409,7 +408,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - resources.add(new TbResourceInfo(resourceService.saveResourceInternal(resource))); + resources.add(new TbResourceInfo(resourceService.save(resource))); } List loadedResources = new ArrayList<>();