Browse Source

refactored due to deprecated handleException

pull/6757/head
YevhenBondarenko 4 years ago
parent
commit
1d3d000be2
  1. 36
      application/src/main/java/org/thingsboard/server/controller/AlarmController.java
  2. 131
      application/src/main/java/org/thingsboard/server/controller/AssetController.java
  3. 29
      application/src/main/java/org/thingsboard/server/controller/CustomerController.java
  4. 194
      application/src/main/java/org/thingsboard/server/controller/DashboardController.java
  5. 310
      application/src/main/java/org/thingsboard/server/controller/DeviceController.java
  6. 45
      application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java
  7. 128
      application/src/main/java/org/thingsboard/server/controller/EdgeController.java
  8. 41
      application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java
  9. 141
      application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
  10. 56
      application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java
  11. 65
      application/src/main/java/org/thingsboard/server/controller/QueueController.java
  12. 167
      application/src/main/java/org/thingsboard/server/controller/RuleChainController.java
  13. 29
      application/src/main/java/org/thingsboard/server/controller/TbResourceController.java
  14. 14
      application/src/main/java/org/thingsboard/server/controller/TenantController.java
  15. 34
      application/src/main/java/org/thingsboard/server/controller/UserController.java
  16. 30
      application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java
  17. 6
      application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java
  18. 6
      application/src/main/java/org/thingsboard/server/service/entitiy/AbstractTbEntityService.java
  19. 13
      application/src/main/java/org/thingsboard/server/service/entitiy/alarm/DefaultTbAlarmService.java
  20. 116
      application/src/main/java/org/thingsboard/server/service/entitiy/asset/DefaultTbAssetService.java
  21. 29
      application/src/main/java/org/thingsboard/server/service/entitiy/customer/DefaultTbCustomerService.java
  22. 234
      application/src/main/java/org/thingsboard/server/service/entitiy/dashboard/DefaultTbDashboardService.java
  23. 169
      application/src/main/java/org/thingsboard/server/service/entitiy/device/DefaultTbDeviceService.java
  24. 4
      application/src/main/java/org/thingsboard/server/service/entitiy/device/TbDeviceService.java
  25. 83
      application/src/main/java/org/thingsboard/server/service/entitiy/device/profile/DefaultTbDeviceProfileService.java
  26. 96
      application/src/main/java/org/thingsboard/server/service/entitiy/edge/DefaultTbEdgeService.java
  27. 42
      application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java
  28. 153
      application/src/main/java/org/thingsboard/server/service/entitiy/entityview/DefaultTbEntityViewService.java
  29. 75
      application/src/main/java/org/thingsboard/server/service/entitiy/ota/DefaultTbOtaPackageService.java
  30. 52
      application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultUserService.java
  31. 28
      application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
  32. 235
      application/src/main/java/org/thingsboard/server/service/rule/DefaultTbRuleChainService.java

36
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; 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.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmInfo; import org.thingsboard.server.common.data.alarm.AlarmInfo;
import org.thingsboard.server.common.data.alarm.AlarmQuery; import org.thingsboard.server.common.data.alarm.AlarmQuery;
import org.thingsboard.server.common.data.alarm.AlarmSearchStatus; import org.thingsboard.server.common.data.alarm.AlarmSearchStatus;
import org.thingsboard.server.common.data.alarm.AlarmSeverity; import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.alarm.AlarmStatus; 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.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.AlarmId; 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 { public Alarm saveAlarm(@ApiParam(value = "A JSON value representing the alarm.") @RequestBody Alarm alarm) throws ThingsboardException {
alarm.setTenantId(getTenantId()); alarm.setTenantId(getTenantId());
checkEntity(alarm.getId(), alarm, Resource.ALARM); checkEntity(alarm.getId(), alarm, Resource.ALARM);
try { return tbAlarmService.save(alarm, getCurrentUser());
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)", @ApiOperation(value = "Delete Alarm (deleteAlarm)",
@ -152,13 +144,9 @@ public class AlarmController extends BaseController {
@ResponseBody @ResponseBody
public Boolean deleteAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException { public Boolean deleteAlarm(@ApiParam(value = ALARM_ID_PARAM_DESCRIPTION) @PathVariable(ALARM_ID) String strAlarmId) throws ThingsboardException {
checkParameter(ALARM_ID, strAlarmId); checkParameter(ALARM_ID, strAlarmId);
try { AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);
Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); return tbAlarmService.delete(alarm, getCurrentUser());
return tbAlarmService.delete(alarm, getCurrentUser());
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Acknowledge Alarm (ackAlarm)", @ApiOperation(value = "Acknowledge Alarm (ackAlarm)",
@ -168,15 +156,11 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST) @RequestMapping(value = "/alarm/{alarmId}/ack", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK) @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); checkParameter(ALARM_ID, strAlarmId);
AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);
try { tbAlarmService.ack(alarm, getCurrentUser()).get();
tbAlarmService.ack(alarm, getCurrentUser()).get();
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Clear Alarm (clearAlarm)", @ApiOperation(value = "Clear Alarm (clearAlarm)",
@ -186,15 +170,11 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST) @RequestMapping(value = "/alarm/{alarmId}/clear", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK) @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); checkParameter(ALARM_ID, strAlarmId);
AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
Alarm alarm = checkAlarmId(alarmId, Operation.WRITE); Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);
try { tbAlarmService.clear(alarm, getCurrentUser()).get();
tbAlarmService.clear(alarm, getCurrentUser()).get();
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Get Alarms (getAlarms)", @ApiOperation(value = "Get Alarms (getAlarms)",

131
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.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntitySubtype; 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.Asset;
import org.thingsboard.server.common.data.asset.AssetInfo; import org.thingsboard.server.common.data.asset.AssetInfo;
import org.thingsboard.server.common.data.asset.AssetSearchQuery; 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.edge.Edge;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
@ -146,18 +144,12 @@ public class AssetController extends BaseController {
@RequestMapping(value = "/asset", method = RequestMethod.POST) @RequestMapping(value = "/asset", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Asset saveAsset(@ApiParam(value = "A JSON value representing the asset.") @RequestBody Asset asset) throws ThingsboardException { public Asset saveAsset(@ApiParam(value = "A JSON value representing the asset.") @RequestBody Asset asset) throws ThingsboardException {
try { if (TB_SERVICE_QUEUE.equals(asset.getType())) {
if (TB_SERVICE_QUEUE.equals(asset.getType())) { throw new ThingsboardException("Unable to save asset with type " + TB_SERVICE_QUEUE, ThingsboardErrorCode.BAD_REQUEST_PARAMS);
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(getTenantId());
checkEntity(asset.getId(), asset, Resource.ASSET);
return tbAssetService.save(asset, getCurrentUser());
} }
@ApiOperation(value = "Delete asset (deleteAsset)", @ApiOperation(value = "Delete asset (deleteAsset)",
@ -165,17 +157,11 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE) @RequestMapping(value = "/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK) @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); checkParameter(ASSET_ID, strAssetId);
try { AssetId assetId = new AssetId(toUUID(strAssetId));
AssetId assetId = new AssetId(toUUID(strAssetId)); Asset asset = checkAssetId(assetId, Operation.DELETE);
Asset asset = checkAssetId(assetId, Operation.DELETE); tbAssetService.delete(asset, getCurrentUser()).get();
tbAssetService.delete(asset, getCurrentUser()).get();
} catch (Exception e) {
notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.ASSET), ActionType.DELETED,
getCurrentUser(), e, strAssetId);
throw handleException(e);
}
} }
@ApiOperation(value = "Assign asset to customer (assignAssetToCustomer)", @ApiOperation(value = "Assign asset to customer (assignAssetToCustomer)",
@ -185,21 +171,13 @@ public class AssetController extends BaseController {
@ResponseBody @ResponseBody
public Asset assignAssetToCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) @PathVariable("customerId") String strCustomerId, 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 { @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
try { checkParameter("customerId", strCustomerId);
checkParameter("customerId", strCustomerId); checkParameter(ASSET_ID, strAssetId);
checkParameter(ASSET_ID, strAssetId); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); Customer customer = checkCustomerId(customerId, Operation.READ);
Customer customer = checkCustomerId(customerId, Operation.READ); AssetId assetId = new AssetId(toUUID(strAssetId));
AssetId assetId = new AssetId(toUUID(strAssetId)); checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER);
checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); return tbAssetService.assignAssetToCustomer(getTenantId(), assetId, customer, getCurrentUser());
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)", @ApiOperation(value = "Unassign asset from customer (unassignAssetFromCustomer)",
@ -208,21 +186,14 @@ public class AssetController extends BaseController {
@RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE) @RequestMapping(value = "/customer/asset/{assetId}", method = RequestMethod.DELETE)
@ResponseBody @ResponseBody
public Asset unassignAssetFromCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { public Asset unassignAssetFromCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
try { checkParameter(ASSET_ID, strAssetId);
checkParameter(ASSET_ID, strAssetId); AssetId assetId = new AssetId(toUUID(strAssetId));
AssetId assetId = new AssetId(toUUID(strAssetId)); Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER);
Asset asset = checkAssetId(assetId, Operation.UNASSIGN_FROM_CUSTOMER); if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
if (asset.getCustomerId() == null || asset.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { throw new IncorrectParameterException("Asset isn't assigned to any customer!");
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)", @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) @RequestMapping(value = "/customer/public/asset/{assetId}", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Asset assignAssetToPublicCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException { public Asset assignAssetToPublicCustomer(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
try { checkParameter(ASSET_ID, strAssetId);
checkParameter(ASSET_ID, strAssetId); AssetId assetId = new AssetId(toUUID(strAssetId));
AssetId assetId = new AssetId(toUUID(strAssetId)); checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER);
checkAssetId(assetId, Operation.ASSIGN_TO_CUSTOMER); return tbAssetService.assignAssetToPublicCustomer(getTenantId(), assetId, getCurrentUser());
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)", @ApiOperation(value = "Get Tenant Assets (getTenantAssets)",
@ -485,23 +450,16 @@ public class AssetController extends BaseController {
@ResponseBody @ResponseBody
public Asset assignAssetToEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, 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 { @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(ASSET_ID, strAssetId);
checkParameter(ASSET_ID, strAssetId);
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ); Edge edge = checkEdgeId(edgeId, Operation.READ);
AssetId assetId = new AssetId(toUUID(strAssetId)); AssetId assetId = new AssetId(toUUID(strAssetId));
checkAssetId(assetId, Operation.READ); 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)", @ApiOperation(value = "Unassign asset from edge (unassignAssetFromEdge)",
@ -516,22 +474,15 @@ public class AssetController extends BaseController {
@ResponseBody @ResponseBody
public Asset unassignAssetFromEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION) @PathVariable(EDGE_ID) String strEdgeId, 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 { @ApiParam(value = ASSET_ID_PARAM_DESCRIPTION) @PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(ASSET_ID, strAssetId);
checkParameter(ASSET_ID, strAssetId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.READ);
Edge edge = checkEdgeId(edgeId, Operation.READ);
AssetId assetId = new AssetId(toUUID(strAssetId)); AssetId assetId = new AssetId(toUUID(strAssetId));
Asset asset = checkAssetId(assetId, Operation.READ); 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)", @ApiOperation(value = "Get assets assigned to edge (getEdgeAssets)",

29
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.Customer; 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.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
@ -145,16 +143,9 @@ public class CustomerController extends BaseController {
@RequestMapping(value = "/customer", method = RequestMethod.POST) @RequestMapping(value = "/customer", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Customer saveCustomer(@ApiParam(value = "A JSON value representing the customer.") @RequestBody Customer customer) throws ThingsboardException { public Customer saveCustomer(@ApiParam(value = "A JSON value representing the customer.") @RequestBody Customer customer) throws ThingsboardException {
try { customer.setTenantId(getTenantId());
customer.setTenantId(getTenantId()); checkEntity(customer.getId(), customer, Resource.CUSTOMER);
checkEntity(customer.getId(), customer, Resource.CUSTOMER); return tbCustomerService.save(customer, getCurrentUser());
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)", @ApiOperation(value = "Delete Customer (deleteCustomer)",
@ -166,16 +157,10 @@ public class CustomerController extends BaseController {
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public void deleteCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION) public void deleteCustomer(@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException { @PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
try { checkParameter(CUSTOMER_ID, strCustomerId);
checkParameter(CUSTOMER_ID, strCustomerId); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); Customer customer = checkCustomerId(customerId, Operation.DELETE);
Customer customer = checkCustomerId(customerId, Operation.DELETE); tbCustomerService.delete(customer, getCurrentUser());
tbCustomerService.delete(customer, getCurrentUser());
} catch (Exception e) {
notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.CUSTOMER), ActionType.DELETED,
getCurrentUser(), e, strCustomerId);
throw handleException(e);
}
} }
@ApiOperation(value = "Get Tenant Customers (getCustomers)", @ApiOperation(value = "Get Tenant Customers (getCustomers)",

194
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.Customer;
import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DashboardInfo; 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.HomeDashboard;
import org.thingsboard.server.common.data.HomeDashboardInfo; import org.thingsboard.server.common.data.HomeDashboardInfo;
import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User; 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.Edge;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
@ -183,16 +181,9 @@ public class DashboardController extends BaseController {
public Dashboard saveDashboard( public Dashboard saveDashboard(
@ApiParam(value = "A JSON value representing the dashboard.") @ApiParam(value = "A JSON value representing the dashboard.")
@RequestBody Dashboard dashboard) throws ThingsboardException { @RequestBody Dashboard dashboard) throws ThingsboardException {
try { dashboard.setTenantId(getTenantId());
dashboard.setTenantId(getTenantId()); checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD);
checkEntity(dashboard.getId(), dashboard, Resource.DASHBOARD); return tbDashboardService.save(dashboard, getCurrentUser());
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)", @ApiOperation(value = "Delete the Dashboard (deleteDashboard)",
@ -203,16 +194,10 @@ public class DashboardController extends BaseController {
public void deleteDashboard( public void deleteDashboard(
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.DELETE); tbDashboardService.delete(dashboard, getCurrentUser());
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)", @ApiOperation(value = "Assign the Dashboard (assignDashboardToCustomer)",
@ -227,22 +212,15 @@ public class DashboardController extends BaseController {
@PathVariable(CUSTOMER_ID) String strCustomerId, @PathVariable(CUSTOMER_ID) String strCustomerId,
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter(CUSTOMER_ID, strCustomerId);
checkParameter(CUSTOMER_ID, strCustomerId); checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId);
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
Customer customer = checkCustomerId(customerId, Operation.READ); Customer customer = checkCustomerId(customerId, Operation.READ);
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER);
return tbDashboardService.assignDashboardToCustomer(dashboard, customer, getCurrentUser()); 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)", @ApiOperation(value = "Unassign the Dashboard (unassignDashboardFromCustomer)",
@ -257,20 +235,13 @@ public class DashboardController extends BaseController {
@PathVariable(CUSTOMER_ID) String strCustomerId, @PathVariable(CUSTOMER_ID) String strCustomerId,
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter("customerId", strCustomerId);
checkParameter("customerId", strCustomerId); checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); Customer customer = checkCustomerId(customerId, Operation.READ);
Customer customer = checkCustomerId(customerId, Operation.READ); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); return tbDashboardService.unassignDashboardFromCustomer(dashboard, customer, getCurrentUser());
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)", @ApiOperation(value = "Update the Dashboard Customers (updateDashboardCustomers)",
@ -287,18 +258,11 @@ public class DashboardController extends BaseController {
@PathVariable(DASHBOARD_ID) String strDashboardId, @PathVariable(DASHBOARD_ID) String strDashboardId,
@ApiParam(value = "JSON array with the list of customer ids, or empty to remove all customers") @ApiParam(value = "JSON array with the list of customer ids, or empty to remove all customers")
@RequestBody(required = false) String[] strCustomerIds) throws ThingsboardException { @RequestBody(required = false) String[] strCustomerIds) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard);
Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard); return tbDashboardService.updateDashboardCustomers(dashboard, customerIds, getCurrentUser());
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)", @ApiOperation(value = "Adds the Dashboard Customers (addDashboardCustomers)",
@ -314,18 +278,11 @@ public class DashboardController extends BaseController {
@PathVariable(DASHBOARD_ID) String strDashboardId, @PathVariable(DASHBOARD_ID) String strDashboardId,
@ApiParam(value = "JSON array with the list of customer ids") @ApiParam(value = "JSON array with the list of customer ids")
@RequestBody String[] strCustomerIds) throws ThingsboardException { @RequestBody String[] strCustomerIds) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard);
Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard); return tbDashboardService.addDashboardCustomers(dashboard, customerIds, getCurrentUser());
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)", @ApiOperation(value = "Remove the Dashboard Customers (removeDashboardCustomers)",
@ -341,18 +298,11 @@ public class DashboardController extends BaseController {
@PathVariable(DASHBOARD_ID) String strDashboardId, @PathVariable(DASHBOARD_ID) String strDashboardId,
@ApiParam(value = "JSON array with the list of customer ids") @ApiParam(value = "JSON array with the list of customer ids")
@RequestBody String[] strCustomerIds) throws ThingsboardException { @RequestBody String[] strCustomerIds) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard);
Set<CustomerId> customerIds = customerIdFromStr(strCustomerIds, dashboard); return tbDashboardService.removeDashboardCustomers(dashboard, customerIds, getCurrentUser());
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)", @ApiOperation(value = "Assign the Dashboard to Public Customer (assignDashboardToPublicCustomer)",
@ -369,17 +319,10 @@ public class DashboardController extends BaseController {
public Dashboard assignDashboardToPublicCustomer( public Dashboard assignDashboardToPublicCustomer(
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.ASSIGN_TO_CUSTOMER); return tbDashboardService.assignDashboardToPublicCustomer(dashboard, getCurrentUser());
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)", @ApiOperation(value = "Unassign the Dashboard from Public Customer (unassignDashboardFromPublicCustomer)",
@ -392,17 +335,10 @@ public class DashboardController extends BaseController {
public Dashboard unassignDashboardFromPublicCustomer( public Dashboard unassignDashboardFromPublicCustomer(
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION) @ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER);
Dashboard dashboard = checkDashboardId(dashboardId, Operation.UNASSIGN_FROM_CUSTOMER); return tbDashboardService.unassignDashboardFromPublicCustomer(dashboard, getCurrentUser());
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)", @ApiOperation(value = "Get Tenant Dashboards by System Administrator (getTenantDashboards)",
@ -687,22 +623,15 @@ public class DashboardController extends BaseController {
@ResponseBody @ResponseBody
public Dashboard assignDashboardToEdge(@PathVariable("edgeId") String strEdgeId, public Dashboard assignDashboardToEdge(@PathVariable("edgeId") String strEdgeId,
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter("edgeId", strEdgeId);
checkParameter("edgeId", strEdgeId); checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId);
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ); Edge edge = checkEdgeId(edgeId, Operation.READ);
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
checkDashboardId(dashboardId, Operation.READ); checkDashboardId(dashboardId, Operation.READ);
return tbDashboardService.asignDashboardToEdge(getTenantId(), dashboardId, edge, getCurrentUser()); 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)", @ApiOperation(value = "Unassign dashboard from edge (unassignDashboardFromEdge)",
@ -718,23 +647,16 @@ public class DashboardController extends BaseController {
@ResponseBody @ResponseBody
public Dashboard unassignDashboardFromEdge(@PathVariable("edgeId") String strEdgeId, public Dashboard unassignDashboardFromEdge(@PathVariable("edgeId") String strEdgeId,
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException { @PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(DASHBOARD_ID, strDashboardId);
checkParameter(DASHBOARD_ID, strDashboardId);
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ); Edge edge = checkEdgeId(edgeId, Operation.READ);
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
Dashboard dashboard = checkDashboardId(dashboardId, Operation.READ); 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)", @ApiOperation(value = "Get Edge Dashboards (getEdgeDashboards)",

310
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.Device;
import org.thingsboard.server.common.data.DeviceInfo; import org.thingsboard.server.common.data.DeviceInfo;
import org.thingsboard.server.common.data.EntitySubtype; 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.SaveDeviceWithCredentialsRequest;
import org.thingsboard.server.common.data.Tenant; 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.device.DeviceSearchQuery;
import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; 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, 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. " + @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 { "If omitted, access token will be auto-generated.") @RequestParam(name = "accessToken", required = false) String accessToken) throws ThingsboardException {
try { device.setTenantId(getCurrentUser().getTenantId());
device.setTenantId(getCurrentUser().getTenantId()); Device oldDevice = null;
Device oldDevice = null; if (device.getId() != null) {
if (device.getId() != null) { oldDevice = checkDeviceId(device.getId(), Operation.WRITE);
oldDevice = checkDeviceId(device.getId(), Operation.WRITE); } else {
} else { checkEntity(null, device, Resource.DEVICE);
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(device, oldDevice, accessToken, getCurrentUser());
} }
@ApiOperation(value = "Create Device (saveDevice) with credentials ", @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.") public Device saveDeviceWithCredentials(@ApiParam(value = "The JSON object with device and credentials. See method description above for example.")
@RequestBody SaveDeviceWithCredentialsRequest deviceAndCredentials) throws ThingsboardException { @RequestBody SaveDeviceWithCredentialsRequest deviceAndCredentials) throws ThingsboardException {
Device device = checkNotNull(deviceAndCredentials.getDevice()); Device device = checkNotNull(deviceAndCredentials.getDevice());
try { DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials());
DeviceCredentials credentials = checkNotNull(deviceAndCredentials.getCredentials()); device.setTenantId(getCurrentUser().getTenantId());
device.setTenantId(getCurrentUser().getTenantId()); checkEntity(device.getId(), device, Resource.DEVICE);
checkEntity(device.getId(), device, Resource.DEVICE); return tbDeviceService.saveDeviceWithCredentials(device, credentials, getCurrentUser());
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)", @ApiOperation(value = "Delete device (deleteDevice)",
@ -215,17 +200,11 @@ public class DeviceController extends BaseController {
@RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE) @RequestMapping(value = "/device/{deviceId}", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public void deleteDevice(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) public void deleteDevice(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws Exception {
try { checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); Device device = checkDeviceId(deviceId, Operation.DELETE);
Device device = checkDeviceId(deviceId, Operation.DELETE); tbDeviceService.delete(device, getCurrentUser()).get();
tbDeviceService.delete(device, getCurrentUser()).get();
} catch (Exception e) {
notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.DEVICE), ActionType.DELETED,
getCurrentUser(), e, strDeviceId);
throw handleException(e);
}
} }
@ApiOperation(value = "Assign device to customer (assignDeviceToCustomer)", @ApiOperation(value = "Assign device to customer (assignDeviceToCustomer)",
@ -237,20 +216,13 @@ public class DeviceController extends BaseController {
@PathVariable("customerId") String strCustomerId, @PathVariable("customerId") String strCustomerId,
@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter("customerId", strCustomerId);
checkParameter("customerId", strCustomerId); checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); Customer customer = checkCustomerId(customerId, Operation.READ);
Customer customer = checkCustomerId(customerId, Operation.READ); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER);
checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); return tbDeviceService.assignDeviceToCustomer(getTenantId(), deviceId, customer, getCurrentUser());
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)", @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) public Device unassignDeviceFromCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
checkParameter(DEVICE_ID, strDeviceId); checkParameter(DEVICE_ID, strDeviceId);
try { DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); Device device = checkDeviceId(deviceId, Operation.UNASSIGN_FROM_CUSTOMER);
Device device = checkDeviceId(deviceId, Operation.UNASSIGN_FROM_CUSTOMER); if (device.getCustomerId() == null || device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
if (device.getCustomerId() == null || device.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { throw new IncorrectParameterException("Device isn't assigned to any customer!");
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()); 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);
}
} }
@ApiOperation(value = "Make device publicly available (assignDeviceToPublicCustomer)", @ApiOperation(value = "Make device publicly available (assignDeviceToPublicCustomer)",
@ -288,17 +253,10 @@ public class DeviceController extends BaseController {
@ResponseBody @ResponseBody
public Device assignDeviceToPublicCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) public Device assignDeviceToPublicCustomer(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER);
checkDeviceId(deviceId, Operation.ASSIGN_TO_CUSTOMER); return tbDeviceService.assignDeviceToPublicCustomer(getTenantId(), deviceId, getCurrentUser());
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)", @ApiOperation(value = "Get Device Credentials (getDeviceCredentialsByDeviceId)",
@ -308,16 +266,10 @@ public class DeviceController extends BaseController {
@ResponseBody @ResponseBody
public DeviceCredentials getDeviceCredentialsByDeviceId(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) public DeviceCredentials getDeviceCredentialsByDeviceId(@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS);
Device device = checkDeviceId(deviceId, Operation.READ_CREDENTIALS); return tbDeviceService.getDeviceCredentialsByDeviceId(device, getCurrentUser());
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. " + @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( public DeviceCredentials updateDeviceCredentials(
@ApiParam(value = "A JSON value representing the device credentials.") @ApiParam(value = "A JSON value representing the device credentials.")
@RequestBody DeviceCredentials deviceCredentials) throws ThingsboardException { @RequestBody DeviceCredentials deviceCredentials) throws ThingsboardException {
try { checkNotNull(deviceCredentials);
checkNotNull(deviceCredentials); Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS);
Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS); return tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser());
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)", @ApiOperation(value = "Get Tenant Devices (getTenantDevices)",
@ -597,47 +543,43 @@ public class DeviceController extends BaseController {
@PathVariable(DEVICE_NAME) String deviceName, @PathVariable(DEVICE_NAME) String deviceName,
@ApiParam(value = "Claiming request which can optionally contain secret key") @ApiParam(value = "Claiming request which can optionally contain secret key")
@RequestBody(required = false) ClaimRequest claimRequest) throws ThingsboardException { @RequestBody(required = false) ClaimRequest claimRequest) throws ThingsboardException {
try { checkParameter(DEVICE_NAME, deviceName);
checkParameter(DEVICE_NAME, deviceName); final DeferredResult<ResponseEntity> deferredResult = new DeferredResult<>();
final DeferredResult<ResponseEntity> deferredResult = new DeferredResult<>();
SecurityUser user = getCurrentUser();
TenantId tenantId = user.getTenantId();
CustomerId customerId = user.getCustomerId();
Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, TenantId tenantId = user.getTenantId();
device.getId(), device); CustomerId customerId = user.getCustomerId();
String secretKey = getSecretKey(claimRequest);
Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName));
ListenableFuture<ClaimResult> future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user); accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES,
device.getId(), device);
Futures.addCallback(future, new FutureCallback<>() { String secretKey = getSecretKey(claimRequest);
@Override
public void onSuccess(@Nullable ClaimResult result) { ListenableFuture<ClaimResult> future = tbDeviceService.claimDevice(tenantId, device, customerId, secretKey, user);
HttpStatus status;
if (result != null) { Futures.addCallback(future, new FutureCallback<>() {
if (result.getResponse().equals(ClaimResponse.SUCCESS)) { @Override
status = HttpStatus.OK; public void onSuccess(@Nullable ClaimResult result) {
deferredResult.setResult(new ResponseEntity<>(result, status)); HttpStatus status;
} else { if (result != null) {
status = HttpStatus.BAD_REQUEST; if (result.getResponse().equals(ClaimResponse.SUCCESS)) {
deferredResult.setResult(new ResponseEntity<>(result.getResponse(), status)); status = HttpStatus.OK;
} deferredResult.setResult(new ResponseEntity<>(result, status));
} else { } 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 @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
deferredResult.setErrorResult(t); deferredResult.setErrorResult(t);
} }
}, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor());
return deferredResult; return deferredResult;
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Reclaim device (reClaimDevice)", @ApiOperation(value = "Reclaim device (reClaimDevice)",
@ -649,32 +591,28 @@ public class DeviceController extends BaseController {
public DeferredResult<ResponseEntity> reClaimDevice(@ApiParam(value = "Unique name of the device which is going to be reclaimed") public DeferredResult<ResponseEntity> reClaimDevice(@ApiParam(value = "Unique name of the device which is going to be reclaimed")
@PathVariable(DEVICE_NAME) String deviceName) throws ThingsboardException { @PathVariable(DEVICE_NAME) String deviceName) throws ThingsboardException {
checkParameter(DEVICE_NAME, deviceName); checkParameter(DEVICE_NAME, deviceName);
try { final DeferredResult<ResponseEntity> deferredResult = new DeferredResult<>();
final DeferredResult<ResponseEntity> deferredResult = new DeferredResult<>();
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
TenantId tenantId = user.getTenantId(); TenantId tenantId = user.getTenantId();
Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName)); Device device = checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName));
accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES, accessControlService.checkPermission(user, Resource.DEVICE, Operation.CLAIM_DEVICES,
device.getId(), device); device.getId(), device);
ListenableFuture<ReclaimResult> result = tbDeviceService.reclaimDevice(tenantId, device, user); ListenableFuture<ReclaimResult> result = tbDeviceService.reclaimDevice(tenantId, device, user);
Futures.addCallback(result, new FutureCallback<>() { Futures.addCallback(result, new FutureCallback<>() {
@Override @Override
public void onSuccess(ReclaimResult reclaimResult) { public void onSuccess(ReclaimResult reclaimResult) {
deferredResult.setResult(new ResponseEntity(HttpStatus.OK)); deferredResult.setResult(new ResponseEntity(HttpStatus.OK));
} }
@Override @Override
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
deferredResult.setErrorResult(t); deferredResult.setErrorResult(t);
} }
}, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor());
return deferredResult; return deferredResult;
} catch (Exception e) {
throw handleException(e);
}
} }
private String getSecretKey(ClaimRequest claimRequest) { private String getSecretKey(ClaimRequest claimRequest) {
@ -694,23 +632,17 @@ public class DeviceController extends BaseController {
@PathVariable(TENANT_ID) String strTenantId, @PathVariable(TENANT_ID) String strTenantId,
@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter(TENANT_ID, strTenantId);
checkParameter(TENANT_ID, strTenantId); checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT);
Device device = checkDeviceId(deviceId, Operation.ASSIGN_TO_TENANT);
TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId));
TenantId newTenantId = TenantId.fromUUID(toUUID(strTenantId)); Tenant newTenant = tenantService.findTenantById(newTenantId);
Tenant newTenant = tenantService.findTenantById(newTenantId); if (newTenant == null) {
if (newTenant == null) { throw new ThingsboardException("Could not find the specified Tenant!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
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)", @ApiOperation(value = "Assign device to edge (assignDeviceToEdge)",
@ -727,21 +659,15 @@ public class DeviceController extends BaseController {
@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.READ);
Edge edge = checkEdgeId(edgeId, Operation.READ);
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
checkDeviceId(deviceId, Operation.READ); 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)", @ApiOperation(value = "Unassign device from edge (unassignDeviceFromEdge)",
@ -758,20 +684,14 @@ public class DeviceController extends BaseController {
@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException { @PathVariable(DEVICE_ID) String strDeviceId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(DEVICE_ID, strDeviceId);
checkParameter(DEVICE_ID, strDeviceId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.READ);
Edge edge = checkEdgeId(edgeId, Operation.READ);
DeviceId deviceId = new DeviceId(toUUID(strDeviceId)); DeviceId deviceId = new DeviceId(toUUID(strDeviceId));
Device device = checkDeviceId(deviceId, Operation.READ); Device device = checkDeviceId(deviceId, Operation.READ);
return tbDeviceService.unassignDeviceFromEdge(device, edge, getCurrentUser()); 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)", @ApiOperation(value = "Get devices assigned to edge (getEdgeDevices)",

45
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.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.DeviceProfileInfo; 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.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
@ -202,16 +200,9 @@ public class DeviceProfileController extends BaseController {
public DeviceProfile saveDeviceProfile( public DeviceProfile saveDeviceProfile(
@ApiParam(value = "A JSON value representing the device profile.") @ApiParam(value = "A JSON value representing the device profile.")
@RequestBody DeviceProfile deviceProfile) throws ThingsboardException { @RequestBody DeviceProfile deviceProfile) throws ThingsboardException {
try { deviceProfile.setTenantId(getTenantId());
deviceProfile.setTenantId(getTenantId()); checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE);
checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE); return tbDeviceProfileService.save(deviceProfile, getCurrentUser());
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)", @ApiOperation(value = "Delete device profile (deleteDeviceProfile)",
@ -224,16 +215,10 @@ public class DeviceProfileController extends BaseController {
public void deleteDeviceProfile( public void deleteDeviceProfile(
@ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException {
try { checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId);
checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE);
DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE); tbDeviceProfileService.delete(deviceProfile, getCurrentUser());
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)", @ApiOperation(value = "Make Device Profile Default (setDefaultDeviceProfile)",
@ -245,17 +230,11 @@ public class DeviceProfileController extends BaseController {
public DeviceProfile setDefaultDeviceProfile( public DeviceProfile setDefaultDeviceProfile(
@ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION) @ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException { @PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException {
try { checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId);
checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId); DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId)); DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE);
DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.WRITE); DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId());
DeviceProfile previousDefaultDeviceProfile = deviceProfileService.findDefaultDeviceProfile(getTenantId()); return tbDeviceProfileService.setDefaultDeviceProfile(deviceProfile, previousDefaultDeviceProfile, getCurrentUser());
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)", @ApiOperation(value = "Get Device Profiles (getDeviceProfiles)",

128
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.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntitySubtype; 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.Edge;
import org.thingsboard.server.common.data.edge.EdgeInfo; import org.thingsboard.server.common.data.edge.EdgeInfo;
import org.thingsboard.server.common.data.edge.EdgeSearchQuery; import org.thingsboard.server.common.data.edge.EdgeSearchQuery;
@ -149,30 +147,24 @@ public class EdgeController extends BaseController {
@RequestMapping(value = "/edge", method = RequestMethod.POST) @RequestMapping(value = "/edge", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Edge saveEdge(@ApiParam(value = "A JSON value representing the edge.", required = true) 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(); TenantId tenantId = getTenantId();
try { edge.setTenantId(tenantId);
edge.setTenantId(tenantId); boolean created = edge.getId() == null;
boolean created = edge.getId() == null;
RuleChain edgeTemplateRootRuleChain = null;
RuleChain edgeTemplateRootRuleChain = null; if (created) {
if (created) { edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId);
edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(tenantId); if (edgeTemplateRootRuleChain == null) {
if (edgeTemplateRootRuleChain == null) { throw new DataValidationException("Root edge rule chain is not available!");
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)", @ApiOperation(value = "Delete edge (deleteEdge)",
@ -182,16 +174,10 @@ public class EdgeController extends BaseController {
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public void deleteEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) public void deleteEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.DELETE);
Edge edge = checkEdgeId(edgeId, Operation.DELETE); tbEdgeService.delete(edge, getCurrentUser());
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)", @ApiOperation(value = "Get Tenant Edges (getEdges)",
@ -229,19 +215,13 @@ public class EdgeController extends BaseController {
@PathVariable("customerId") String strCustomerId, @PathVariable("customerId") String strCustomerId,
@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) @ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
try { checkParameter("customerId", strCustomerId);
checkParameter("customerId", strCustomerId); checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); Customer customer = checkCustomerId(customerId, Operation.READ);
Customer customer = checkCustomerId(customerId, Operation.READ); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER);
checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); return tbEdgeService.assignEdgeToCustomer(getTenantId(), edgeId, customer, getCurrentUser());
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)", @ApiOperation(value = "Unassign edge from customer (unassignEdgeFromCustomer)",
@ -252,21 +232,15 @@ public class EdgeController extends BaseController {
@ResponseBody @ResponseBody
public Edge unassignEdgeFromCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) public Edge unassignEdgeFromCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER);
Edge edge = checkEdgeId(edgeId, Operation.UNASSIGN_FROM_CUSTOMER); if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
if (edge.getCustomerId() == null || edge.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { throw new IncorrectParameterException("Edge isn't assigned to any customer!");
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);
} }
Customer customer = checkCustomerId(edge.getCustomerId(), Operation.READ);
return tbEdgeService.unassignEdgeFromCustomer(edge, customer, getCurrentUser());
} }
@ApiOperation(value = "Make edge publicly available (assignEdgeToPublicCustomer)", @ApiOperation(value = "Make edge publicly available (assignEdgeToPublicCustomer)",
@ -279,16 +253,10 @@ public class EdgeController extends BaseController {
@ResponseBody @ResponseBody
public Edge assignEdgeToPublicCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true) public Edge assignEdgeToPublicCustomer(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException { @PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER);
checkEdgeId(edgeId, Operation.ASSIGN_TO_CUSTOMER); return tbEdgeService.assignEdgeToPublicCustomer(getTenantId(), edgeId, getCurrentUser());
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)", @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) public Edge setEdgeRootRuleChain(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId, @PathVariable(EDGE_ID) String strEdgeId,
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION, required = true) @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("ruleChainId") String strRuleChainId) throws ThingsboardException { @PathVariable("ruleChainId") String strRuleChainId) throws Exception {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter("ruleChainId", strRuleChainId);
checkParameter("ruleChainId", strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); checkRuleChain(ruleChainId, Operation.WRITE);
checkRuleChain(ruleChainId, Operation.WRITE); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.WRITE);
Edge edge = checkEdgeId(edgeId, Operation.WRITE); accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge);
accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, Operation.WRITE, edge.getId(), edge); return tbEdgeService.setEdgeRootRuleChain(edge, ruleChainId, getCurrentUser());
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)", @ApiOperation(value = "Get Customer Edges (getCustomerEdges)",

41
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.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; 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.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.EntityIdFactory; import org.thingsboard.server.common.data.id.EntityIdFactory;
@ -80,22 +79,14 @@ public class EntityRelationController extends BaseController {
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public void saveRelation(@ApiParam(value = "A JSON value representing the relation.", required = true) public void saveRelation(@ApiParam(value = "A JSON value representing the relation.", required = true)
@RequestBody EntityRelation relation) throws ThingsboardException { @RequestBody EntityRelation relation) throws ThingsboardException {
try { checkNotNull(relation);
checkNotNull(relation); checkEntityId(relation.getFrom(), Operation.WRITE);
checkEntityId(relation.getFrom(), Operation.WRITE); checkEntityId(relation.getTo(), Operation.WRITE);
checkEntityId(relation.getTo(), Operation.WRITE); if (relation.getTypeGroup() == null) {
if (relation.getTypeGroup() == null) { relation.setTypeGroup(RelationTypeGroup.COMMON);
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);
} }
tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser());
} }
@ApiOperation(value = "Delete Relation (deleteRelation)", @ApiOperation(value = "Delete Relation (deleteRelation)",
@ -120,15 +111,7 @@ public class EntityRelationController extends BaseController {
checkEntityId(toId, Operation.WRITE); checkEntityId(toId, Operation.WRITE);
RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON); RelationTypeGroup relationTypeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup); EntityRelation relation = new EntityRelation(fromId, toId, strRelationType, relationTypeGroup);
try { tbEntityRelationService.delete(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser());
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)", @ApiOperation(value = "Delete Relations (deleteRelations)",
@ -143,13 +126,7 @@ public class EntityRelationController extends BaseController {
checkParameter("entityType", strType); checkParameter("entityType", strType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId); EntityId entityId = EntityIdFactory.getByTypeAndId(strType, strId);
checkEntityId(entityId, Operation.WRITE); checkEntityId(entityId, Operation.WRITE);
try { tbEntityRelationService.deleteRelations(getTenantId(), getCurrentUser().getCustomerId(), entityId, getCurrentUser());
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)", @ApiOperation(value = "Get Relation (getRelation)",

141
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.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntitySubtype; 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.EntityView;
import org.thingsboard.server.common.data.EntityViewInfo; 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.edge.Edge;
import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery; import org.thingsboard.server.common.data.entityview.EntityViewSearchQuery;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
@ -142,22 +140,15 @@ public class EntityViewController extends BaseController {
public EntityView saveEntityView( public EntityView saveEntityView(
@ApiParam(value = "A JSON object representing the entity view.") @ApiParam(value = "A JSON object representing the entity view.")
@RequestBody EntityView entityView) throws ThingsboardException { @RequestBody EntityView entityView) throws ThingsboardException {
try { entityView.setTenantId(getCurrentUser().getTenantId());
entityView.setTenantId(getCurrentUser().getTenantId()); EntityView existingEntityView = null;
EntityView existingEntityView = null; if (entityView.getId() == null) {
if (entityView.getId() == null) { accessControlService
accessControlService .checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView);
.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.CREATE, null, entityView); } else {
} else { existingEntityView = checkEntityViewId(entityView.getId(), Operation.WRITE);
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)", @ApiOperation(value = "Delete entity view (deleteEntityView)",
@ -170,15 +161,9 @@ public class EntityViewController extends BaseController {
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
checkParameter(ENTITY_VIEW_ID, strEntityViewId); checkParameter(ENTITY_VIEW_ID, strEntityViewId);
try { EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE);
EntityView entityView = checkEntityViewId(entityViewId, Operation.DELETE); tbEntityViewService.delete(entityView, getCurrentUser());
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)", @ApiOperation(value = "Get Entity View by name (getTenantEntityView)",
@ -208,22 +193,16 @@ public class EntityViewController extends BaseController {
@PathVariable(CUSTOMER_ID) String strCustomerId, @PathVariable(CUSTOMER_ID) String strCustomerId,
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
try { checkParameter(CUSTOMER_ID, strCustomerId);
checkParameter(CUSTOMER_ID, strCustomerId); checkParameter(ENTITY_VIEW_ID, strEntityViewId);
checkParameter(ENTITY_VIEW_ID, strEntityViewId);
CustomerId customerId = new CustomerId(toUUID(strCustomerId)); CustomerId customerId = new CustomerId(toUUID(strCustomerId));
Customer customer = checkCustomerId(customerId, Operation.READ); Customer customer = checkCustomerId(customerId, Operation.READ);
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER); 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)", @ApiOperation(value = "Unassign Entity View from customer (unassignEntityViewFromCustomer)",
@ -234,22 +213,16 @@ public class EntityViewController extends BaseController {
public EntityView unassignEntityViewFromCustomer( public EntityView unassignEntityViewFromCustomer(
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
try { checkParameter(ENTITY_VIEW_ID, strEntityViewId);
checkParameter(ENTITY_VIEW_ID, strEntityViewId); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER);
EntityView entityView = checkEntityViewId(entityViewId, Operation.UNASSIGN_FROM_CUSTOMER); if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) {
if (entityView.getCustomerId() == null || entityView.getCustomerId().getId().equals(ModelConstants.NULL_UUID)) { throw new IncorrectParameterException("Entity View isn't assigned to any customer!");
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)", @ApiOperation(value = "Get Customer Entity Views (getCustomerEntityViews)",
@ -448,20 +421,14 @@ public class EntityViewController extends BaseController {
public EntityView assignEntityViewToPublicCustomer( public EntityView assignEntityViewToPublicCustomer(
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION) @ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
try { checkParameter(ENTITY_VIEW_ID, strEntityViewId);
checkParameter(ENTITY_VIEW_ID, strEntityViewId); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER);
checkEntityViewId(entityViewId, Operation.ASSIGN_TO_CUSTOMER);
Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId()); Customer publicCustomer = customerService.findOrCreatePublicCustomer(getTenantId());
return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(), return tbEntityViewService.assignEntityViewToPublicCustomer(getTenantId(), getCurrentUser().getCustomerId(),
publicCustomer, entityViewId, getCurrentUser()); 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)", @ApiOperation(value = "Assign entity view to edge (assignEntityViewToEdge)",
@ -476,23 +443,17 @@ public class EntityViewController extends BaseController {
@ResponseBody @ResponseBody
public EntityView assignEntityViewToEdge(@PathVariable(EDGE_ID) String strEdgeId, public EntityView assignEntityViewToEdge(@PathVariable(EDGE_ID) String strEdgeId,
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(ENTITY_VIEW_ID, strEntityViewId);
checkParameter(ENTITY_VIEW_ID, strEntityViewId);
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ); Edge edge = checkEdgeId(edgeId, Operation.READ);
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
checkEntityViewId(entityViewId, Operation.READ); checkEntityViewId(entityViewId, Operation.READ);
return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(), return tbEntityViewService.assignEntityViewToEdge(getTenantId(), getCurrentUser().getCustomerId(),
entityViewId, edge, getCurrentUser()); 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)", @ApiOperation(value = "Unassign entity view from edge (unassignEntityViewFromEdge)",
@ -507,23 +468,17 @@ public class EntityViewController extends BaseController {
@ResponseBody @ResponseBody
public EntityView unassignEntityViewFromEdge(@PathVariable(EDGE_ID) String strEdgeId, public EntityView unassignEntityViewFromEdge(@PathVariable(EDGE_ID) String strEdgeId,
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException { @PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
try { checkParameter(EDGE_ID, strEdgeId);
checkParameter(EDGE_ID, strEdgeId); checkParameter(ENTITY_VIEW_ID, strEntityViewId);
checkParameter(ENTITY_VIEW_ID, strEntityViewId);
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
Edge edge = checkEdgeId(edgeId, Operation.READ); Edge edge = checkEdgeId(edgeId, Operation.READ);
EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId)); EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
EntityView entityView = checkEntityViewId(entityViewId, Operation.READ); EntityView entityView = checkEntityViewId(entityViewId, Operation.READ);
return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView, return tbEntityViewService.unassignEntityViewFromEdge(getTenantId(), entityView.getCustomerId(), entityView,
edge, getCurrentUser()); 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')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")

56
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; 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.OtaPackage;
import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.OtaPackageInfo;
import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; 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.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.OtaPackageId; 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.Operation;
import org.thingsboard.server.service.security.permission.Resource; 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.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import static org.thingsboard.server.controller.ControllerConstants.DEVICE_PROFILE_ID_PARAM_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.DEVICE_PROFILE_ID_PARAM_DESCRIPTION;
@ -156,17 +156,10 @@ public class OtaPackageController extends BaseController {
@ResponseBody @ResponseBody
public OtaPackageInfo saveOtaPackageInfo(@ApiParam(value = "A JSON value representing the OTA Package.") public OtaPackageInfo saveOtaPackageInfo(@ApiParam(value = "A JSON value representing the OTA Package.")
@RequestBody SaveOtaPackageInfoRequest otaPackageInfo) throws ThingsboardException { @RequestBody SaveOtaPackageInfoRequest otaPackageInfo) throws ThingsboardException {
try { otaPackageInfo.setTenantId(getTenantId());
otaPackageInfo.setTenantId(getTenantId()); checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE);
checkEntity(otaPackageInfo.getId(), otaPackageInfo, Resource.OTA_PACKAGE);
return tbOtaPackageService.save(otaPackageInfo, getCurrentUser()); 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)", @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) @ApiParam(value = "OTA Package checksum algorithm.", allowableValues = OTA_PACKAGE_CHECKSUM_ALGORITHM_ALLOWABLE_VALUES)
@RequestParam(CHECKSUM_ALGORITHM) String checksumAlgorithmStr, @RequestParam(CHECKSUM_ALGORITHM) String checksumAlgorithmStr,
@ApiParam(value = "OTA Package data.") @ApiParam(value = "OTA Package data.")
@RequestPart MultipartFile file) throws ThingsboardException { @RequestPart MultipartFile file) throws ThingsboardException, IOException {
try { checkParameter(OTA_PACKAGE_ID, strOtaPackageId);
checkParameter(OTA_PACKAGE_ID, strOtaPackageId); checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr);
checkParameter(CHECKSUM_ALGORITHM, checksumAlgorithmStr); OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ);
OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.READ); ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase());
ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase()); byte[] data = file.getBytes();
byte[] data = file.getBytes(); return tbOtaPackageService.saveOtaPackageData(otaPackageInfo, checksum, checksumAlgorithm,
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);
}
} }
@ApiOperation(value = "Get OTA Package Infos (getOtaPackages)", @ApiOperation(value = "Get OTA Package Infos (getOtaPackages)",
@ -266,17 +253,10 @@ public class OtaPackageController extends BaseController {
@ResponseBody @ResponseBody
public void deleteOtaPackage(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION) public void deleteOtaPackage(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION)
@PathVariable("otaPackageId") String strOtaPackageId) throws ThingsboardException { @PathVariable("otaPackageId") String strOtaPackageId) throws ThingsboardException {
try { checkParameter(OTA_PACKAGE_ID, strOtaPackageId);
checkParameter(OTA_PACKAGE_ID, strOtaPackageId); OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId)); OtaPackageInfo otaPackageInfo = checkOtaPackageInfoId(otaPackageId, Operation.DELETE);
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);
}
} }
} }

65
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 sortProperty,
@RequestParam(required = false) String sortOrder) throws ThingsboardException { @RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("serviceType", serviceType); checkParameter("serviceType", serviceType);
try { PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); ServiceType type = ServiceType.valueOf(serviceType);
ServiceType type = ServiceType.valueOf(serviceType); switch (type) {
switch (type) { case TB_RULE_ENGINE:
case TB_RULE_ENGINE: return queueService.findQueuesByTenantId(getTenantId(), pageLink);
return queueService.findQueuesByTenantId(getTenantId(), pageLink); default:
default: return new PageData<>();
return new PageData<>();
}
} catch (Exception e) {
throw handleException(e);
} }
} }
@ -74,14 +70,9 @@ public class QueueController extends BaseController {
@ResponseBody @ResponseBody
public Queue getQueueById(@PathVariable("queueId") String queueIdStr) throws ThingsboardException { public Queue getQueueById(@PathVariable("queueId") String queueIdStr) throws ThingsboardException {
checkParameter("queueId", queueIdStr); checkParameter("queueId", queueIdStr);
try { QueueId queueId = new QueueId(UUID.fromString(queueIdStr));
QueueId queueId = new QueueId(UUID.fromString(queueIdStr)); checkQueueId(queueId, Operation.READ);
checkQueueId(queueId, Operation.READ); return checkNotNull(queueService.findQueueById(getTenantId(), queueId));
return checkNotNull(queueService.findQueueById(getTenantId(), queueId));
} catch (
Exception e) {
throw handleException(e);
}
} }
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN')")
@ -90,23 +81,19 @@ public class QueueController extends BaseController {
public Queue saveQueue(@RequestBody Queue queue, public Queue saveQueue(@RequestBody Queue queue,
@RequestParam String serviceType) throws ThingsboardException { @RequestParam String serviceType) throws ThingsboardException {
checkParameter("serviceType", serviceType); 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); ServiceType type = ServiceType.valueOf(serviceType);
switch (type) { switch (type) {
case TB_RULE_ENGINE: case TB_RULE_ENGINE:
queue.setTenantId(getTenantId()); queue.setTenantId(getTenantId());
Queue savedQueue = tbQueueService.saveQueue(queue); Queue savedQueue = tbQueueService.saveQueue(queue);
checkNotNull(savedQueue); checkNotNull(savedQueue);
return savedQueue; return savedQueue;
default: default:
return null; return null;
}
} catch (Exception e) {
throw handleException(e);
} }
} }
@ -115,12 +102,8 @@ public class QueueController extends BaseController {
@ResponseBody @ResponseBody
public void deleteQueue(@PathVariable("queueId") String queueIdStr) throws ThingsboardException { public void deleteQueue(@PathVariable("queueId") String queueIdStr) throws ThingsboardException {
checkParameter("queueId", queueIdStr); checkParameter("queueId", queueIdStr);
try { QueueId queueId = new QueueId(toUUID(queueIdStr));
QueueId queueId = new QueueId(toUUID(queueIdStr)); checkQueueId(queueId, Operation.DELETE);
checkQueueId(queueId, Operation.DELETE); tbQueueService.deleteQueue(getTenantId(), queueId);
tbQueueService.deleteQueue(getTenantId(), queueId);
} catch (Exception e) {
throw handleException(e);
}
} }
} }

167
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.ActorSystemContext;
import org.thingsboard.server.actors.tenant.DebugTbRateLimits; import org.thingsboard.server.actors.tenant.DebugTbRateLimits;
import org.thingsboard.server.common.data.DataConstants; 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.Event;
import org.thingsboard.server.common.data.StringUtils; 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.edge.Edge;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.EdgeId; 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.Operation;
import org.thingsboard.server.service.security.permission.Resource; import org.thingsboard.server.service.security.permission.Resource;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -235,16 +234,9 @@ public class RuleChainController extends BaseController {
public RuleChain saveRuleChain( public RuleChain saveRuleChain(
@ApiParam(value = "A JSON value representing the rule chain.") @ApiParam(value = "A JSON value representing the rule chain.")
@RequestBody RuleChain ruleChain) throws ThingsboardException { @RequestBody RuleChain ruleChain) throws ThingsboardException {
try { ruleChain.setTenantId(getCurrentUser().getTenantId());
ruleChain.setTenantId(getCurrentUser().getTenantId()); checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN);
checkEntity(ruleChain.getId(), ruleChain, Resource.RULE_CHAIN); return tbRuleChainService.save(ruleChain, getCurrentUser());
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", @ApiOperation(value = "Create Default Rule Chain",
@ -255,18 +247,10 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain saveRuleChain( public RuleChain saveRuleChain(
@ApiParam(value = "A JSON value representing the request.") @ApiParam(value = "A JSON value representing the request.")
@RequestBody DefaultRuleChainCreateRequest request) throws ThingsboardException { @RequestBody DefaultRuleChainCreateRequest request) throws ThingsboardException, IOException {
try { checkNotNull(request);
checkNotNull(request); checkParameter(request.getName(), "name");
checkParameter(request.getName(), "name"); return tbRuleChainService.saveDefaultByName(getTenantId(), request, getCurrentUser());
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)", @ApiOperation(value = "Set Root Rule Chain (setRootRuleChain)",
@ -277,16 +261,10 @@ public class RuleChainController extends BaseController {
public RuleChain setRootRuleChain( public RuleChain setRootRuleChain(
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE);
RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); return tbRuleChainService.setRootRuleChain(getTenantId(), ruleChain, getCurrentUser());
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", @ApiOperation(value = "Update Rule Chain Metadata",
@ -300,23 +278,17 @@ public class RuleChainController extends BaseController {
@ApiParam(value = "Update related rule nodes.") @ApiParam(value = "Update related rule nodes.")
@RequestParam(value = "updateRelated", required = false, defaultValue = "true") boolean updateRelated @RequestParam(value = "updateRelated", required = false, defaultValue = "true") boolean updateRelated
) throws ThingsboardException { ) throws ThingsboardException {
try { TenantId tenantId = getTenantId();
TenantId tenantId = getTenantId(); if (debugPerTenantEnabled) {
if (debugPerTenantEnabled) { ConcurrentMap<TenantId, DebugTbRateLimits> debugPerTenantLimits = actorContext.getDebugPerTenantLimits();
ConcurrentMap<TenantId, DebugTbRateLimits> debugPerTenantLimits = actorContext.getDebugPerTenantLimits(); DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null);
DebugTbRateLimits debugTbRateLimits = debugPerTenantLimits.getOrDefault(tenantId, null); if (debugTbRateLimits != null) {
if (debugTbRateLimits != null) { debugPerTenantLimits.remove(tenantId, debugTbRateLimits);
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)", @ApiOperation(value = "Get Rule Chains (getRuleChains)",
@ -359,16 +331,10 @@ public class RuleChainController extends BaseController {
public void deleteRuleChain( public void deleteRuleChain(
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) @ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE);
RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.DELETE); tbRuleChainService.delete(ruleChain, getCurrentUser());
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)", @ApiOperation(value = "Get latest input message (getLatestRuleNodeDebugInput)",
@ -553,21 +519,15 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain assignRuleChainToEdge(@PathVariable("edgeId") String strEdgeId, public RuleChain assignRuleChainToEdge(@PathVariable("edgeId") String strEdgeId,
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter("edgeId", strEdgeId);
checkParameter("edgeId", strEdgeId); checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.WRITE);
Edge edge = checkEdgeId(edgeId, Operation.WRITE);
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ); 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)", @ApiOperation(value = "Unassign rule chain from edge (unassignRuleChainFromEdge)",
@ -582,20 +542,14 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain unassignRuleChainFromEdge(@PathVariable("edgeId") String strEdgeId, public RuleChain unassignRuleChainFromEdge(@PathVariable("edgeId") String strEdgeId,
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter("edgeId", strEdgeId);
checkParameter("edgeId", strEdgeId); checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
EdgeId edgeId = new EdgeId(toUUID(strEdgeId)); Edge edge = checkEdgeId(edgeId, Operation.WRITE);
Edge edge = checkEdgeId(edgeId, Operation.WRITE); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.READ);
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)", @ApiOperation(value = "Get Edge Rule Chains (getEdgeRuleChains)",
@ -636,16 +590,10 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain setEdgeTemplateRootRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) public RuleChain setEdgeTemplateRootRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE);
RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); return tbRuleChainService.setEdgeTemplateRootRuleChain(getTenantId(), ruleChain, getCurrentUser());
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)", @ApiOperation(value = "Set Auto Assign To Edge Rule Chain (setAutoAssignToEdgeRuleChain)",
@ -656,16 +604,10 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain setAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) public RuleChain setAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE);
RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE); return tbRuleChainService.setAutoAssignToEdgeRuleChain(getTenantId(), ruleChain, getCurrentUser());
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)", @ApiOperation(value = "Unset Auto Assign To Edge Rule Chain (unsetAutoAssignToEdgeRuleChain)",
@ -676,17 +618,10 @@ public class RuleChainController extends BaseController {
@ResponseBody @ResponseBody
public RuleChain unsetAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION) public RuleChain unsetAutoAssignToEdgeRuleChain(@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException { @PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
try { checkParameter(RULE_CHAIN_ID, strRuleChainId);
checkParameter(RULE_CHAIN_ID, strRuleChainId); RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId)); RuleChain ruleChain = checkRuleChain(ruleChainId, Operation.WRITE);
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 // TODO: @voba refactor this - add new config to edge rule chain to set it as auto-assign

29
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; 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.TbResource;
import org.thingsboard.server.common.data.TbResourceInfo; 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.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.id.TbResourceId;
import org.thingsboard.server.common.data.lwm2m.LwM2mObject; import org.thingsboard.server.common.data.lwm2m.LwM2mObject;
@ -149,16 +147,9 @@ public class TbResourceController extends BaseController {
@ResponseBody @ResponseBody
public TbResource saveResource(@ApiParam(value = "A JSON value representing the Resource.") public TbResource saveResource(@ApiParam(value = "A JSON value representing the Resource.")
@RequestBody TbResource resource) throws ThingsboardException { @RequestBody TbResource resource) throws ThingsboardException {
try { resource.setTenantId(getTenantId());
resource.setTenantId(getTenantId()); checkEntity(resource.getId(), resource, Resource.TB_RESOURCE);
checkEntity(resource.getId(), resource, Resource.TB_RESOURCE); return tbResourceService.save(resource, getCurrentUser());
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)", @ApiOperation(value = "Get Resource Infos (getResources)",
@ -242,15 +233,9 @@ public class TbResourceController extends BaseController {
@ResponseBody @ResponseBody
public void deleteResource(@ApiParam(value = RESOURCE_ID_PARAM_DESCRIPTION) public void deleteResource(@ApiParam(value = RESOURCE_ID_PARAM_DESCRIPTION)
@PathVariable("resourceId") String strResourceId) throws ThingsboardException { @PathVariable("resourceId") String strResourceId) throws ThingsboardException {
try { checkParameter(RESOURCE_ID, strResourceId);
checkParameter(RESOURCE_ID, strResourceId); TbResourceId resourceId = new TbResourceId(toUUID(strResourceId));
TbResourceId resourceId = new TbResourceId(toUUID(strResourceId)); TbResource tbResource = checkResourceId(resourceId, Operation.DELETE);
TbResource tbResource = checkResourceId(resourceId, Operation.DELETE); tbResourceService.delete(tbResource, getCurrentUser());
tbResourceService.delete(tbResource, getCurrentUser());
} catch (Exception e) {
notificationEntityService.logEntityAction(getTenantId(), emptyId(EntityType.TB_RESOURCE),
ActionType.DELETED, getCurrentUser(), e, strResourceId);
throw handleException(e);
}
} }
} }

14
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) @RequestMapping(value = "/tenant", method = RequestMethod.POST)
@ResponseBody @ResponseBody
public Tenant saveTenant(@ApiParam(value = "A JSON value representing the tenant.") 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); checkEntity(tenant.getId(), tenant, Resource.TENANT);
try { return tbTenantService.save(tenant);
return tbTenantService.save(tenant);
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Delete Tenant (deleteTenant)", @ApiOperation(value = "Delete Tenant (deleteTenant)",
@ -139,11 +135,7 @@ public class TenantController extends BaseController {
checkParameter(TENANT_ID, strTenantId); checkParameter(TENANT_ID, strTenantId);
TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId)); TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId));
Tenant tenant = checkTenantId(tenantId, Operation.DELETE); Tenant tenant = checkTenantId(tenantId, Operation.DELETE);
try { tbTenantService.delete(tenant);
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) @ApiOperation(value = "Get Tenants (getTenants)", notes = "Returns a page of tenants registered in the platform. " + PAGE_DATA_PARAMETERS + SYSTEM_AUTHORITY_PARAGRAPH)

34
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.rule.engine.api.MailService; 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.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
@ -187,17 +185,11 @@ public class UserController extends BaseController {
@RequestBody User user, @RequestBody User user,
@ApiParam(value = "Send activation email (or use activation link)", defaultValue = "true") @ApiParam(value = "Send activation email (or use activation link)", defaultValue = "true")
@RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException { @RequestParam(required = false, defaultValue = "true") boolean sendActivationMail, HttpServletRequest request) throws ThingsboardException {
try { if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) {
if (Authority.TENANT_ADMIN.equals(getCurrentUser().getAuthority())) { user.setTenantId(getCurrentUser().getTenantId());
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", @ApiOperation(value = "Send or re-send the activation email",
@ -267,19 +259,13 @@ public class UserController extends BaseController {
public void deleteUser( public void deleteUser(
@ApiParam(value = USER_ID_PARAM_DESCRIPTION) @ApiParam(value = USER_ID_PARAM_DESCRIPTION)
@PathVariable(USER_ID) String strUserId) throws ThingsboardException { @PathVariable(USER_ID) String strUserId) throws ThingsboardException {
try { checkParameter(USER_ID, strUserId);
checkParameter(USER_ID, strUserId); UserId userId = new UserId(toUUID(strUserId));
UserId userId = new UserId(toUUID(strUserId)); User user = checkUserId(userId, Operation.DELETE);
User user = checkUserId(userId, Operation.DELETE); if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) {
if (user.getAuthority() == Authority.SYS_ADMIN && getCurrentUser().getId().equals(userId)) { throw new ThingsboardException("Sysadmin is not allowed to delete himself", ThingsboardErrorCode.PERMISSION_DENIED);
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)", @ApiOperation(value = "Get Users (getUsers)",

30
application/src/main/java/org/thingsboard/server/controller/WidgetsBundleController.java

@ -97,19 +97,15 @@ public class WidgetsBundleController extends BaseController {
public WidgetsBundle saveWidgetsBundle( public WidgetsBundle saveWidgetsBundle(
@ApiParam(value = "A JSON value representing the Widget Bundle.", required = true) @ApiParam(value = "A JSON value representing the Widget Bundle.", required = true)
@RequestBody WidgetsBundle widgetsBundle) throws ThingsboardException { @RequestBody WidgetsBundle widgetsBundle) throws ThingsboardException {
try { if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) {
if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { widgetsBundle.setTenantId(TenantId.SYS_TENANT_ID);
widgetsBundle.setTenantId(TenantId.SYS_TENANT_ID); } else {
} else { widgetsBundle.setTenantId(getCurrentUser().getTenantId());
widgetsBundle.setTenantId(getCurrentUser().getTenantId()); }
}
checkEntity(widgetsBundle.getId(), widgetsBundle, Resource.WIDGETS_BUNDLE); checkEntity(widgetsBundle.getId(), widgetsBundle, Resource.WIDGETS_BUNDLE);
return tbWidgetsBundleService.save(widgetsBundle); return tbWidgetsBundleService.save(widgetsBundle);
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Delete widgets bundle (deleteWidgetsBundle)", @ApiOperation(value = "Delete widgets bundle (deleteWidgetsBundle)",
@ -120,14 +116,10 @@ public class WidgetsBundleController extends BaseController {
public void deleteWidgetsBundle( public void deleteWidgetsBundle(
@ApiParam(value = WIDGET_BUNDLE_ID_PARAM_DESCRIPTION, required = true) @ApiParam(value = WIDGET_BUNDLE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("widgetsBundleId") String strWidgetsBundleId) throws ThingsboardException { @PathVariable("widgetsBundleId") String strWidgetsBundleId) throws ThingsboardException {
try { checkParameter("widgetsBundleId", strWidgetsBundleId);
checkParameter("widgetsBundleId", strWidgetsBundleId); WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId));
WidgetsBundleId widgetsBundleId = new WidgetsBundleId(toUUID(strWidgetsBundleId)); WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE);
WidgetsBundle widgetsBundle = checkWidgetsBundleId(widgetsBundleId, Operation.DELETE); tbWidgetsBundleService.delete(widgetsBundle);
tbWidgetsBundleService.delete(widgetsBundle);
} catch (Exception e) {
throw handleException(e);
}
} }
@ApiOperation(value = "Get Widget Bundles (getWidgetsBundles)", @ApiOperation(value = "Get Widget Bundles (getWidgetsBundles)",

6
application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java

@ -121,7 +121,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService<Device> {
} }
entity.setDeviceProfileId(deviceProfile.getId()); entity.setDeviceProfileId(deviceProfile.getId());
return tbDeviceService.saveDeviceWithCredentials(user.getTenantId(), entity, deviceCredentials, user); return tbDeviceService.saveDeviceWithCredentials(entity, deviceCredentials, user);
} }
@Override @Override
@ -176,7 +176,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService<Device> {
ObjectNode lwm2mCredentials = JacksonUtil.newObjectNode(); ObjectNode lwm2mCredentials = JacksonUtil.newObjectNode();
Set.of(BulkImportColumnType.LWM2M_CLIENT_SECURITY_CONFIG_MODE, BulkImportColumnType.LWM2M_BOOTSTRAP_SERVER_SECURITY_MODE, 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) .map(fields::get)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.forEach(securityMode -> { .forEach(securityMode -> {
@ -233,7 +233,7 @@ public class DeviceBulkImportService extends AbstractBulkImportService<Device> {
Lwm2mDeviceProfileTransportConfiguration transportConfiguration = new Lwm2mDeviceProfileTransportConfiguration(); Lwm2mDeviceProfileTransportConfiguration transportConfiguration = new Lwm2mDeviceProfileTransportConfiguration();
transportConfiguration.setBootstrap(Collections.emptyList()); 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())); transportConfiguration.setObserveAttr(new TelemetryMappingConfiguration(Collections.emptyMap(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptyMap()));
DeviceProfileData deviceProfileData = new DeviceProfileData(); DeviceProfileData deviceProfileData = new DeviceProfileData();

6
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.AlarmId;
import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.EntityId; 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.id.TenantId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageDataIterableByTenantIdEntityId; 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.alarm.AlarmService;
import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.edge.EdgeService; import org.thingsboard.server.dao.edge.EdgeService;
import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.service.executors.DbCallbackExecutorService; import org.thingsboard.server.service.executors.DbCallbackExecutorService;
import java.util.ArrayList; import java.util.ArrayList;
@ -121,4 +123,8 @@ public abstract class AbstractTbEntityService {
} }
return result; return result;
} }
protected <I extends EntityId> I emptyId(EntityType entityType) {
return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID);
}
} }

13
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 lombok.AllArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil; 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.User;
import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmStatus; import org.thingsboard.server.common.data.alarm.AlarmStatus;
@ -40,9 +41,15 @@ public class DefaultTbAlarmService extends AbstractTbEntityService implements Tb
@Override @Override
public Alarm save(Alarm alarm, User user) throws ThingsboardException { public Alarm save(Alarm alarm, User user) throws ThingsboardException {
ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); TenantId tenantId = alarm.getTenantId();
notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); try {
return savedAlarm; 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 @Override

116
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 lombok.AllArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; 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.User;
import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.audit.ActionType; 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 { public Asset save(Asset asset, User user) throws ThingsboardException {
ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = asset.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = asset.getTenantId(); TenantId tenantId = asset.getTenantId();
Asset savedAsset = checkNotNull(assetService.saveAsset(asset)); try {
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), savedAsset, asset.getCustomerId(), actionType, user); Asset savedAsset = checkNotNull(assetService.saveAsset(asset));
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedAsset.getId(), savedAsset,
return savedAsset; asset.getCustomerId(), actionType, user);
return savedAsset;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), asset, actionType, user, e);
throw e;
}
} }
@Override @Override
public ListenableFuture<Void> delete(Asset asset, User user) { public ListenableFuture<Void> delete(Asset asset, User user) {
TenantId tenantId = asset.getTenantId(); TenantId tenantId = asset.getTenantId();
AssetId assetId = asset.getId(); AssetId assetId = asset.getId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId); try {
assetService.deleteAsset(tenantId, assetId); List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, assetId);
notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(), ActionType.DELETED, assetService.deleteAsset(tenantId, assetId);
relatedEdgeIds, user, assetId.toString()); notificationEntityService.notifyDeleteEntity(tenantId, assetId, asset, asset.getCustomerId(),
ActionType.DELETED, relatedEdgeIds, user, assetId.toString());
return removeAlarmsByEntityId(tenantId, assetId);
return removeAlarmsByEntityId(tenantId, assetId);
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), ActionType.DELETED, user, e,
assetId.toString());
throw e;
}
} }
@Override @Override
public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { public Asset assignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, customerId));
actionType, user, true, customerId.toString(), customer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset,
actionType, user, true, customerId.toString(), customer.getName());
return savedAsset;
return savedAsset;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e,
assetId.toString(), customerId.toString());
throw e;
}
} }
@Override @Override
public Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException { public Asset unassignAssetToCustomer(TenantId tenantId, AssetId assetId, Customer customer, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId)); try {
CustomerId customerId = customer.getId(); Asset savedAsset = checkNotNull(assetService.unassignAssetFromCustomer(tenantId, assetId));
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset, CustomerId customerId = customer.getId();
actionType, user, true, customerId.toString(), customer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, customerId, savedAsset,
actionType, user, true, customerId.toString(), customer.getName());
return savedAsset;
return savedAsset;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, assetId.toString());
throw e;
}
} }
@Override @Override
public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException { public Asset assignAssetToPublicCustomer(TenantId tenantId, AssetId assetId, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); try {
Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId())); Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset, Asset savedAsset = checkNotNull(assetService.assignAssetToCustomer(tenantId, assetId, publicCustomer.getId()));
actionType, user, false, actionType.toString(), publicCustomer.getId().toString(), publicCustomer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, assetId, savedAsset.getCustomerId(), savedAsset,
actionType, user, false, actionType.toString(), publicCustomer.getId().toString(), publicCustomer.getName());
return savedAsset;
return savedAsset;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType, user, e, assetId.toString());
throw e;
}
} }
@Override @Override
public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException { public Asset assignAssetToEdge(TenantId tenantId, AssetId assetId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE; ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(), Asset savedAsset = checkNotNull(assetService.assignAssetToEdge(tenantId, assetId, edgeId));
edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName()); notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, savedAsset.getCustomerId(),
edgeId, savedAsset, actionType, user, assetId.toString(), edgeId.toString(), edge.getName());
return savedAsset;
return savedAsset;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ASSET), actionType,
user, e, assetId.toString(), edgeId.toString());
throw e;
}
} }
@Override @Override
@ -111,10 +144,17 @@ public class DefaultTbAssetService extends AbstractTbEntityService implements Tb
ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE; ActionType actionType = ActionType.UNASSIGNED_FROM_EDGE;
AssetId assetId = asset.getId(); AssetId assetId = asset.getId();
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
Asset savedAsset = checkNotNull(assetService.unassignAssetFromEdge(tenantId, assetId, edgeId)); 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()); notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, assetId, asset.getCustomerId(),
return savedAsset; 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;
}
} }
} }

29
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 lombok.AllArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; 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.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException; 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; ActionType actionType = customer.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = customer.getTenantId(); TenantId tenantId = customer.getTenantId();
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer)); try {
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedCustomer.getId(), savedCustomer, customerId, actionType, user); Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer));
return savedCustomer; 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 @Override
public void delete(Customer customer, User user) { public void delete(Customer customer, User user) {
TenantId tenantId = customer.getTenantId(); TenantId tenantId = customer.getTenantId();
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId()); try {
customerService.deleteCustomer(tenantId, customerId); List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, customer.getId());
notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId, customerService.deleteCustomer(tenantId, customerId);
ActionType.DELETED, relatedEdgeIds, user, customerId.toString()); notificationEntityService.notifyDeleteEntity(tenantId, customer.getId(), customer, customerId,
tbClusterService.broadcastEntityStateChangeEvent(tenantId, customer.getId(), ComponentLifecycleEvent.DELETED); 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;
}
} }
} }

234
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.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard; 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.ShortCustomerInfo;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType; 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 { public Dashboard save(Dashboard dashboard, User user) throws ThingsboardException {
ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = dashboard.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard)); try {
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard, Dashboard savedDashboard = checkNotNull(dashboardService.saveDashboard(dashboard));
null, actionType, user); notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedDashboard.getId(), savedDashboard,
return savedDashboard; null, actionType, user);
return savedDashboard;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), dashboard, actionType, user, e);
throw e;
}
} }
@Override @Override
public void delete(Dashboard dashboard, User user) { public void delete(Dashboard dashboard, User user) {
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId); try {
dashboardService.deleteDashboard(tenantId, dashboardId); List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, dashboardId);
notificationEntityService.notifyDeleteEntity(tenantId, dashboardId, dashboard, null, dashboardService.deleteDashboard(tenantId, dashboardId);
ActionType.DELETED, relatedEdgeIds, user, dashboardId.toString()); 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 @Override
@ -69,10 +80,16 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard, Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId));
actionType, user, true, customerId.toString(), customer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, customerId, savedDashboard,
return 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 @Override
@ -80,12 +97,17 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); try {
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, publicCustomer.getId())); Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), savedDashboard, Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, publicCustomer.getId()));
actionType, user, false, dashboardId.toString(), notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), savedDashboard,
publicCustomer.getId().toString(), publicCustomer.getName()); actionType, user, false, dashboardId.toString(),
return savedDashboard; publicCustomer.getId().toString(), publicCustomer.getName());
return savedDashboard;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString());
throw e;
}
} }
@Override @Override
@ -93,12 +115,17 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); try {
Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, publicCustomer.getId())); Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), dashboard, Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, publicCustomer.getId()));
actionType, user, false, dashboardId.toString(), notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboardId, publicCustomer.getId(), dashboard,
publicCustomer.getId().toString(), publicCustomer.getName()); actionType, user, false, dashboardId.toString(),
return savedDashboard; publicCustomer.getId().toString(), publicCustomer.getName());
return savedDashboard;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e, dashboardId.toString());
throw e;
}
} }
@Override @Override
@ -106,40 +133,45 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
Set<CustomerId> addedCustomerIds = new HashSet<>(); try {
Set<CustomerId> removedCustomerIds = new HashSet<>(); Set<CustomerId> addedCustomerIds = new HashSet<>();
for (CustomerId customerId : customerIds) { Set<CustomerId> removedCustomerIds = new HashSet<>();
if (!dashboard.isAssignedToCustomer(customerId)) { for (CustomerId customerId : customerIds) {
addedCustomerIds.add(customerId); if (!dashboard.isAssignedToCustomer(customerId)) {
addedCustomerIds.add(customerId);
}
} }
}
Set<ShortCustomerInfo> assignedCustomers = dashboard.getAssignedCustomers(); Set<ShortCustomerInfo> assignedCustomers = dashboard.getAssignedCustomers();
if (assignedCustomers != null) { if (assignedCustomers != null) {
for (ShortCustomerInfo customerInfo : assignedCustomers) { for (ShortCustomerInfo customerInfo : assignedCustomers) {
if (!customerIds.contains(customerInfo.getCustomerId())) { if (!customerIds.contains(customerInfo.getCustomerId())) {
removedCustomerIds.add(customerInfo.getCustomerId()); removedCustomerIds.add(customerInfo.getCustomerId());
}
} }
} }
}
if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) { if (addedCustomerIds.isEmpty() && removedCustomerIds.isEmpty()) {
return dashboard; return dashboard;
} else { } else {
Dashboard savedDashboard = null; Dashboard savedDashboard = null;
for (CustomerId customerId : addedCustomerIds) { for (CustomerId customerId : addedCustomerIds) {
savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId)); savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId));
ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId);
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard,
actionType, user, true, customerInfo.getTitle()); actionType, user, true, customerInfo.getTitle());
} }
for (CustomerId customerId : removedCustomerIds) { for (CustomerId customerId : removedCustomerIds) {
ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId);
savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId)); savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customerId));
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard,
ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customerInfo.getTitle()); 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<CustomerId> customerIds, User user) throws ThingsboardException { public Dashboard addDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
if (customerIds.isEmpty()) { DashboardId dashboardId = dashboard.getId();
return dashboard; try {
} else { if (customerIds.isEmpty()) {
Dashboard savedDashboard = null; return dashboard;
for (CustomerId customerId : customerIds) { } else {
savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboard.getId(), customerId)); Dashboard savedDashboard = null;
ShortCustomerInfo customerInfo = savedDashboard.getAssignedCustomerInfo(customerId); for (CustomerId customerId : customerIds) {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, savedDashboard = checkNotNull(dashboardService.assignDashboardToCustomer(tenantId, dashboardId, customerId));
actionType, user, true, customerInfo.getTitle()); 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<CustomerId> customerIds, User user) throws ThingsboardException { public Dashboard removeDashboardCustomers(Dashboard dashboard, Set<CustomerId> customerIds, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
if (customerIds.isEmpty()) { DashboardId dashboardId = dashboard.getId();
return dashboard; try {
} else { if (customerIds.isEmpty()) {
Dashboard savedDashboard = null; return dashboard;
for (CustomerId customerId : customerIds) { } else {
ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId); Dashboard savedDashboard = null;
savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customerId)); for (CustomerId customerId : customerIds) {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, savedDashboard.getId(), customerId, savedDashboard, ShortCustomerInfo customerInfo = dashboard.getAssignedCustomerInfo(customerId);
actionType, user, true, customerInfo.getTitle()); 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 { public Dashboard asignDashboardToEdge(TenantId tenantId, DashboardId dashboardId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE; ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null, Dashboard savedDashboard = checkNotNull(dashboardService.assignDashboardToEdge(tenantId, dashboardId, edgeId));
edgeId, savedDashboard, actionType, user, dashboardId.toString(), notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null,
edgeId.toString(), edge.getName()); edgeId, savedDashboard, actionType, user, dashboardId.toString(),
return savedDashboard; edgeId.toString(), edge.getName());
return savedDashboard;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE),
actionType, user, e, dashboardId.toString(), edgeId);
throw e;
}
} }
@Override @Override
@ -196,22 +246,34 @@ public class DefaultTbDashboardService extends AbstractTbEntityService implement
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
DashboardId dashboardId = dashboard.getId(); DashboardId dashboardId = dashboard.getId();
EdgeId edgeId = edge.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, notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, dashboardId, null,
edgeId, dashboard, actionType, user, dashboardId.toString(), edgeId, dashboard, actionType, user, dashboardId.toString(),
edgeId.toString(), edge.getName()); edgeId.toString(), edge.getName());
return savedDevice; return savedDevice;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DASHBOARD), actionType, user, e,
dashboardId.toString(), edgeId.toString());
throw e;
}
} }
@Override @Override
public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException { public Dashboard unassignDashboardFromCustomer(Dashboard dashboard, Customer customer, User user) throws ThingsboardException {
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
TenantId tenantId = dashboard.getTenantId(); TenantId tenantId = dashboard.getTenantId();
Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboard.getId(), customer.getId())); DashboardId dashboardId = dashboard.getId();
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, dashboard.getId(), customer.getId(), savedDashboard, try {
actionType, user, true, customer.getId().toString(), customer.getName()); Dashboard savedDashboard = checkNotNull(dashboardService.unassignDashboardFromCustomer(tenantId, dashboardId, customer.getId()));
return savedDashboard; 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;
}
} }
} }

169
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.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Device; 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.Tenant;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
@ -57,46 +58,71 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T
private final TenantService tenantService; private final TenantService tenantService;
@Override @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; ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
Device savedDevice = checkNotNull(deviceService.saveDeviceWithAccessToken(device, accessToken)); TenantId tenantId = device.getTenantId();
notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), try {
savedDevice, oldDevice, actionType, user); 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 @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; ActionType actionType = device.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
Device savedDevice = checkNotNull(deviceService.saveDeviceWithCredentials(device, credentials)); TenantId tenantId = device.getTenantId();
notificationEntityService.notifyCreateOrUpdateDevice(tenantId, savedDevice.getId(), savedDevice.getCustomerId(), try {
savedDevice, device, actionType, user); 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 @Override
public ListenableFuture<Void> delete(Device device, User user) { public ListenableFuture<Void> delete(Device device, User user) {
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId(); DeviceId deviceId = device.getId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId); try {
deviceService.deleteDevice(tenantId, deviceId); List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, deviceId);
notificationEntityService.notifyDeleteDevice(tenantId, deviceId, device.getCustomerId(), device, deviceService.deleteDevice(tenantId, deviceId);
relatedEdgeIds, user, deviceId.toString()); 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 @Override
public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, User user) throws ThingsboardException { public Device assignDeviceToCustomer(TenantId tenantId, DeviceId deviceId, Customer customer, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, customerId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, Device savedDevice = checkNotNull(deviceService.assignDeviceToCustomer(tenantId, deviceId, customerId));
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(), customerId.toString());
throw e;
}
} }
@Override @Override
@ -104,46 +130,70 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T
ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER; ActionType actionType = ActionType.UNASSIGNED_FROM_CUSTOMER;
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId(); DeviceId deviceId = device.getId();
Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId)); try {
CustomerId customerId = customer.getId(); Device savedDevice = checkNotNull(deviceService.unassignDeviceFromCustomer(tenantId, deviceId));
CustomerId customerId = customer.getId();
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice, notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, customerId, savedDevice,
actionType, user, actionType, user,
true, customerId.toString(), customer.getName()); 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 @Override
public Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, User user) throws ThingsboardException { public Device assignDeviceToPublicCustomer(TenantId tenantId, DeviceId deviceId, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER; ActionType actionType = ActionType.ASSIGNED_TO_CUSTOMER;
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); 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, notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, deviceId, savedDevice.getCustomerId(), savedDevice,
actionType, user, false, deviceId.toString(), actionType, user, false, deviceId.toString(),
publicCustomer.getId().toString(), publicCustomer.getName()); 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 @Override
public DeviceCredentials getDeviceCredentialsByDeviceId(Device device, User user) throws ThingsboardException { public DeviceCredentials getDeviceCredentialsByDeviceId(Device device, User user) throws ThingsboardException {
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId(); DeviceId deviceId = device.getId();
DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId)); try {
notificationEntityService.logEntityAction(tenantId, deviceId, device, device.getCustomerId(), DeviceCredentials deviceCredentials = checkNotNull(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, deviceId));
ActionType.CREDENTIALS_READ, user, deviceId.toString()); notificationEntityService.logEntityAction(tenantId, deviceId, device, device.getCustomerId(),
return deviceCredentials; 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 @Override
public DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException { public DeviceCredentials updateDeviceCredentials(Device device, DeviceCredentials deviceCredentials, User user) throws ThingsboardException {
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId(); DeviceId deviceId = device.getId();
DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials)); try {
notificationEntityService.notifyUpdateDeviceCredentials(tenantId, deviceId, device.getCustomerId(), device, result, user); DeviceCredentials result = checkNotNull(deviceCredentialsService.updateDeviceCredentials(tenantId, deviceCredentials));
return result; 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 @Override
@ -179,23 +229,36 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T
public Device assignDeviceToTenant(Device device, Tenant newTenant, User user) { public Device assignDeviceToTenant(Device device, Tenant newTenant, User user) {
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
TenantId newTenantId = newTenant.getId(); TenantId newTenantId = newTenant.getId();
Tenant tenant = tenantService.findTenantById(tenantId); DeviceId deviceId = device.getId();
Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device); try {
Tenant tenant = tenantService.findTenantById(tenantId);
Device assignedDevice = deviceService.assignDeviceToTenant(newTenantId, device);
notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, device.getId(), notificationEntityService.notifyAssignDeviceToTenant(tenantId, newTenantId, deviceId,
assignedDevice.getCustomerId(), assignedDevice, tenant, user, newTenantId.toString(), newTenant.getName()); 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 @Override
public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException { public Device assignDeviceToEdge(TenantId tenantId, DeviceId deviceId, Edge edge, User user) throws ThingsboardException {
ActionType actionType = ActionType.ASSIGNED_TO_EDGE; ActionType actionType = ActionType.ASSIGNED_TO_EDGE;
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(), Device savedDevice = checkNotNull(deviceService.assignDeviceToEdge(tenantId, deviceId, edgeId));
edgeId, savedDevice, actionType, user, deviceId.toString(), edgeId.toString(), edge.getName()); notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, savedDevice.getCustomerId(),
return savedDevice; 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 @Override
@ -203,11 +266,17 @@ public class DefaultTbDeviceService extends AbstractTbEntityService implements T
TenantId tenantId = device.getTenantId(); TenantId tenantId = device.getTenantId();
DeviceId deviceId = device.getId(); DeviceId deviceId = device.getId();
EdgeId edgeId = edge.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(), notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, deviceId, device.getCustomerId(),
edgeId, device, ActionType.UNASSIGNED_FROM_EDGE, user, deviceId.toString(), edgeId.toString(), edge.getName()); edgeId, device, ActionType.UNASSIGNED_FROM_EDGE, user, deviceId.toString(), edgeId.toString(), edge.getName());
return savedDevice; return savedDevice;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE),
ActionType.UNASSIGNED_FROM_EDGE, user, e, deviceId.toString(), edgeId.toString());
throw e;
}
} }
} }

4
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 { 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<Void> delete(Device device, User user); ListenableFuture<Void> delete(Device device, User user);

83
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.DeviceProfile; 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.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException; 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 { public DeviceProfile save(DeviceProfile deviceProfile, User user) throws ThingsboardException {
ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = deviceProfile.getTenantId(); TenantId tenantId = deviceProfile.getTenantId();
boolean isFirmwareChanged = false; try {
boolean isSoftwareChanged = false; boolean isFirmwareChanged = false;
boolean isSoftwareChanged = false;
if (actionType.equals(ActionType.UPDATED)) { if (actionType.equals(ActionType.UPDATED)) {
DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId());
if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) { if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
isFirmwareChanged = true; isFirmwareChanged = true;
}
if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
isSoftwareChanged = true;
}
} }
if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) { DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
isSoftwareChanged = true;
}
}
DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
tbClusterService.onDeviceProfileChange(savedDeviceProfile, null); tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(), tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedDeviceProfile.getId(),
actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged); otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(), notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, savedDeviceProfile.getId(),
savedDeviceProfile, user, actionType, true, null); savedDeviceProfile, user, actionType, true, null);
return savedDeviceProfile; return savedDeviceProfile;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.DEVICE_PROFILE), deviceProfile, actionType, user, e);
throw e;
}
} }
@Override @Override
public void delete(DeviceProfile deviceProfile, User user) { public void delete(DeviceProfile deviceProfile, User user) {
DeviceProfileId deviceProfileId = deviceProfile.getId(); DeviceProfileId deviceProfileId = deviceProfile.getId();
TenantId tenantId = deviceProfile.getTenantId(); TenantId tenantId = deviceProfile.getTenantId();
deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId); try {
deviceProfileService.deleteDeviceProfile(tenantId, deviceProfileId);
tbClusterService.onDeviceProfileDelete(deviceProfile, null); tbClusterService.onDeviceProfileDelete(deviceProfile, null);
tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED); tbClusterService.broadcastEntityStateChangeEvent(tenantId, deviceProfileId, ComponentLifecycleEvent.DELETED);
notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile, notificationEntityService.notifyCreateOrUpdateOrDelete(tenantId, null, deviceProfileId, deviceProfile,
user, ActionType.DELETED, true, null, deviceProfileId.toString()); 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 @Override
public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException { public DeviceProfile setDefaultDeviceProfile(DeviceProfile deviceProfile, DeviceProfile previousDefaultDeviceProfile, User user) throws ThingsboardException {
TenantId tenantId = deviceProfile.getTenantId(); TenantId tenantId = deviceProfile.getTenantId();
if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfile.getId())) { DeviceProfileId deviceProfileId = deviceProfile.getId();
if (previousDefaultDeviceProfile != null) { try {
previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId()); if (deviceProfileService.setDefaultDeviceProfile(tenantId, deviceProfileId)) {
notificationEntityService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile, if (previousDefaultDeviceProfile != null) {
ActionType.UPDATED, user); previousDefaultDeviceProfile = deviceProfileService.findDeviceProfileById(tenantId, previousDefaultDeviceProfile.getId());
} notificationEntityService.logEntityAction(tenantId, previousDefaultDeviceProfile.getId(), previousDefaultDeviceProfile,
deviceProfile = deviceProfileService.findDeviceProfileById(tenantId, deviceProfile.getId()); 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;
} }
} }

96
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; 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.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.Edge; 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 { public Edge save(Edge edge, RuleChain edgeTemplateRootRuleChain, User user) throws Exception {
ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = edge.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = edge.getTenantId(); TenantId tenantId = edge.getTenantId();
Edge savedEdge = checkNotNull(edgeService.saveEdge(edge)); try {
EdgeId edgeId = savedEdge.getId(); Edge savedEdge = checkNotNull(edgeService.saveEdge(edge));
EdgeId edgeId = savedEdge.getId();
if (actionType == ActionType.ADDED) {
ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId); if (actionType == ActionType.ADDED) {
edgeNotificationService.setEdgeRootRuleChain(tenantId, savedEdge, edgeTemplateRootRuleChain.getId()); ruleChainService.assignRuleChainToEdge(tenantId, edgeTemplateRootRuleChain.getId(), edgeId);
edgeService.assignDefaultRuleChainsToEdge(tenantId, 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 @Override
public void delete(Edge edge, User user) { public void delete(Edge edge, User user) {
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
TenantId tenantId = edge.getTenantId(); TenantId tenantId = edge.getTenantId();
edgeService.deleteEdge(tenantId, edgeId); try {
notificationEntityService.notifyEdge(tenantId, edgeId, edge.getCustomerId(), edge, ActionType.DELETED, user, edgeId.toString()); 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 @Override
public Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, User user) throws ThingsboardException { public Edge assignEdgeToCustomer(TenantId tenantId, EdgeId edgeId, Customer customer, User user) throws ThingsboardException {
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId)); try {
notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user, Edge savedEdge = checkNotNull(edgeService.assignEdgeToCustomer(tenantId, edgeId, customerId));
edgeId.toString(), customerId.toString(), customer.getName()); notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user,
edgeId.toString(), customerId.toString(), customer.getName());
return savedEdge;
return savedEdge;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.EDGE),
ActionType.ASSIGNED_TO_CUSTOMER, user, e, edgeId.toString(), customerId.toString());
throw e;
}
} }
@Override @Override
@ -83,31 +101,49 @@ public class DefaultTbEdgeService extends AbstractTbEntityService implements TbE
TenantId tenantId = edge.getTenantId(); TenantId tenantId = edge.getTenantId();
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Edge savedEdge = checkNotNull(edgeService.unassignEdgeFromCustomer(tenantId, edgeId)); 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()); notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.UNASSIGNED_FROM_CUSTOMER, user,
return savedEdge; 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 @Override
public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException { public Edge assignEdgeToPublicCustomer(TenantId tenantId, EdgeId edgeId, User user) throws ThingsboardException {
Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId); Customer publicCustomer = customerService.findOrCreatePublicCustomer(tenantId);
CustomerId customerId = publicCustomer.getId(); 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, notificationEntityService.notifyEdge(tenantId, edgeId, customerId, savedEdge, ActionType.ASSIGNED_TO_CUSTOMER, user,
edgeId.toString(), customerId.toString(), publicCustomer.getName()); 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 @Override
public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception { public Edge setEdgeRootRuleChain(Edge edge, RuleChainId ruleChainId, User user) throws Exception {
TenantId tenantId = edge.getTenantId(); TenantId tenantId = edge.getTenantId();
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId); try {
notificationEntityService.notifyEdge(tenantId, edgeId, null, updatedEdge, ActionType.UPDATED, user); Edge updatedEdge = edgeNotificationService.setEdgeRootRuleChain(tenantId, edge, ruleChainId);
return updatedEdge; 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;
}
} }
} }

42
application/src/main/java/org/thingsboard/server/service/entitiy/entity/relation/DefaultTbEntityRelationService.java

@ -40,24 +40,46 @@ public class DefaultTbEntityRelationService extends AbstractTbEntityService impl
@Override @Override
public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { public void save(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException {
relationService.saveRelation(tenantId, relation); try {
notificationEntityService.notifyCreateOrUpdateRelation(tenantId, customerId, relationService.saveRelation(tenantId, relation);
relation, user, ActionType.RELATION_ADD_OR_UPDATE, 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 @Override
public void delete(TenantId tenantId, CustomerId customerId, EntityRelation relation, User user) throws ThingsboardException { 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()); try {
if (!found) { boolean found = relationService.deleteRelation(tenantId, relation.getFrom(), relation.getTo(), relation.getType(), relation.getTypeGroup());
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); 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 @Override
public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) throws ThingsboardException { public void deleteRelations(TenantId tenantId, CustomerId customerId, EntityId entityId, User user) throws ThingsboardException {
relationService.deleteEntityRelations(tenantId, entityId); try {
notificationEntityService.logEntityAction(tenantId, entityId, null, customerId, ActionType.RELATIONS_DELETED, user); 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;
}
} }
} }

153
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.springframework.stereotype.Service;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.DataConstants; 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.EntityView;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType; 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 { public EntityView save(EntityView entityView, EntityView existingEntityView, User user) throws ThingsboardException {
ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = entityView.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = entityView.getTenantId(); TenantId tenantId = entityView.getTenantId();
List<ListenableFuture<?>> futures = new ArrayList<>(); try {
if (existingEntityView != null) { List<ListenableFuture<?>> futures = new ArrayList<>();
if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) { if (existingEntityView != null) {
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); if (existingEntityView.getKeys() != null && existingEntityView.getKeys().getAttributes() != null) {
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SERVER_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user)); futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.CLIENT_SCOPE, existingEntityView.getKeys().getAttributes().getCs(), user));
futures.add(deleteAttributesFromEntityView(existingEntityView, DataConstants.SHARED_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<String> tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ?
existingEntityView.getKeys().getTimeseries() : Collections.emptyList();
futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user));
} }
List<String> tsKeys = existingEntityView.getKeys() != null && existingEntityView.getKeys().getTimeseries() != null ? EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView));
existingEntityView.getKeys().getTimeseries() : Collections.emptyList(); if (savedEntityView.getKeys() != null) {
futures.add(deleteLatestFromEntityView(existingEntityView, tsKeys, user)); if (savedEntityView.getKeys().getAttributes() != null) {
} futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user));
EntityView savedEntityView = checkNotNull(entityViewService.saveEntityView(entityView)); futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SERVER_SCOPE, savedEntityView.getKeys().getAttributes().getSs(), user));
if (savedEntityView.getKeys() != null) { futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.SHARED_SCOPE, savedEntityView.getKeys().getAttributes().getSh(), user));
if (savedEntityView.getKeys().getAttributes() != null) { }
futures.add(copyAttributesFromEntityToEntityView(savedEntityView, DataConstants.CLIENT_SCOPE, savedEntityView.getKeys().getAttributes().getCs(), user)); futures.add(copyLatestFromEntityToEntityView(tenantId, savedEntityView));
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)); for (ListenableFuture<?> future : futures) {
} try {
for (ListenableFuture<?> future : futures) { future.get();
try { } catch (InterruptedException | ExecutionException e) {
future.get(); throw new RuntimeException("Failed to copy attributes to entity view", e);
} catch (InterruptedException | ExecutionException e) { }
throw new RuntimeException("Failed to copy attributes to entity view", e);
} }
}
notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedEntityView.getId(), savedEntityView, notificationEntityService.notifyCreateOrUpdateEntity(tenantId, savedEntityView.getId(), savedEntityView,
null, actionType, user); null, actionType, user);
return savedEntityView; return savedEntityView;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.ENTITY_VIEW), entityView,
actionType, user, e);
throw e;
}
} }
@Override @Override
public void delete(EntityView entityView, User user) throws ThingsboardException { public void delete(EntityView entityView, User user) throws ThingsboardException {
TenantId tenantId = entityView.getTenantId(); TenantId tenantId = entityView.getTenantId();
EntityViewId entityViewId = entityView.getId(); EntityViewId entityViewId = entityView.getId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId); try {
entityViewService.deleteEntityView(tenantId, entityViewId); List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, entityViewId);
notificationEntityService.notifyDeleteEntity(tenantId, entityViewId, entityView, entityView.getCustomerId(), ActionType.DELETED, entityViewService.deleteEntityView(tenantId, entityViewId);
relatedEdgeIds, user, entityViewId.toString()); 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 @Override
public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { public EntityView assignEntityViewToCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException {
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, entityViewId, customerId));
ActionType.ASSIGNED_TO_CUSTOMER, user, true, customerId.toString(), customer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView,
return 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 @Override
public EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer, public EntityView assignEntityViewToPublicCustomer(TenantId tenantId, CustomerId customerId, Customer publicCustomer,
EntityViewId entityViewId, User user) throws ThingsboardException { EntityViewId entityViewId, User user) throws ThingsboardException {
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId, try {
entityViewId, publicCustomer.getId())); EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToCustomer(tenantId,
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView, entityViewId, publicCustomer.getId()));
ActionType.ASSIGNED_TO_CUSTOMER, user, false, savedEntityView.getEntityId().toString(), notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customerId, savedEntityView,
publicCustomer.getId().toString(), publicCustomer.getName()); ActionType.ASSIGNED_TO_CUSTOMER, user, false, savedEntityView.getEntityId().toString(),
return savedEntityView; 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 @Override
public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, User user) throws ThingsboardException { public EntityView assignEntityViewToEdge(TenantId tenantId, CustomerId customerId, EntityViewId entityViewId, Edge edge, User user) throws ThingsboardException {
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, EntityView savedEntityView = checkNotNull(entityViewService.assignEntityViewToEdge(tenantId, entityViewId, edgeId));
edgeId, savedEntityView, ActionType.ASSIGNED_TO_EDGE, user, savedEntityView.getEntityId().toString(), notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId,
edgeId.toString(), edge.getName()); edgeId, savedEntityView, ActionType.ASSIGNED_TO_EDGE, user, savedEntityView.getEntityId().toString(),
return savedEntityView; 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 @Override
@ -150,19 +181,31 @@ public class DefaultTbEntityViewService extends AbstractTbEntityService implemen
Edge edge, User user) throws ThingsboardException { Edge edge, User user) throws ThingsboardException {
EntityViewId entityViewId = entityView.getId(); EntityViewId entityViewId = entityView.getId();
EdgeId edgeId = edge.getId(); EdgeId edgeId = edge.getId();
EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId, EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromEdge(tenantId, entityViewId, edgeId));
edgeId, entityView, ActionType.UNASSIGNED_FROM_EDGE, user, entityViewId.toString(), notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, entityViewId, customerId,
edgeId.toString(), edge.getName()); edgeId, entityView, ActionType.UNASSIGNED_FROM_EDGE, user, entityViewId.toString(),
return savedEntityView; 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 @Override
public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException { public EntityView unassignEntityViewFromCustomer(TenantId tenantId, EntityViewId entityViewId, Customer customer, User user) throws ThingsboardException {
EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId)); try {
notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView, EntityView savedEntityView = checkNotNull(entityViewService.unassignEntityViewFromCustomer(tenantId, entityViewId));
ActionType.UNASSIGNED_FROM_CUSTOMER, user, true, customer.getId().toString(), customer.getName()); notificationEntityService.notifyAssignOrUnassignEntityToCustomer(tenantId, entityViewId, customer.getId(), savedEntityView,
return 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<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, User user) throws ThingsboardException { private ListenableFuture<List<Void>> copyAttributesFromEntityToEntityView(EntityView entityView, String scope, Collection<String> keys, User user) throws ThingsboardException {

75
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.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; 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.OtaPackage;
import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.OtaPackageInfo;
import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest; import org.thingsboard.server.common.data.SaveOtaPackageInfoRequest;
@ -44,12 +45,18 @@ public class DefaultTbOtaPackageService extends AbstractTbEntityService implemen
@Override @Override
public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, User user) throws ThingsboardException { public OtaPackageInfo save(SaveOtaPackageInfoRequest saveOtaPackageInfoRequest, User user) throws ThingsboardException {
TenantId tenantId = saveOtaPackageInfoRequest.getTenantId();
ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = saveOtaPackageInfoRequest.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
OtaPackageInfo savedOtaPackageInfo = checkNotNull(otaPackageService.saveOtaPackageInfo( TenantId tenantId = saveOtaPackageInfoRequest.getTenantId();
new OtaPackageInfo(saveOtaPackageInfoRequest), saveOtaPackageInfoRequest.isUsesUrl())); try {
notificationEntityService.logEntityAction(tenantId, savedOtaPackageInfo.getId(), savedOtaPackageInfo, actionType, user); OtaPackageInfo savedOtaPackageInfo = checkNotNull(otaPackageService.saveOtaPackageInfo(
return savedOtaPackageInfo; 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 @Override
@ -57,35 +64,47 @@ public class DefaultTbOtaPackageService extends AbstractTbEntityService implemen
byte[] data, String filename, String contentType, User user) throws ThingsboardException { byte[] data, String filename, String contentType, User user) throws ThingsboardException {
TenantId tenantId = otaPackageInfo.getTenantId(); TenantId tenantId = otaPackageInfo.getTenantId();
OtaPackageId otaPackageId = otaPackageInfo.getId(); OtaPackageId otaPackageId = otaPackageInfo.getId();
if (StringUtils.isEmpty(checksum)) { try {
checksum = otaPackageService.generateChecksum(checksumAlgorithm, ByteBuffer.wrap(data)); 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 @Override
public void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException { public void delete(OtaPackageInfo otaPackageInfo, User user) throws ThingsboardException {
TenantId tenantId = otaPackageInfo.getTenantId(); TenantId tenantId = otaPackageInfo.getTenantId();
OtaPackageId otaPackageId = otaPackageInfo.getId(); OtaPackageId otaPackageId = otaPackageInfo.getId();
otaPackageService.deleteOtaPackage(tenantId, otaPackageId); try {
notificationEntityService.logEntityAction(tenantId, otaPackageId, otaPackageInfo, ActionType.DELETED, user, otaPackageService.deleteOtaPackage(tenantId, otaPackageId);
otaPackageInfo.getId().toString()); 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;
}
} }
} }

52
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 lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.rule.engine.api.MailService; 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.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardException; 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, public User save(TenantId tenantId, CustomerId customerId, User tbUser, boolean sendActivationMail,
HttpServletRequest request, User user) throws ThingsboardException { HttpServletRequest request, User user) throws ThingsboardException {
ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = tbUser.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
boolean sendEmail = tbUser.getId() == null && sendActivationMail; try {
User savedUser = checkNotNull(userService.saveUser(tbUser)); boolean sendEmail = tbUser.getId() == null && sendActivationMail;
if (sendEmail) { User savedUser = checkNotNull(userService.saveUser(tbUser));
UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId()); if (sendEmail) {
String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request); UserCredentials userCredentials = userService.findUserCredentialsByUserId(tenantId, savedUser.getId());
String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl, String baseUrl = systemSecurityService.getBaseUrl(tenantId, customerId, request);
userCredentials.getActivateToken()); String activateUrl = String.format(ACTIVATE_URL_PATTERN, baseUrl,
String email = savedUser.getEmail(); userCredentials.getActivateToken());
try { String email = savedUser.getEmail();
mailService.sendActivationEmail(activateUrl, email); try {
} catch (ThingsboardException e) { mailService.sendActivationEmail(activateUrl, email);
userService.deleteUser(tenantId, savedUser.getId()); } catch (ThingsboardException e) {
throw 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 @Override
public void delete(TenantId tenantId, CustomerId customerId, User tbUser, User user) throws ThingsboardException { public void delete(TenantId tenantId, CustomerId customerId, User tbUser, User user) throws ThingsboardException {
UserId userId = tbUser.getId(); UserId userId = tbUser.getId();
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, userId);
userService.deleteUser(tenantId, userId); try {
notificationEntityService.notifyDeleteEntity(tenantId, userId, tbUser, customerId, List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(tenantId, userId);
ActionType.DELETED, relatedEdgeIds, user, userId.toString()); 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;
}
} }
} }

28
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.InvalidDDFFileException;
import org.eclipse.leshan.core.model.ObjectModel; import org.eclipse.leshan.core.model.ObjectModel;
import org.springframework.stereotype.Service; 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.ResourceType;
import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResource;
import org.thingsboard.server.common.data.TbResourceInfo; 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 { public TbResource save(TbResource tbResource, User user) throws ThingsboardException {
ActionType actionType = tbResource.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = tbResource.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
TenantId tenantId = tbResource.getTenantId(); TenantId tenantId = tbResource.getTenantId();
try {
TbResource savedResource = checkNotNull(saveResourceInternal(tbResource)); TbResource savedResource = checkNotNull(saveResourceInternal(tbResource));
tbClusterService.onResourceChange(savedResource, null); tbClusterService.onResourceChange(savedResource, null);
notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user); notificationEntityService.logEntityAction(tenantId, savedResource.getId(), savedResource, actionType, user);
return savedResource; return savedResource;
} catch (Exception e) {
notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.TB_RESOURCE),
tbResource, actionType, user, e);
throw e;
}
} }
@Override @Override
public void delete(TbResource tbResource, User user) { public void delete(TbResource tbResource, User user) {
TbResourceId resourceId = tbResource.getId(); TbResourceId resourceId = tbResource.getId();
TenantId tenantId = tbResource.getTenantId(); TenantId tenantId = tbResource.getTenantId();
resourceService.deleteResource(tenantId, resourceId); try {
tbClusterService.onResourceDeleted(tbResource, null); resourceService.deleteResource(tenantId, resourceId);
notificationEntityService.logEntityAction(tenantId, resourceId, tbResource, ActionType.DELETED, user, resourceId.toString()); 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;
}
} }
} }

235
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.TbRuleChainInputNode;
import org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration; import org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration;
import org.thingsboard.rule.engine.flow.TbRuleChainOutputNode; 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.User;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.Edge;
@ -170,73 +171,97 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement
TenantId tenantId = ruleChain.getTenantId(); TenantId tenantId = ruleChain.getTenantId();
ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED; ActionType actionType = ruleChain.getId() == null ? ActionType.ADDED : ActionType.UPDATED;
RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain)); RuleChain savedRuleChain = checkNotNull(ruleChainService.saveRuleChain(ruleChain));
try {
if (RuleChainType.CORE.equals(savedRuleChain.getType())) { if (RuleChainType.CORE.equals(savedRuleChain.getType())) {
tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(),
actionType.equals(ActionType.ADDED) ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED); 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 @Override
public void delete(RuleChain ruleChain, User user) { public void delete(RuleChain ruleChain, User user) {
TenantId tenantId = ruleChain.getTenantId(); TenantId tenantId = ruleChain.getTenantId();
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
List<RuleNode> referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId); try {
List<RuleNode> referencingRuleNodes = ruleChainService.getReferencingRuleChainNodes(tenantId, ruleChainId);
Set<RuleChainId> referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet()); Set<RuleChainId> referencingRuleChainIds = referencingRuleNodes.stream().map(RuleNode::getRuleChainId).collect(Collectors.toSet());
List<EdgeId> relatedEdgeIds = null; List<EdgeId> relatedEdgeIds = null;
if (RuleChainType.EDGE.equals(ruleChain.getType())) { if (RuleChainType.EDGE.equals(ruleChain.getType())) {
relatedEdgeIds = findRelatedEdgeIds(tenantId, ruleChainId); 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())) { if (RuleChainType.CORE.equals(ruleChain.getType())) {
referencingRuleChainIds.forEach(referencingRuleChainId -> referencingRuleChainIds.forEach(referencingRuleChainId ->
tbClusterService.broadcastEntityStateChangeEvent(tenantId, referencingRuleChainId, ComponentLifecycleEvent.UPDATED)); 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 @Override
public RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, User user) throws IOException { public RuleChain saveDefaultByName(TenantId tenantId, DefaultRuleChainCreateRequest request, User user) throws IOException {
RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName()); try {
tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED); RuleChain savedRuleChain = installScripts.createDefaultRuleChain(tenantId, request.getName());
notificationEntityService.logEntityAction(tenantId, savedRuleChain.getId(), savedRuleChain, ActionType.ADDED, user); tbClusterService.broadcastEntityStateChangeEvent(tenantId, savedRuleChain.getId(), ComponentLifecycleEvent.CREATED);
return savedRuleChain; 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 @Override
public RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { public RuleChain setRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId); try {
if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) { RuleChain previousRootRuleChain = ruleChainService.getRootTenantRuleChain(tenantId);
if (previousRootRuleChain != null) { if (ruleChainService.setRootRuleChain(tenantId, ruleChainId)) {
RuleChainId previousRootRuleChainId = previousRootRuleChain.getId(); if (previousRootRuleChain != null) {
previousRootRuleChain = ruleChainService.findRuleChainById(tenantId, previousRootRuleChainId); 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); ComponentLifecycleEvent.UPDATED);
notificationEntityService.logEntityAction(tenantId, previousRootRuleChainId, previousRootRuleChain, notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user);
ActionType.UPDATED, user);
} }
ruleChain = ruleChainService.findRuleChainById(tenantId, ruleChainId); return ruleChain;
} catch (Exception e) {
tbClusterService.broadcastEntityStateChangeEvent(tenantId, ruleChainId, notificationEntityService.logEntityAction(tenantId, emptyId(EntityType.RULE_CHAIN), ActionType.UPDATED,
ComponentLifecycleEvent.UPDATED); user, e, ruleChainId.toString());
notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); throw e;
} }
return ruleChain;
} }
@Override @Override
@ -244,85 +269,123 @@ public class DefaultTbRuleChainService extends AbstractTbEntityService implement
boolean updateRelated, User user) throws ThingsboardException { boolean updateRelated, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
RuleChainId ruleChainMetaDataId = ruleChainMetaData.getRuleChainId(); RuleChainId ruleChainMetaDataId = ruleChainMetaData.getRuleChainId();
RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData); try {
checkNotNull(result.isSuccess() ? true : null); RuleChainUpdateResult result = ruleChainService.saveRuleChainMetaData(tenantId, ruleChainMetaData);
checkNotNull(result.isSuccess() ? true : null);
List<RuleChain> updatedRuleChains;
if (updateRelated && result.isSuccess()) {
updatedRuleChains = updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result);
} else {
updatedRuleChains = Collections.emptyList();
}
RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId)); List<RuleChain> updatedRuleChains;
if (updateRelated && result.isSuccess()) {
updatedRuleChains = updateRelatedRuleChains(tenantId, ruleChainMetaDataId, result);
} else {
updatedRuleChains = Collections.emptyList();
}
if (RuleChainType.CORE.equals(ruleChain.getType())) { RuleChainMetaData savedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, ruleChainMetaDataId));
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); 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.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user, ruleChainMetaData);
notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED);
}
for (RuleChain updatedRuleChain : updatedRuleChains) {
if (RuleChainType.EDGE.equals(ruleChain.getType())) { if (RuleChainType.EDGE.equals(ruleChain.getType())) {
notificationEntityService.notifySendMsgToEdgeService(tenantId, updatedRuleChain.getId(), EdgeEventActionType.UPDATED); notificationEntityService.notifySendMsgToEdgeService(tenantId, ruleChain.getId(), EdgeEventActionType.UPDATED);
} else {
RuleChainMetaData updatedRuleChainMetaData = checkNotNull(ruleChainService.loadRuleChainMetaData(tenantId, updatedRuleChain.getId()));
notificationEntityService.logEntityAction(tenantId, updatedRuleChain.getId(), updatedRuleChain,
ActionType.UPDATED, user, updatedRuleChainMetaData);
} }
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 @Override
public RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { public RuleChain assignRuleChainToEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edge.getId())); EdgeId edgeId = edge.getId();
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, try {
null, edge.getId(), savedRuleChain, ActionType.ASSIGNED_TO_EDGE, RuleChain savedRuleChain = checkNotNull(ruleChainService.assignRuleChainToEdge(tenantId, ruleChainId, edgeId));
user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId,
return savedRuleChain; 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 @Override
public RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException { public RuleChain unassignRuleChainFromEdge(TenantId tenantId, RuleChain ruleChain, Edge edge, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edge.getId(), false)); EdgeId edgeId = edge.getId();
notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId, try {
null, edge.getId(), savedRuleChain, ActionType.UNASSIGNED_FROM_EDGE, RuleChain savedRuleChain = checkNotNull(ruleChainService.unassignRuleChainFromEdge(tenantId, ruleChainId, edgeId, false));
user, ruleChainId.toString(), edge.getId().toString(), edge.getName()); notificationEntityService.notifyAssignOrUnassignEntityToEdge(tenantId, ruleChainId,
return savedRuleChain; 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 @Override
public RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { public RuleChain setEdgeTemplateRootRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId); try {
notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); ruleChainService.setEdgeTemplateRootRuleChain(tenantId, ruleChainId);
return ruleChain; 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 @Override
public RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { public RuleChain setAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId); try {
notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); ruleChainService.setAutoAssignToEdgeRuleChain(tenantId, ruleChainId);
return ruleChain; 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 @Override
public RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException { public RuleChain unsetAutoAssignToEdgeRuleChain(TenantId tenantId, RuleChain ruleChain, User user) throws ThingsboardException {
RuleChainId ruleChainId = ruleChain.getId(); RuleChainId ruleChainId = ruleChain.getId();
ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId); try {
notificationEntityService.logEntityAction(tenantId, ruleChainId, ruleChain, ActionType.UPDATED, user); ruleChainService.unsetAutoAssignToEdgeRuleChain(tenantId, ruleChainId);
return ruleChain; 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<RuleChainId> updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map<String, String> labelsMap) { private Set<RuleChainId> updateRelatedRuleChains(TenantId tenantId, RuleChainId ruleChainId, Map<String, String> labelsMap) {

Loading…
Cancel
Save