diff --git a/application/src/main/data/json/tenant/edge_management/rule_chains/edge_root_rule_chain.json b/application/src/main/data/json/edge/rule_chains/edge_root_rule_chain.json
similarity index 83%
rename from application/src/main/data/json/tenant/edge_management/rule_chains/edge_root_rule_chain.json
rename to application/src/main/data/json/edge/rule_chains/edge_root_rule_chain.json
index f908b1661e..ec1341cc71 100644
--- a/application/src/main/data/json/tenant/edge_management/rule_chains/edge_root_rule_chain.json
+++ b/application/src/main/data/json/edge/rule_chains/edge_root_rule_chain.json
@@ -6,7 +6,8 @@
"firstRuleNodeId": null,
"root": true,
"debugMode": false,
- "configuration": null
+ "configuration": null,
+ "externalId": null
},
"metadata": {
"firstNodeIndex": 0,
@@ -23,7 +24,8 @@
"configuration": {
"persistAlarmRulesState": false,
"fetchAlarmRulesStateOnStart": false
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -35,7 +37,8 @@
"debugMode": false,
"configuration": {
"defaultTTL": 0
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -46,8 +49,10 @@
"name": "Save Client Attributes",
"debugMode": false,
"configuration": {
- "scope": "CLIENT_SCOPE"
- }
+ "scope": "CLIENT_SCOPE",
+ "notifyDevice": "false"
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -59,7 +64,8 @@
"debugMode": false,
"configuration": {
"version": 0
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -73,7 +79,8 @@
"scriptLang": "TBEL",
"jsScript": "return '\\nIncoming message:\\n' + JSON.stringify(msg) + '\\nIncoming metadata:\\n' + JSON.stringify(metadata);",
"tbelScript": "return '\\nIncoming message:\\n' + JSON.stringify(msg) + '\\nIncoming metadata:\\n' + JSON.stringify(metadata);"
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -87,7 +94,8 @@
"scriptLang": "TBEL",
"jsScript": "return '\\nIncoming message:\\n' + JSON.stringify(msg) + '\\nIncoming metadata:\\n' + JSON.stringify(metadata);",
"tbelScript": "return '\\nIncoming message:\\n' + JSON.stringify(msg) + '\\nIncoming metadata:\\n' + JSON.stringify(metadata);"
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
@@ -99,19 +107,34 @@
"debugMode": false,
"configuration": {
"timeoutInSeconds": 60
- }
+ },
+ "externalId": null
},
{
"additionalInfo": {
- "layoutX": 1129,
- "layoutY": 52
+ "layoutX": 1126,
+ "layoutY": 104
},
"type": "org.thingsboard.rule.engine.edge.TbMsgPushToCloudNode",
"name": "Push to cloud",
"debugMode": false,
"configuration": {
"scope": "SERVER_SCOPE"
- }
+ },
+ "externalId": null
+ },
+ {
+ "additionalInfo": {
+ "layoutX": 826,
+ "layoutY": 601
+ },
+ "type": "org.thingsboard.rule.engine.edge.TbMsgPushToCloudNode",
+ "name": "Push to cloud",
+ "debugMode": false,
+ "configuration": {
+ "scope": "SERVER_SCOPE"
+ },
+ "externalId": null
}
],
"connections": [
@@ -132,24 +155,14 @@
},
{
"fromIndex": 3,
- "toIndex": 6,
- "type": "RPC Request to Device"
- },
- {
- "fromIndex": 3,
- "toIndex": 5,
- "type": "Other"
+ "toIndex": 1,
+ "type": "Post telemetry"
},
{
"fromIndex": 3,
"toIndex": 2,
"type": "Post attributes"
},
- {
- "fromIndex": 3,
- "toIndex": 1,
- "type": "Post telemetry"
- },
{
"fromIndex": 3,
"toIndex": 4,
@@ -157,23 +170,23 @@
},
{
"fromIndex": 3,
- "toIndex": 7,
- "type": "Attributes Updated"
+ "toIndex": 5,
+ "type": "Other"
},
{
"fromIndex": 3,
- "toIndex": 7,
- "type": "Attributes Deleted"
+ "toIndex": 6,
+ "type": "RPC Request to Device"
},
{
"fromIndex": 3,
- "toIndex": 7,
- "type": "Timeseries Deleted"
+ "toIndex": 8,
+ "type": "Attributes Deleted"
},
{
"fromIndex": 3,
- "toIndex": 7,
- "type": "Timeseries Updated"
+ "toIndex": 8,
+ "type": "Attributes Updated"
}
],
"ruleChainConnections": null
diff --git a/application/src/main/data/json/system/widget_bundles/alarm_widgets.json b/application/src/main/data/json/system/widget_bundles/alarm_widgets.json
index e7a97b36f8..16a155cebb 100644
--- a/application/src/main/data/json/system/widget_bundles/alarm_widgets.json
+++ b/application/src/main/data/json/system/widget_bundles/alarm_widgets.json
@@ -23,7 +23,7 @@
"dataKeySettingsSchema": "",
"settingsDirective": "tb-alarms-table-widget-settings",
"dataKeySettingsDirective": "tb-alarms-table-key-settings",
- "defaultConfig": "{\"timewindow\":{\"realtime\":{\"interval\":1000,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":200}},\"showTitle\":true,\"backgroundColor\":\"rgb(255, 255, 255)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"4px\",\"settings\":{\"enableSelection\":true,\"enableSearch\":true,\"displayDetails\":true,\"allowAcknowledgment\":true,\"allowClear\":true,\"allowAssign\":true,\"displayComments\":true,\"displayPagination\":true,\"defaultPageSize\":10,\"defaultSortOrder\":\"-createdTime\",\"enableSelectColumnDisplay\":true,\"enableStickyAction\":false,\"enableFilter\":true},\"title\":\"Alarms table\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400,\"padding\":\"5px 10px 5px 10px\"},\"useDashboardTimewindow\":false,\"showLegend\":false,\"alarmSource\":{\"type\":\"function\",\"dataKeys\":[{\"name\":\"createdTime\",\"type\":\"alarm\",\"label\":\"Created time\",\"color\":\"#2196f3\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.021092237451093787},{\"name\":\"originator\",\"type\":\"alarm\",\"label\":\"Originator\",\"color\":\"#4caf50\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.2780007688856758},{\"name\":\"type\",\"type\":\"alarm\",\"label\":\"Type\",\"color\":\"#f44336\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.7323586880398418},{\"name\":\"severity\",\"type\":\"alarm\",\"label\":\"Severity\",\"color\":\"#ffc107\",\"settings\":{\"useCellStyleFunction\":false,\"useCellContentFunction\":false},\"_hash\":0.09927019860088193},{\"name\":\"status\",\"type\":\"alarm\",\"label\":\"Status\",\"color\":\"#607d8b\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.6588418951443418},{\"name\":\"assignee\",\"type\":\"alarm\",\"label\":\"Assignee\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.5008441077416634}],\"entityAliasId\":null,\"name\":\"alarms\"},\"alarmSearchStatus\":\"ANY\",\"alarmsPollingInterval\":5,\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\",\"widgetStyle\":{},\"displayTimewindow\":true,\"actions\":{},\"alarmStatusList\":[],\"alarmSeverityList\":[],\"alarmTypeList\":[],\"searchPropagatedAlarms\":false}"
+ "defaultConfig": "{\"timewindow\":{\"realtime\":{\"interval\":1000,\"timewindowMs\":86400000},\"aggregation\":{\"type\":\"NONE\",\"limit\":200}},\"showTitle\":true,\"backgroundColor\":\"rgb(255, 255, 255)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"4px\",\"settings\":{\"enableSelection\":true,\"enableSearch\":true,\"displayDetails\":true,\"allowAcknowledgment\":true,\"allowClear\":true,\"allowAssign\":true,\"displayActivity\":true,\"displayPagination\":true,\"defaultPageSize\":10,\"defaultSortOrder\":\"-createdTime\",\"enableSelectColumnDisplay\":true,\"enableStickyAction\":false,\"enableFilter\":true},\"title\":\"Alarms table\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400,\"padding\":\"5px 10px 5px 10px\"},\"useDashboardTimewindow\":false,\"showLegend\":false,\"alarmSource\":{\"type\":\"function\",\"dataKeys\":[{\"name\":\"createdTime\",\"type\":\"alarm\",\"label\":\"Created time\",\"color\":\"#2196f3\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.021092237451093787},{\"name\":\"originator\",\"type\":\"alarm\",\"label\":\"Originator\",\"color\":\"#4caf50\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.2780007688856758},{\"name\":\"type\",\"type\":\"alarm\",\"label\":\"Type\",\"color\":\"#f44336\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.7323586880398418},{\"name\":\"severity\",\"type\":\"alarm\",\"label\":\"Severity\",\"color\":\"#ffc107\",\"settings\":{\"useCellStyleFunction\":false,\"useCellContentFunction\":false},\"_hash\":0.09927019860088193},{\"name\":\"status\",\"type\":\"alarm\",\"label\":\"Status\",\"color\":\"#607d8b\",\"settings\":{\"useCellStyleFunction\":false,\"cellStyleFunction\":\"\",\"useCellContentFunction\":false,\"cellContentFunction\":\"\"},\"_hash\":0.6588418951443418},{\"name\":\"assignee\",\"type\":\"alarm\",\"label\":\"Assignee\",\"color\":\"#9c27b0\",\"settings\":{},\"_hash\":0.5008441077416634}],\"entityAliasId\":null,\"name\":\"alarms\"},\"alarmSearchStatus\":\"ANY\",\"alarmsPollingInterval\":5,\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\",\"widgetStyle\":{},\"displayTimewindow\":true,\"actions\":{},\"alarmStatusList\":[],\"alarmSeverityList\":[],\"alarmTypeList\":[],\"searchPropagatedAlarms\":false}"
}
}
]
diff --git a/application/src/main/data/json/system/widget_bundles/home_page_widgets.json b/application/src/main/data/json/system/widget_bundles/home_page_widgets.json
new file mode 100644
index 0000000000..fc5b13154c
--- /dev/null
+++ b/application/src/main/data/json/system/widget_bundles/home_page_widgets.json
@@ -0,0 +1,50 @@
+{
+ "widgetsBundle": {
+ "alias": "home_page_widgets",
+ "title": "Home page widgets",
+ "image": null,
+ "description": null,
+ "externalId": null,
+ "name": "Home page widgets"
+ },
+ "widgetTypes": [
+ {
+ "alias": "documentation_links",
+ "name": "Documentation links",
+ "image": null,
+ "description": null,
+ "descriptor": {
+ "type": "static",
+ "sizeX": 7.5,
+ "sizeY": 3,
+ "resources": [],
+ "templateHtml": "\n\n",
+ "templateCss": "",
+ "controllerScript": "self.onInit = function() {\n}",
+ "settingsSchema": "",
+ "dataKeySettingsSchema": "",
+ "settingsDirective": "tb-doc-links-widget-settings",
+ "defaultConfig": "{\"showTitle\":false,\"backgroundColor\":\"rgb(255, 255, 255)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"columns\":3},\"title\":\"Documentation links\",\"dropShadow\":true}"
+ }
+ },
+ {
+ "alias": "getting_started",
+ "name": "Getting started",
+ "image": null,
+ "description": null,
+ "descriptor": {
+ "type": "static",
+ "sizeX": 7.5,
+ "sizeY": 6.5,
+ "resources": [],
+ "templateHtml": "\n\n",
+ "templateCss": "",
+ "controllerScript": "self.onInit = function() {\n}",
+ "settingsSchema": "",
+ "dataKeySettingsSchema": "",
+ "settingsDirective": "",
+ "defaultConfig": "{\"showTitle\":false,\"backgroundColor\":\"rgb(255, 255, 255)\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{},\"title\":\"Getting started\",\"dropShadow\":true}"
+ }
+ }
+ ]
+}
\ No newline at end of file
diff --git a/application/src/main/data/upgrade/3.4.4/schema_update.sql b/application/src/main/data/upgrade/3.4.4/schema_update.sql
index 6860adc612..985dea197c 100644
--- a/application/src/main/data/upgrade/3.4.4/schema_update.sql
+++ b/application/src/main/data/upgrade/3.4.4/schema_update.sql
@@ -107,7 +107,7 @@ CREATE TABLE IF NOT EXISTS notification_template (
tenant_id UUID NOT NULL,
name VARCHAR(255) NOT NULL,
notification_type VARCHAR(50) NOT NULL,
- configuration VARCHAR(10000) NOT NULL,
+ configuration VARCHAR(10000000) NOT NULL,
CONSTRAINT uq_notification_template_name UNIQUE (tenant_id, name)
);
CREATE INDEX IF NOT EXISTS idx_notification_template_tenant_id_created_time ON notification_template(tenant_id, created_time DESC);
@@ -132,7 +132,7 @@ CREATE TABLE IF NOT EXISTS notification_request (
tenant_id UUID NOT NULL,
targets VARCHAR(10000) NOT NULL,
template_id UUID,
- template VARCHAR(10000),
+ template VARCHAR(10000000),
info VARCHAR(1000),
additional_config VARCHAR(1000),
originator_entity_id UUID,
@@ -167,11 +167,12 @@ CREATE INDEX IF NOT EXISTS idx_notification_recipient_id_created_time ON notific
ALTER TABLE tb_user ADD COLUMN IF NOT EXISTS phone VARCHAR(255);
CREATE TABLE IF NOT EXISTS user_settings (
- user_id uuid NOT NULL CONSTRAINT user_settings_pkey PRIMARY KEY,
- settings varchar(100000),
- CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES tb_user(id) ON DELETE CASCADE
+ user_id uuid NOT NULL,
+ type VARCHAR(50) NOT NULL,
+ settings varchar(10000),
+ CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES tb_user(id) ON DELETE CASCADE,
+ CONSTRAINT user_settings_pkey PRIMARY KEY (user_id, type)
);
-
-- ALARM INFO VIEW
DROP VIEW IF EXISTS alarm_info CASCADE;
diff --git a/application/src/main/java/org/thingsboard/server/actors/ActorSystemContext.java b/application/src/main/java/org/thingsboard/server/actors/ActorSystemContext.java
index c0fff5e387..26eab30d5d 100644
--- a/application/src/main/java/org/thingsboard/server/actors/ActorSystemContext.java
+++ b/application/src/main/java/org/thingsboard/server/actors/ActorSystemContext.java
@@ -71,7 +71,6 @@ import org.thingsboard.server.dao.event.EventService;
import org.thingsboard.server.dao.nosql.CassandraBufferedRateReadExecutor;
import org.thingsboard.server.dao.nosql.CassandraBufferedRateWriteExecutor;
import org.thingsboard.server.dao.notification.NotificationRequestService;
-import org.thingsboard.server.dao.notification.NotificationRuleProcessingService;
import org.thingsboard.server.dao.notification.NotificationRuleService;
import org.thingsboard.server.dao.notification.NotificationTargetService;
import org.thingsboard.server.dao.notification.NotificationTemplateService;
@@ -90,6 +89,7 @@ import org.thingsboard.server.dao.widget.WidgetTypeService;
import org.thingsboard.server.dao.widget.WidgetsBundleService;
import org.thingsboard.server.queue.discovery.PartitionService;
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider;
+import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor;
import org.thingsboard.server.queue.util.DataDecodingEncodingService;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.component.ComponentDiscoveryService;
@@ -341,7 +341,7 @@ public class ActorSystemContext {
@Autowired
@Getter
- private NotificationRuleProcessingService notificationRuleProcessingService;
+ private NotificationRuleProcessor notificationRuleProcessor;
@Autowired
@Getter
diff --git a/application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleEngineComponentActor.java b/application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleEngineComponentActor.java
index d330dfceec..e1918466a8 100644
--- a/application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleEngineComponentActor.java
+++ b/application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleEngineComponentActor.java
@@ -24,7 +24,7 @@ import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent;
import org.thingsboard.server.common.msg.TbActorStopReason;
-import org.thingsboard.server.dao.notification.trigger.RuleEngineComponentLifecycleEventTrigger;
+import org.thingsboard.server.common.msg.notification.trigger.RuleEngineComponentLifecycleEventTrigger;
public abstract class RuleEngineComponentActor> extends ComponentActor {
@@ -50,7 +50,8 @@ public abstract class RuleEngineComponentActor deleteRepositorySettings() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.DELETE);
- return wrapFuture(versionControlService.deleteVersionControlSettings(getTenantId()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ public DeferredResult deleteRepositorySettings() throws Exception {
+ accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.DELETE);
+ return wrapFuture(versionControlService.deleteVersionControlSettings(getTenantId()));
}
@ApiOperation(value = "Check repository access (checkRepositoryAccess)",
@@ -322,14 +278,10 @@ public class AdminController extends BaseController {
@RequestMapping(value = "/repositorySettings/checkAccess", method = RequestMethod.POST)
public DeferredResult checkRepositoryAccess(
@ApiParam(value = "A JSON value representing the Repository Settings.")
- @RequestBody RepositorySettings settings) throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
- settings = checkNotNull(settings);
- return wrapFuture(versionControlService.checkVersionControlAccess(getTenantId(), settings));
- } catch (Exception e) {
- throw handleException(e);
- }
+ @RequestBody RepositorySettings settings) throws Exception {
+ accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
+ settings = checkNotNull(settings);
+ return wrapFuture(versionControlService.checkVersionControlAccess(getTenantId(), settings));
}
@ApiOperation(value = "Get auto commit settings (getAutoCommitSettings)",
@@ -337,12 +289,8 @@ public class AdminController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/autoCommitSettings")
public AutoCommitSettings getAutoCommitSettings() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
- return checkNotNull(autoCommitSettingsService.get(getTenantId()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
+ return checkNotNull(autoCommitSettingsService.get(getTenantId()));
}
@ApiOperation(value = "Check auto commit settings exists (autoCommitSettingsExists)",
@@ -350,12 +298,8 @@ public class AdminController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/autoCommitSettings/exists")
public Boolean autoCommitSettingsExists() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
- return autoCommitSettingsService.get(getTenantId()) != null;
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ);
+ return autoCommitSettingsService.get(getTenantId()) != null;
}
@ApiOperation(value = "Creates or Updates the auto commit settings (saveAutoCommitSettings)",
@@ -374,12 +318,8 @@ public class AdminController extends BaseController {
@RequestMapping(value = "/autoCommitSettings", method = RequestMethod.DELETE)
@ResponseStatus(value = HttpStatus.OK)
public void deleteAutoCommitSettings() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.DELETE);
- autoCommitSettingsService.delete(getTenantId());
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.DELETE);
+ autoCommitSettingsService.delete(getTenantId());
}
@ApiOperation(value = "Check for new Platform Releases (checkUpdates)",
@@ -389,11 +329,7 @@ public class AdminController extends BaseController {
@RequestMapping(value = "/updates", method = RequestMethod.GET)
@ResponseBody
public UpdateMessage checkUpdates() throws ThingsboardException {
- try {
- return updateService.checkUpdates();
- } catch (Exception e) {
- throw handleException(e);
- }
+ return updateService.checkUpdates();
}
@ApiOperation(value = "Get system info (getSystemInfo)",
diff --git a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java
index 54368af0db..59ed65c6c9 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AlarmController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AlarmController.java
@@ -53,6 +53,7 @@ import org.thingsboard.server.service.security.permission.Operation;
import org.thingsboard.server.service.security.permission.Resource;
import java.util.UUID;
+import java.util.concurrent.ExecutionException;
import static org.thingsboard.server.controller.ControllerConstants.ALARM_ID_PARAM_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.ALARM_INFO_DESCRIPTION;
@@ -258,7 +259,7 @@ public class AlarmController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = ALARM_QUERY_FETCH_ORIGINATOR_DESCRIPTION)
@RequestParam(required = false) Boolean fetchOriginator
- ) throws ThingsboardException {
+ ) throws ThingsboardException, ExecutionException, InterruptedException {
checkParameter("EntityId", strEntityId);
checkParameter("EntityType", strEntityType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId);
@@ -275,11 +276,7 @@ public class AlarmController extends BaseController {
}
TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- try {
- return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(entityId, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(entityId, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
}
@ApiOperation(value = "Get All Alarms (getAllAlarms)",
@@ -314,7 +311,7 @@ public class AlarmController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = ALARM_QUERY_FETCH_ORIGINATOR_DESCRIPTION)
@RequestParam(required = false) Boolean fetchOriginator
- ) throws ThingsboardException {
+ ) throws ThingsboardException, ExecutionException, InterruptedException {
AlarmSearchStatus alarmSearchStatus = StringUtils.isEmpty(searchStatus) ? null : AlarmSearchStatus.valueOf(searchStatus);
AlarmStatus alarmStatus = StringUtils.isEmpty(status) ? null : AlarmStatus.valueOf(status);
if (alarmSearchStatus != null && alarmStatus != null) {
@@ -327,14 +324,10 @@ public class AlarmController extends BaseController {
}
TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- try {
- if (getCurrentUser().isCustomerUser()) {
- return checkNotNull(alarmService.findCustomerAlarms(getCurrentUser().getTenantId(), getCurrentUser().getCustomerId(), new AlarmQuery(null, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
- } else {
- return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(null, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
- }
- } catch (Exception e) {
- throw handleException(e);
+ if (getCurrentUser().isCustomerUser()) {
+ return checkNotNull(alarmService.findCustomerAlarms(getCurrentUser().getTenantId(), getCurrentUser().getCustomerId(), new AlarmQuery(null, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
+ } else {
+ return checkNotNull(alarmService.findAlarms(getCurrentUser().getTenantId(), new AlarmQuery(null, pageLink, alarmSearchStatus, alarmStatus, assigneeUserId, fetchOriginator)).get());
}
}
@@ -367,11 +360,8 @@ public class AlarmController extends BaseController {
"and 'status' can't be specified at the same time!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
checkEntityId(entityId, Operation.READ);
- try {
- return alarmService.findHighestAlarmSeverity(getCurrentUser().getTenantId(), entityId, alarmSearchStatus, alarmStatus, assigneeId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return alarmService.findHighestAlarmSeverity(getCurrentUser().getTenantId(), entityId, alarmSearchStatus,
+ alarmStatus, assigneeId);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/AssetController.java b/application/src/main/java/org/thingsboard/server/controller/AssetController.java
index 7627d9d27b..510fefe305 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AssetController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AssetController.java
@@ -60,6 +60,7 @@ import org.thingsboard.server.service.security.permission.Resource;
import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.ASSET_ID_PARAM_DESCRIPTION;
@@ -108,12 +109,8 @@ public class AssetController extends BaseController {
public Asset getAssetById(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
- try {
- AssetId assetId = new AssetId(toUUID(strAssetId));
- return checkAssetId(assetId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ AssetId assetId = new AssetId(toUUID(strAssetId));
+ return checkAssetId(assetId, Operation.READ);
}
@ApiOperation(value = "Get Asset Info (getAssetInfoById)",
@@ -127,12 +124,8 @@ public class AssetController extends BaseController {
public AssetInfo getAssetInfoById(@ApiParam(value = ASSET_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_ID) String strAssetId) throws ThingsboardException {
checkParameter(ASSET_ID, strAssetId);
- try {
- AssetId assetId = new AssetId(toUUID(strAssetId));
- return checkAssetInfoId(assetId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ AssetId assetId = new AssetId(toUUID(strAssetId));
+ return checkAssetInfoId(assetId, Operation.READ);
}
@ApiOperation(value = "Create Or Update Asset (saveAsset)",
@@ -228,16 +221,12 @@ public class AssetController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(assetService.findAssetsByTenantIdAndType(tenantId, type, pageLink));
- } else {
- return checkNotNull(assetService.findAssetsByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(assetService.findAssetsByTenantIdAndType(tenantId, type, pageLink));
+ } else {
+ return checkNotNull(assetService.findAssetsByTenantId(tenantId, pageLink));
}
}
@@ -262,19 +251,15 @@ public class AssetController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(assetService.findAssetInfosByTenantIdAndType(tenantId, type, pageLink));
- } else if (assetProfileId != null && assetProfileId.length() > 0) {
- AssetProfileId profileId = new AssetProfileId(toUUID(assetProfileId));
- return checkNotNull(assetService.findAssetInfosByTenantIdAndAssetProfileId(tenantId, profileId, pageLink));
- } else {
- return checkNotNull(assetService.findAssetInfosByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(assetService.findAssetInfosByTenantIdAndType(tenantId, type, pageLink));
+ } else if (assetProfileId != null && assetProfileId.length() > 0) {
+ AssetProfileId profileId = new AssetProfileId(toUUID(assetProfileId));
+ return checkNotNull(assetService.findAssetInfosByTenantIdAndAssetProfileId(tenantId, profileId, pageLink));
+ } else {
+ return checkNotNull(assetService.findAssetInfosByTenantId(tenantId, pageLink));
}
}
@@ -287,12 +272,8 @@ public class AssetController extends BaseController {
public Asset getTenantAsset(
@ApiParam(value = ASSET_NAME_DESCRIPTION)
@RequestParam String assetName) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(assetService.findAssetByTenantIdAndName(tenantId, assetName));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(assetService.findAssetByTenantIdAndName(tenantId, assetName));
}
@ApiOperation(value = "Get Customer Assets (getCustomerAssets)",
@@ -317,18 +298,14 @@ public class AssetController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(assetService.findAssetsByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
- } else {
- return checkNotNull(assetService.findAssetsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(assetService.findAssetsByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
+ } else {
+ return checkNotNull(assetService.findAssetsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -356,21 +333,17 @@ public class AssetController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
- } else if (assetProfileId != null && assetProfileId.length() > 0) {
- AssetProfileId profileId = new AssetProfileId(toUUID(assetProfileId));
- return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerIdAndAssetProfileId(tenantId, customerId, profileId, pageLink));
- } else {
- return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
+ } else if (assetProfileId != null && assetProfileId.length() > 0) {
+ AssetProfileId profileId = new AssetProfileId(toUUID(assetProfileId));
+ return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerIdAndAssetProfileId(tenantId, customerId, profileId, pageLink));
+ } else {
+ return checkNotNull(assetService.findAssetInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -381,26 +354,22 @@ public class AssetController extends BaseController {
@ResponseBody
public List getAssetsByIds(
@ApiParam(value = "A list of assets ids, separated by comma ','")
- @RequestParam("assetIds") String[] strAssetIds) throws ThingsboardException {
+ @RequestParam("assetIds") String[] strAssetIds) throws ThingsboardException, ExecutionException, InterruptedException {
checkArrayParameter("assetIds", strAssetIds);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- CustomerId customerId = user.getCustomerId();
- List assetIds = new ArrayList<>();
- for (String strAssetId : strAssetIds) {
- assetIds.add(new AssetId(toUUID(strAssetId)));
- }
- ListenableFuture> assets;
- if (customerId == null || customerId.isNullUid()) {
- assets = assetService.findAssetsByTenantIdAndIdsAsync(tenantId, assetIds);
- } else {
- assets = assetService.findAssetsByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, assetIds);
- }
- return checkNotNull(assets.get());
- } catch (Exception e) {
- throw handleException(e);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ CustomerId customerId = user.getCustomerId();
+ List assetIds = new ArrayList<>();
+ for (String strAssetId : strAssetIds) {
+ assetIds.add(new AssetId(toUUID(strAssetId)));
}
+ ListenableFuture> assets;
+ if (customerId == null || customerId.isNullUid()) {
+ assets = assetService.findAssetsByTenantIdAndIdsAsync(tenantId, assetIds);
+ } else {
+ assets = assetService.findAssetsByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, assetIds);
+ }
+ return checkNotNull(assets.get());
}
@ApiOperation(value = "Find related assets (findByQuery)",
@@ -410,25 +379,21 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/assets", method = RequestMethod.POST)
@ResponseBody
- public List findByQuery(@RequestBody AssetSearchQuery query) throws ThingsboardException {
+ public List findByQuery(@RequestBody AssetSearchQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getAssetTypes());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- List assets = checkNotNull(assetService.findAssetsByQuery(getTenantId(), query).get());
- assets = assets.stream().filter(asset -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- return assets;
- } catch (Exception e) {
- throw handleException(e);
- }
+ List assets = checkNotNull(assetService.findAssetsByQuery(getTenantId(), query).get());
+ assets = assets.stream().filter(asset -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ return assets;
}
@ApiOperation(value = "Get Asset Types (getAssetTypes)",
@@ -436,15 +401,11 @@ public class AssetController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/asset/types", method = RequestMethod.GET)
@ResponseBody
- public List getAssetTypes() throws ThingsboardException {
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- ListenableFuture> assetTypes = assetService.findAssetTypesByTenantId(tenantId);
- return checkNotNull(assetTypes.get());
- } catch (Exception e) {
- throw handleException(e);
- }
+ public List getAssetTypes() throws ThingsboardException, ExecutionException, InterruptedException {
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ ListenableFuture> assetTypes = assetService.findAssetTypesByTenantId(tenantId);
+ return checkNotNull(assetTypes.get());
}
@ApiOperation(value = "Assign asset to edge (assignAssetToEdge)",
@@ -520,33 +481,29 @@ public class AssetController extends BaseController {
@ApiParam(value = "Timestamp. Assets with creation time after it won't be queried")
@RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- checkEdgeId(edgeId, Operation.READ);
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- PageData nonFilteredResult;
- if (type != null && type.trim().length() > 0) {
- nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
- } else {
- nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
- }
- List filteredAssets = nonFilteredResult.getData().stream().filter(asset -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- PageData filteredResult = new PageData<>(filteredAssets,
- nonFilteredResult.getTotalPages(),
- nonFilteredResult.getTotalElements(),
- nonFilteredResult.hasNext());
- return checkNotNull(filteredResult);
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ checkEdgeId(edgeId, Operation.READ);
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ PageData nonFilteredResult;
+ if (type != null && type.trim().length() > 0) {
+ nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
+ } else {
+ nonFilteredResult = assetService.findAssetsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
+ List filteredAssets = nonFilteredResult.getData().stream().filter(asset -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.ASSET, Operation.READ, asset.getId(), asset);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ PageData filteredResult = new PageData<>(filteredAssets,
+ nonFilteredResult.getTotalPages(),
+ nonFilteredResult.getTotalElements(),
+ nonFilteredResult.hasNext());
+ return checkNotNull(filteredResult);
}
@ApiOperation(value = "Import the bulk of assets (processAssetsBulkImport)",
diff --git a/application/src/main/java/org/thingsboard/server/controller/AssetProfileController.java b/application/src/main/java/org/thingsboard/server/controller/AssetProfileController.java
index 6e96f6985b..ebae4169ce 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AssetProfileController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AssetProfileController.java
@@ -78,12 +78,8 @@ public class AssetProfileController extends BaseController {
@ApiParam(value = ASSET_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_PROFILE_ID) String strAssetProfileId) throws ThingsboardException {
checkParameter(ASSET_PROFILE_ID, strAssetProfileId);
- try {
- AssetProfileId assetProfileId = new AssetProfileId(toUUID(strAssetProfileId));
- return checkAssetProfileId(assetProfileId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ AssetProfileId assetProfileId = new AssetProfileId(toUUID(strAssetProfileId));
+ return checkAssetProfileId(assetProfileId, Operation.READ);
}
@ApiOperation(value = "Get Asset Profile Info (getAssetProfileInfoById)",
@@ -97,12 +93,8 @@ public class AssetProfileController extends BaseController {
@ApiParam(value = ASSET_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(ASSET_PROFILE_ID) String strAssetProfileId) throws ThingsboardException {
checkParameter(ASSET_PROFILE_ID, strAssetProfileId);
- try {
- AssetProfileId assetProfileId = new AssetProfileId(toUUID(strAssetProfileId));
- return new AssetProfileInfo(checkAssetProfileId(assetProfileId, Operation.READ));
- } catch (Exception e) {
- throw handleException(e);
- }
+ AssetProfileId assetProfileId = new AssetProfileId(toUUID(strAssetProfileId));
+ return new AssetProfileInfo(checkAssetProfileId(assetProfileId, Operation.READ));
}
@ApiOperation(value = "Get Default Asset Profile (getDefaultAssetProfileInfo)",
@@ -113,11 +105,7 @@ public class AssetProfileController extends BaseController {
@RequestMapping(value = "/assetProfileInfo/default", method = RequestMethod.GET)
@ResponseBody
public AssetProfileInfo getDefaultAssetProfileInfo() throws ThingsboardException {
- try {
- return checkNotNull(assetProfileService.findDefaultAssetProfileInfo(getTenantId()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(assetProfileService.findDefaultAssetProfileInfo(getTenantId()));
}
@ApiOperation(value = "Create Or Update Asset Profile (saveAssetProfile)",
@@ -191,12 +179,8 @@ public class AssetProfileController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(assetProfileService.findAssetProfiles(getTenantId(), pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(assetProfileService.findAssetProfiles(getTenantId(), pageLink));
}
@ApiOperation(value = "Get Asset Profile infos (getAssetProfileInfos)",
@@ -217,11 +201,7 @@ public class AssetProfileController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(assetProfileService.findAssetProfileInfos(getTenantId(), pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(assetProfileService.findAssetProfileInfos(getTenantId(), pageLink));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/AuditLogController.java b/application/src/main/java/org/thingsboard/server/controller/AuditLogController.java
index 805d0209ec..387f0d014b 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AuditLogController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AuditLogController.java
@@ -97,15 +97,11 @@ public class AuditLogController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = AUDIT_LOG_QUERY_ACTION_TYPES_DESCRIPTION)
@RequestParam(name = "actionTypes", required = false) String actionTypesStr) throws ThingsboardException {
- try {
- checkParameter("CustomerId", strCustomerId);
- TenantId tenantId = getCurrentUser().getTenantId();
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- List actionTypes = parseActionTypesStr(actionTypesStr);
- return checkNotNull(auditLogService.findAuditLogsByTenantIdAndCustomerId(tenantId, new CustomerId(UUID.fromString(strCustomerId)), actionTypes, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ checkParameter("CustomerId", strCustomerId);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ List actionTypes = parseActionTypesStr(actionTypesStr);
+ return checkNotNull(auditLogService.findAuditLogsByTenantIdAndCustomerId(tenantId, new CustomerId(UUID.fromString(strCustomerId)), actionTypes, pageLink));
}
@ApiOperation(value = "Get audit logs by user id (getAuditLogsByUserId)",
@@ -135,15 +131,11 @@ public class AuditLogController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = AUDIT_LOG_QUERY_ACTION_TYPES_DESCRIPTION)
@RequestParam(name = "actionTypes", required = false) String actionTypesStr) throws ThingsboardException {
- try {
- checkParameter("UserId", strUserId);
- TenantId tenantId = getCurrentUser().getTenantId();
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- List actionTypes = parseActionTypesStr(actionTypesStr);
- return checkNotNull(auditLogService.findAuditLogsByTenantIdAndUserId(tenantId, new UserId(UUID.fromString(strUserId)), actionTypes, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ checkParameter("UserId", strUserId);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ List actionTypes = parseActionTypesStr(actionTypesStr);
+ return checkNotNull(auditLogService.findAuditLogsByTenantIdAndUserId(tenantId, new UserId(UUID.fromString(strUserId)), actionTypes, pageLink));
}
@ApiOperation(value = "Get audit logs by entity id (getAuditLogsByEntityId)",
@@ -176,16 +168,12 @@ public class AuditLogController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = AUDIT_LOG_QUERY_ACTION_TYPES_DESCRIPTION)
@RequestParam(name = "actionTypes", required = false) String actionTypesStr) throws ThingsboardException {
- try {
- checkParameter("EntityId", strEntityId);
- checkParameter("EntityType", strEntityType);
- TenantId tenantId = getCurrentUser().getTenantId();
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- List actionTypes = parseActionTypesStr(actionTypesStr);
- return checkNotNull(auditLogService.findAuditLogsByTenantIdAndEntityId(tenantId, EntityIdFactory.getByTypeAndId(strEntityType, strEntityId), actionTypes, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ checkParameter("EntityId", strEntityId);
+ checkParameter("EntityType", strEntityType);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ List actionTypes = parseActionTypesStr(actionTypesStr);
+ return checkNotNull(auditLogService.findAuditLogsByTenantIdAndEntityId(tenantId, EntityIdFactory.getByTypeAndId(strEntityType, strEntityId), actionTypes, pageLink));
}
@ApiOperation(value = "Get all audit logs (getAuditLogs)",
@@ -212,14 +200,10 @@ public class AuditLogController extends BaseController {
@RequestParam(required = false) Long endTime,
@ApiParam(value = AUDIT_LOG_QUERY_ACTION_TYPES_DESCRIPTION)
@RequestParam(name = "actionTypes", required = false) String actionTypesStr) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- List actionTypes = parseActionTypesStr(actionTypesStr);
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- return checkNotNull(auditLogService.findAuditLogsByTenantId(tenantId, actionTypes, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ List actionTypes = parseActionTypesStr(actionTypesStr);
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ return checkNotNull(auditLogService.findAuditLogsByTenantId(tenantId, actionTypes, pageLink));
}
private List parseActionTypesStr(String actionTypesStr) {
diff --git a/application/src/main/java/org/thingsboard/server/controller/AuthController.java b/application/src/main/java/org/thingsboard/server/controller/AuthController.java
index 113c292380..32b997c21f 100644
--- a/application/src/main/java/org/thingsboard/server/controller/AuthController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/AuthController.java
@@ -92,12 +92,8 @@ public class AuthController extends BaseController {
@RequestMapping(value = "/auth/user", method = RequestMethod.GET)
public @ResponseBody
User getUser() throws ThingsboardException {
- try {
- SecurityUser securityUser = getCurrentUser();
- return userService.findUserById(securityUser.getTenantId(), securityUser.getId());
- } catch (Exception e) {
- throw handleException(e);
- }
+ SecurityUser securityUser = getCurrentUser();
+ return userService.findUserById(securityUser.getTenantId(), securityUser.getId());
}
@ApiOperation(value = "Logout (logout)",
@@ -117,31 +113,27 @@ public class AuthController extends BaseController {
public ObjectNode changePassword(
@ApiParam(value = "Change Password Request")
@RequestBody ChangePasswordRequest changePasswordRequest) throws ThingsboardException {
- try {
- String currentPassword = changePasswordRequest.getCurrentPassword();
- String newPassword = changePasswordRequest.getNewPassword();
- SecurityUser securityUser = getCurrentUser();
- UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
- if (!passwordEncoder.matches(currentPassword, userCredentials.getPassword())) {
- throw new ThingsboardException("Current password doesn't match!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
- }
- systemSecurityService.validatePassword(securityUser.getTenantId(), newPassword, userCredentials);
- if (passwordEncoder.matches(newPassword, userCredentials.getPassword())) {
- throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
- }
- userCredentials.setPassword(passwordEncoder.encode(newPassword));
- userService.replaceUserCredentials(securityUser.getTenantId(), userCredentials);
+ String currentPassword = changePasswordRequest.getCurrentPassword();
+ String newPassword = changePasswordRequest.getNewPassword();
+ SecurityUser securityUser = getCurrentUser();
+ UserCredentials userCredentials = userService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
+ if (!passwordEncoder.matches(currentPassword, userCredentials.getPassword())) {
+ throw new ThingsboardException("Current password doesn't match!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ systemSecurityService.validatePassword(securityUser.getTenantId(), newPassword, userCredentials);
+ if (passwordEncoder.matches(newPassword, userCredentials.getPassword())) {
+ throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ userCredentials.setPassword(passwordEncoder.encode(newPassword));
+ userService.replaceUserCredentials(securityUser.getTenantId(), userCredentials);
- sendEntityNotificationMsg(getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED);
+ sendEntityNotificationMsg(getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED);
- eventPublisher.publishEvent(new UserCredentialsInvalidationEvent(securityUser.getId()));
- ObjectNode response = JacksonUtil.newObjectNode();
- response.put("token", tokenFactory.createAccessJwtToken(securityUser).getToken());
- response.put("refreshToken", tokenFactory.createRefreshToken(securityUser).getToken());
- return response;
- } catch (Exception e) {
- throw handleException(e);
- }
+ eventPublisher.publishEvent(new UserCredentialsInvalidationEvent(securityUser.getId()));
+ ObjectNode response = JacksonUtil.newObjectNode();
+ response.put("token", tokenFactory.createAccessJwtToken(securityUser).getToken());
+ response.put("refreshToken", tokenFactory.createRefreshToken(securityUser).getToken());
+ return response;
}
@ApiOperation(value = "Get the current User password policy (getUserPasswordPolicy)",
@@ -149,13 +141,9 @@ public class AuthController extends BaseController {
@RequestMapping(value = "/noauth/userPasswordPolicy", method = RequestMethod.GET)
@ResponseBody
public UserPasswordPolicy getUserPasswordPolicy() throws ThingsboardException {
- try {
- SecuritySettings securitySettings =
- checkNotNull(systemSecurityService.getSecuritySettings(TenantId.SYS_TENANT_ID));
- return securitySettings.getPasswordPolicy();
- } catch (Exception e) {
- throw handleException(e);
- }
+ SecuritySettings securitySettings =
+ checkNotNull(systemSecurityService.getSecuritySettings(TenantId.SYS_TENANT_ID));
+ return securitySettings.getPasswordPolicy();
}
@ApiOperation(value = "Check Activate User Token (checkActivateToken)",
@@ -255,34 +243,30 @@ public class AuthController extends BaseController {
@RequestBody ActivateUserRequest activateRequest,
@RequestParam(required = false, defaultValue = "true") boolean sendActivationMail,
HttpServletRequest request) throws ThingsboardException {
- try {
- String activateToken = activateRequest.getActivateToken();
- String password = activateRequest.getPassword();
- systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, null);
- String encodedPassword = passwordEncoder.encode(password);
- UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, activateToken, encodedPassword);
- User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
- UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
- SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
- userService.setUserCredentialsEnabled(user.getTenantId(), user.getId(), true);
- String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
- String loginUrl = String.format("%s/login", baseUrl);
- String email = user.getEmail();
+ String activateToken = activateRequest.getActivateToken();
+ String password = activateRequest.getPassword();
+ systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, null);
+ String encodedPassword = passwordEncoder.encode(password);
+ UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, activateToken, encodedPassword);
+ User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
+ UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
+ SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal);
+ userService.setUserCredentialsEnabled(user.getTenantId(), user.getId(), true);
+ String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
+ String loginUrl = String.format("%s/login", baseUrl);
+ String email = user.getEmail();
- if (sendActivationMail) {
- try {
- mailService.sendAccountActivatedEmail(loginUrl, email);
- } catch (Exception e) {
- log.info("Unable to send account activation email [{}]", e.getMessage());
- }
+ if (sendActivationMail) {
+ try {
+ mailService.sendAccountActivatedEmail(loginUrl, email);
+ } catch (Exception e) {
+ log.info("Unable to send account activation email [{}]", e.getMessage());
}
+ }
- sendEntityNotificationMsg(user.getTenantId(), user.getId(), EdgeEventActionType.CREDENTIALS_UPDATED);
+ sendEntityNotificationMsg(user.getTenantId(), user.getId(), EdgeEventActionType.CREDENTIALS_UPDATED);
- return tokenFactory.createTokenPair(securityUser);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return tokenFactory.createTokenPair(securityUser);
}
@ApiOperation(value = "Reset password (resetPassword)",
@@ -296,46 +280,38 @@ public class AuthController extends BaseController {
@ApiParam(value = "Reset password request.")
@RequestBody ResetPasswordRequest resetPasswordRequest,
HttpServletRequest request) throws ThingsboardException {
- try {
- String resetToken = resetPasswordRequest.getResetToken();
- String password = resetPasswordRequest.getPassword();
- UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
- if (userCredentials != null) {
- systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, userCredentials);
- if (passwordEncoder.matches(password, userCredentials.getPassword())) {
- throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
- }
- String encodedPassword = passwordEncoder.encode(password);
- userCredentials.setPassword(encodedPassword);
- userCredentials.setResetToken(null);
- userCredentials = userService.replaceUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
- User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
- UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
- SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
- String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
- String loginUrl = String.format("%s/login", baseUrl);
- String email = user.getEmail();
- mailService.sendPasswordWasResetEmail(loginUrl, email);
+ String resetToken = resetPasswordRequest.getResetToken();
+ String password = resetPasswordRequest.getPassword();
+ UserCredentials userCredentials = userService.findUserCredentialsByResetToken(TenantId.SYS_TENANT_ID, resetToken);
+ if (userCredentials != null) {
+ systemSecurityService.validatePassword(TenantId.SYS_TENANT_ID, password, userCredentials);
+ if (passwordEncoder.matches(password, userCredentials.getPassword())) {
+ throw new ThingsboardException("New password should be different from existing!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ String encodedPassword = passwordEncoder.encode(password);
+ userCredentials.setPassword(encodedPassword);
+ userCredentials.setResetToken(null);
+ userCredentials = userService.replaceUserCredentials(TenantId.SYS_TENANT_ID, userCredentials);
+ User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
+ UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
+ SecurityUser securityUser = new SecurityUser(user, userCredentials.isEnabled(), principal);
+ String baseUrl = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), request);
+ String loginUrl = String.format("%s/login", baseUrl);
+ String email = user.getEmail();
+ mailService.sendPasswordWasResetEmail(loginUrl, email);
- eventPublisher.publishEvent(new UserCredentialsInvalidationEvent(securityUser.getId()));
+ eventPublisher.publishEvent(new UserCredentialsInvalidationEvent(securityUser.getId()));
- return tokenFactory.createTokenPair(securityUser);
- } else {
- throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
- }
- } catch (Exception e) {
- throw handleException(e);
+ return tokenFactory.createTokenPair(securityUser);
+ } else {
+ throw new ThingsboardException("Invalid reset token!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
}
private void logLogoutAction(HttpServletRequest request) throws ThingsboardException {
- try {
- var user = getCurrentUser();
- systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(request), ActionType.LOGOUT, null);
- eventPublisher.publishEvent(new UserSessionInvalidationEvent(user.getSessionId()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ var user = getCurrentUser();
+ systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(request), ActionType.LOGOUT, null);
+ eventPublisher.publishEvent(new UserSessionInvalidationEvent(user.getSessionId()));
}
private TbRateLimits getTbRateLimits(UserId userId) {
diff --git a/application/src/main/java/org/thingsboard/server/controller/BaseController.java b/application/src/main/java/org/thingsboard/server/controller/BaseController.java
index a68955d9b4..34f065d500 100644
--- a/application/src/main/java/org/thingsboard/server/controller/BaseController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/BaseController.java
@@ -103,6 +103,7 @@ import org.thingsboard.server.common.data.rpc.Rpc;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.rule.RuleChainType;
import org.thingsboard.server.common.data.rule.RuleNode;
+import org.thingsboard.server.common.data.settings.UserDashboardAction;
import org.thingsboard.server.common.data.util.ThrowingBiFunction;
import org.thingsboard.server.common.data.widget.WidgetTypeDetails;
import org.thingsboard.server.common.data.widget.WidgetsBundle;
@@ -146,6 +147,7 @@ import org.thingsboard.server.service.component.ComponentDiscoveryService;
import org.thingsboard.server.service.edge.instructions.EdgeInstallService;
import org.thingsboard.server.service.edge.rpc.EdgeRpcService;
import org.thingsboard.server.service.entitiy.TbNotificationEntityService;
+import org.thingsboard.server.service.entitiy.user.TbUserSettingsService;
import org.thingsboard.server.service.ota.OtaPackageStateService;
import org.thingsboard.server.service.profile.TbAssetProfileCache;
import org.thingsboard.server.service.profile.TbDeviceProfileCache;
@@ -168,6 +170,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
+import java.util.function.Function;
import java.util.stream.Collectors;
import static org.thingsboard.server.common.data.StringUtils.isNotEmpty;
@@ -202,7 +205,7 @@ public abstract class BaseController {
protected UserService userService;
@Autowired
- protected UserSettingsService userSettingsService;
+ protected TbUserSettingsService userSettingsService;
@Autowired
protected DeviceService deviceService;
@@ -445,6 +448,14 @@ public abstract class BaseController {
}
}
+ protected T checkEnumParameter(String name, String param, Function valueOf) throws ThingsboardException {
+ try {
+ return valueOf.apply(param.toUpperCase());
+ } catch (IllegalArgumentException e) {
+ throw new ThingsboardException(name + " \"" + param + "\" is not supported!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
+ }
+ }
+
UUID toUUID(String id) throws ThingsboardException {
try {
return UUID.fromString(id);
diff --git a/application/src/main/java/org/thingsboard/server/controller/ComponentDescriptorController.java b/application/src/main/java/org/thingsboard/server/controller/ComponentDescriptorController.java
index 7d461fc764..33a4edfbe0 100644
--- a/application/src/main/java/org/thingsboard/server/controller/ComponentDescriptorController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/ComponentDescriptorController.java
@@ -57,11 +57,7 @@ public class ComponentDescriptorController extends BaseController {
@ApiParam(value = "Component Descriptor class name", required = true)
@PathVariable("componentDescriptorClazz") String strComponentDescriptorClazz) throws ThingsboardException {
checkParameter("strComponentDescriptorClazz", strComponentDescriptorClazz);
- try {
- return checkComponentDescriptorByClazz(strComponentDescriptorClazz);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkComponentDescriptorByClazz(strComponentDescriptorClazz);
}
@ApiOperation(value = "Get Component Descriptors (getComponentDescriptorsByType)",
@@ -76,11 +72,7 @@ public class ComponentDescriptorController extends BaseController {
@ApiParam(value = "Type of the Rule Chain", allowableValues = "CORE,EDGE")
@RequestParam(value = "ruleChainType", required = false) String strRuleChainType) throws ThingsboardException {
checkParameter("componentType", strComponentType);
- try {
- return checkComponentDescriptorsByType(ComponentType.valueOf(strComponentType), getRuleChainType(strRuleChainType));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkComponentDescriptorsByType(ComponentType.valueOf(strComponentType), getRuleChainType(strRuleChainType));
}
@ApiOperation(value = "Get Component Descriptors (getComponentDescriptorsByTypes)",
@@ -95,15 +87,11 @@ public class ComponentDescriptorController extends BaseController {
@ApiParam(value = "Type of the Rule Chain", allowableValues = "CORE,EDGE")
@RequestParam(value = "ruleChainType", required = false) String strRuleChainType) throws ThingsboardException {
checkArrayParameter("componentTypes", strComponentTypes);
- try {
- Set componentTypes = new HashSet<>();
- for (String strComponentType : strComponentTypes) {
- componentTypes.add(ComponentType.valueOf(strComponentType));
- }
- return checkComponentDescriptorsByTypes(componentTypes, getRuleChainType(strRuleChainType));
- } catch (Exception e) {
- throw handleException(e);
+ Set componentTypes = new HashSet<>();
+ for (String strComponentType : strComponentTypes) {
+ componentTypes.add(ComponentType.valueOf(strComponentType));
}
+ return checkComponentDescriptorsByTypes(componentTypes, getRuleChainType(strRuleChainType));
}
private RuleChainType getRuleChainType(String strRuleChainType) {
diff --git a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java
index ef15199fa8..8156c72a41 100644
--- a/application/src/main/java/org/thingsboard/server/controller/CustomerController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/CustomerController.java
@@ -79,16 +79,12 @@ public class CustomerController extends BaseController {
@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
- try {
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- Customer customer = checkCustomerId(customerId, Operation.READ);
- if (!customer.getAdditionalInfo().isNull()) {
- processDashboardIdFromAdditionalInfo((ObjectNode) customer.getAdditionalInfo(), HOME_DASHBOARD);
- }
- return customer;
- } catch (Exception e) {
- throw handleException(e);
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ Customer customer = checkCustomerId(customerId, Operation.READ);
+ if (!customer.getAdditionalInfo().isNull()) {
+ processDashboardIdFromAdditionalInfo((ObjectNode) customer.getAdditionalInfo(), HOME_DASHBOARD);
}
+ return customer;
}
@@ -102,17 +98,13 @@ public class CustomerController extends BaseController {
@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
- try {
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- Customer customer = checkCustomerId(customerId, Operation.READ);
- ObjectMapper objectMapper = new ObjectMapper();
- ObjectNode infoObject = objectMapper.createObjectNode();
- infoObject.put("title", customer.getTitle());
- infoObject.put(IS_PUBLIC, customer.isPublic());
- return infoObject;
- } catch (Exception e) {
- throw handleException(e);
- }
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ Customer customer = checkCustomerId(customerId, Operation.READ);
+ ObjectMapper objectMapper = new ObjectMapper();
+ ObjectNode infoObject = objectMapper.createObjectNode();
+ infoObject.put("title", customer.getTitle());
+ infoObject.put(IS_PUBLIC, customer.isPublic());
+ return infoObject;
}
@ApiOperation(value = "Get Customer Title (getCustomerTitleById)",
@@ -125,13 +117,9 @@ public class CustomerController extends BaseController {
@ApiParam(value = CUSTOMER_ID_PARAM_DESCRIPTION)
@PathVariable(CUSTOMER_ID) String strCustomerId) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
- try {
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- Customer customer = checkCustomerId(customerId, Operation.READ);
- return customer.getTitle();
- } catch (Exception e) {
- throw handleException(e);
- }
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ Customer customer = checkCustomerId(customerId, Operation.READ);
+ return customer.getTitle();
}
@ApiOperation(value = "Create or update Customer (saveCustomer)",
@@ -182,13 +170,9 @@ public class CustomerController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(customerService.findCustomersByTenantId(tenantId, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(customerService.findCustomersByTenantId(tenantId, pageLink));
}
@ApiOperation(value = "Get Tenant Customer by Customer title (getTenantCustomer)",
@@ -199,11 +183,7 @@ public class CustomerController extends BaseController {
public Customer getTenantCustomer(
@ApiParam(value = "A string value representing the Customer title.")
@RequestParam String customerTitle) throws ThingsboardException {
- try {
TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(customerService.findCustomerByTenantIdAndTitle(tenantId, customerTitle), "Customer with title [" + customerTitle + "] is not found");
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(customerService.findCustomerByTenantIdAndTitle(tenantId, customerTitle), "Customer with title [" + customerTitle + "] is not found");
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java
index a6381bebcb..d4e5169e7e 100644
--- a/application/src/main/java/org/thingsboard/server/controller/DashboardController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/DashboardController.java
@@ -140,12 +140,8 @@ public class DashboardController extends BaseController {
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
- try {
- DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
- return checkDashboardInfoId(dashboardId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
+ return checkDashboardInfoId(dashboardId, Operation.READ);
}
@ApiOperation(value = "Get Dashboard (getDashboardById)",
@@ -159,12 +155,8 @@ public class DashboardController extends BaseController {
@ApiParam(value = DASHBOARD_ID_PARAM_DESCRIPTION)
@PathVariable(DASHBOARD_ID) String strDashboardId) throws ThingsboardException {
checkParameter(DASHBOARD_ID, strDashboardId);
- try {
- DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
- return checkDashboardId(dashboardId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
+ return checkDashboardId(dashboardId, Operation.READ);
}
@ApiOperation(value = "Create Or Update Dashboard (saveDashboard)",
@@ -362,14 +354,10 @@ public class DashboardController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId));
- checkTenantId(tenantId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(dashboardService.findDashboardsByTenantId(tenantId, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = TenantId.fromUUID(toUUID(strTenantId));
+ checkTenantId(tenantId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(dashboardService.findDashboardsByTenantId(tenantId, pageLink));
}
@ApiOperation(value = "Get Tenant Dashboards (getTenantDashboards)",
@@ -392,16 +380,12 @@ public class DashboardController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (mobile != null && mobile) {
- return checkNotNull(dashboardService.findMobileDashboardsByTenantId(tenantId, pageLink));
- } else {
- return checkNotNull(dashboardService.findDashboardsByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (mobile != null && mobile) {
+ return checkNotNull(dashboardService.findMobileDashboardsByTenantId(tenantId, pageLink));
+ } else {
+ return checkNotNull(dashboardService.findDashboardsByTenantId(tenantId, pageLink));
}
}
@@ -428,18 +412,14 @@ public class DashboardController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (mobile != null && mobile) {
- return checkNotNull(dashboardService.findMobileDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- } else {
- return checkNotNull(dashboardService.findDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (mobile != null && mobile) {
+ return checkNotNull(dashboardService.findMobileDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
+ } else {
+ return checkNotNull(dashboardService.findDashboardsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -453,31 +433,27 @@ public class DashboardController extends BaseController {
@RequestMapping(value = "/dashboard/home", method = RequestMethod.GET)
@ResponseBody
public HomeDashboard getHomeDashboard() throws ThingsboardException {
- try {
- SecurityUser securityUser = getCurrentUser();
- if (securityUser.isSystemAdmin()) {
- return null;
+ SecurityUser securityUser = getCurrentUser();
+ if (securityUser.isSystemAdmin()) {
+ return null;
+ }
+ User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
+ JsonNode additionalInfo = user.getAdditionalInfo();
+ HomeDashboard homeDashboard;
+ homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
+ if (homeDashboard == null) {
+ if (securityUser.isCustomerUser()) {
+ Customer customer = customerService.findCustomerById(securityUser.getTenantId(), securityUser.getCustomerId());
+ additionalInfo = customer.getAdditionalInfo();
+ homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
}
- User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
- JsonNode additionalInfo = user.getAdditionalInfo();
- HomeDashboard homeDashboard;
- homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
if (homeDashboard == null) {
- if (securityUser.isCustomerUser()) {
- Customer customer = customerService.findCustomerById(securityUser.getTenantId(), securityUser.getCustomerId());
- additionalInfo = customer.getAdditionalInfo();
- homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
- }
- if (homeDashboard == null) {
- Tenant tenant = tenantService.findTenantById(securityUser.getTenantId());
- additionalInfo = tenant.getAdditionalInfo();
- homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
- }
+ Tenant tenant = tenantService.findTenantById(securityUser.getTenantId());
+ additionalInfo = tenant.getAdditionalInfo();
+ homeDashboard = extractHomeDashboardFromAdditionalInfo(additionalInfo);
}
- return homeDashboard;
- } catch (Exception e) {
- throw handleException(e);
}
+ return homeDashboard;
}
@ApiOperation(value = "Get Home Dashboard Info (getHomeDashboardInfo)",
@@ -490,31 +466,27 @@ public class DashboardController extends BaseController {
@RequestMapping(value = "/dashboard/home/info", method = RequestMethod.GET)
@ResponseBody
public HomeDashboardInfo getHomeDashboardInfo() throws ThingsboardException {
- try {
- SecurityUser securityUser = getCurrentUser();
- if (securityUser.isSystemAdmin()) {
- return null;
+ SecurityUser securityUser = getCurrentUser();
+ if (securityUser.isSystemAdmin()) {
+ return null;
+ }
+ User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
+ JsonNode additionalInfo = user.getAdditionalInfo();
+ HomeDashboardInfo homeDashboardInfo;
+ homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
+ if (homeDashboardInfo == null) {
+ if (securityUser.isCustomerUser()) {
+ Customer customer = customerService.findCustomerById(securityUser.getTenantId(), securityUser.getCustomerId());
+ additionalInfo = customer.getAdditionalInfo();
+ homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
}
- User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
- JsonNode additionalInfo = user.getAdditionalInfo();
- HomeDashboardInfo homeDashboardInfo;
- homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
if (homeDashboardInfo == null) {
- if (securityUser.isCustomerUser()) {
- Customer customer = customerService.findCustomerById(securityUser.getTenantId(), securityUser.getCustomerId());
- additionalInfo = customer.getAdditionalInfo();
- homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
- }
- if (homeDashboardInfo == null) {
- Tenant tenant = tenantService.findTenantById(securityUser.getTenantId());
- additionalInfo = tenant.getAdditionalInfo();
- homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
- }
+ Tenant tenant = tenantService.findTenantById(securityUser.getTenantId());
+ additionalInfo = tenant.getAdditionalInfo();
+ homeDashboardInfo = extractHomeDashboardInfoFromAdditionalInfo(additionalInfo);
}
- return homeDashboardInfo;
- } catch (Exception e) {
- throw handleException(e);
}
+ return homeDashboardInfo;
}
@ApiOperation(value = "Get Tenant Home Dashboard Info (getTenantHomeDashboardInfo)",
@@ -525,22 +497,18 @@ public class DashboardController extends BaseController {
@RequestMapping(value = "/tenant/dashboard/home/info", method = RequestMethod.GET)
@ResponseBody
public HomeDashboardInfo getTenantHomeDashboardInfo() throws ThingsboardException {
- try {
- Tenant tenant = tenantService.findTenantById(getTenantId());
- JsonNode additionalInfo = tenant.getAdditionalInfo();
- DashboardId dashboardId = null;
- boolean hideDashboardToolbar = true;
- if (additionalInfo != null && additionalInfo.has(HOME_DASHBOARD_ID) && !additionalInfo.get(HOME_DASHBOARD_ID).isNull()) {
- String strDashboardId = additionalInfo.get(HOME_DASHBOARD_ID).asText();
- dashboardId = new DashboardId(toUUID(strDashboardId));
- if (additionalInfo.has(HOME_DASHBOARD_HIDE_TOOLBAR)) {
- hideDashboardToolbar = additionalInfo.get(HOME_DASHBOARD_HIDE_TOOLBAR).asBoolean();
- }
+ Tenant tenant = tenantService.findTenantById(getTenantId());
+ JsonNode additionalInfo = tenant.getAdditionalInfo();
+ DashboardId dashboardId = null;
+ boolean hideDashboardToolbar = true;
+ if (additionalInfo != null && additionalInfo.has(HOME_DASHBOARD_ID) && !additionalInfo.get(HOME_DASHBOARD_ID).isNull()) {
+ String strDashboardId = additionalInfo.get(HOME_DASHBOARD_ID).asText();
+ dashboardId = new DashboardId(toUUID(strDashboardId));
+ if (additionalInfo.has(HOME_DASHBOARD_HIDE_TOOLBAR)) {
+ hideDashboardToolbar = additionalInfo.get(HOME_DASHBOARD_HIDE_TOOLBAR).asBoolean();
}
- return new HomeDashboardInfo(dashboardId, hideDashboardToolbar);
- } catch (Exception e) {
- throw handleException(e);
}
+ return new HomeDashboardInfo(dashboardId, hideDashboardToolbar);
}
@ApiOperation(value = "Update Tenant Home Dashboard Info (getTenantHomeDashboardInfo)",
@@ -554,27 +522,23 @@ public class DashboardController extends BaseController {
@ApiParam(value = "A JSON object that represents home dashboard id and other parameters", required = true)
@RequestBody HomeDashboardInfo homeDashboardInfo) throws ThingsboardException {
- try {
- if (homeDashboardInfo.getDashboardId() != null) {
- checkDashboardId(homeDashboardInfo.getDashboardId(), Operation.READ);
- }
- Tenant tenant = tenantService.findTenantById(getTenantId());
- JsonNode additionalInfo = tenant.getAdditionalInfo();
- if (additionalInfo == null || !(additionalInfo instanceof ObjectNode)) {
- additionalInfo = JacksonUtil.OBJECT_MAPPER.createObjectNode();
- }
- if (homeDashboardInfo.getDashboardId() != null) {
- ((ObjectNode) additionalInfo).put(HOME_DASHBOARD_ID, homeDashboardInfo.getDashboardId().getId().toString());
- ((ObjectNode) additionalInfo).put(HOME_DASHBOARD_HIDE_TOOLBAR, homeDashboardInfo.isHideDashboardToolbar());
- } else {
- ((ObjectNode) additionalInfo).remove(HOME_DASHBOARD_ID);
- ((ObjectNode) additionalInfo).remove(HOME_DASHBOARD_HIDE_TOOLBAR);
- }
- tenant.setAdditionalInfo(additionalInfo);
- tenantService.saveTenant(tenant);
- } catch (Exception e) {
- throw handleException(e);
+ if (homeDashboardInfo.getDashboardId() != null) {
+ checkDashboardId(homeDashboardInfo.getDashboardId(), Operation.READ);
+ }
+ Tenant tenant = tenantService.findTenantById(getTenantId());
+ JsonNode additionalInfo = tenant.getAdditionalInfo();
+ if (additionalInfo == null || !(additionalInfo instanceof ObjectNode)) {
+ additionalInfo = JacksonUtil.OBJECT_MAPPER.createObjectNode();
+ }
+ if (homeDashboardInfo.getDashboardId() != null) {
+ ((ObjectNode) additionalInfo).put(HOME_DASHBOARD_ID, homeDashboardInfo.getDashboardId().getId().toString());
+ ((ObjectNode) additionalInfo).put(HOME_DASHBOARD_HIDE_TOOLBAR, homeDashboardInfo.isHideDashboardToolbar());
+ } else {
+ ((ObjectNode) additionalInfo).remove(HOME_DASHBOARD_ID);
+ ((ObjectNode) additionalInfo).remove(HOME_DASHBOARD_HIDE_TOOLBAR);
}
+ tenant.setAdditionalInfo(additionalInfo);
+ tenantService.saveTenant(tenant);
}
private HomeDashboardInfo extractHomeDashboardInfoFromAdditionalInfo(JsonNode additionalInfo) {
@@ -681,28 +645,24 @@ public class DashboardController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("edgeId", strEdgeId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- checkEdgeId(edgeId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- PageData nonFilteredResult = dashboardService.findDashboardsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
- List filteredDashboards = nonFilteredResult.getData().stream().filter(dashboardInfo -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.DASHBOARD, Operation.READ, dashboardInfo.getId(), dashboardInfo);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- PageData filteredResult = new PageData<>(filteredDashboards,
- nonFilteredResult.getTotalPages(),
- nonFilteredResult.getTotalElements(),
- nonFilteredResult.hasNext());
- return checkNotNull(filteredResult);
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ checkEdgeId(edgeId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ PageData nonFilteredResult = dashboardService.findDashboardsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
+ List filteredDashboards = nonFilteredResult.getData().stream().filter(dashboardInfo -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.DASHBOARD, Operation.READ, dashboardInfo.getId(), dashboardInfo);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ PageData filteredResult = new PageData<>(filteredDashboards,
+ nonFilteredResult.getTotalPages(),
+ nonFilteredResult.getTotalElements(),
+ nonFilteredResult.hasNext());
+ return checkNotNull(filteredResult);
}
private Set customerIdFromStr(String[] strCustomerIds) {
diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java
index 33eb5d1975..0e6e19ad8d 100644
--- a/application/src/main/java/org/thingsboard/server/controller/DeviceController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/DeviceController.java
@@ -77,6 +77,7 @@ import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.CUSTOMER_AUTHORITY_PARAGRAPH;
@@ -308,16 +309,12 @@ public class DeviceController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(deviceService.findDevicesByTenantIdAndType(tenantId, type, pageLink));
- } else {
- return checkNotNull(deviceService.findDevicesByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(deviceService.findDevicesByTenantIdAndType(tenantId, type, pageLink));
+ } else {
+ return checkNotNull(deviceService.findDevicesByTenantId(tenantId, pageLink));
}
}
@@ -343,19 +340,15 @@ public class DeviceController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder
) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(deviceService.findDeviceInfosByTenantIdAndType(tenantId, type, pageLink));
- } else if (deviceProfileId != null && deviceProfileId.length() > 0) {
- DeviceProfileId profileId = new DeviceProfileId(toUUID(deviceProfileId));
- return checkNotNull(deviceService.findDeviceInfosByTenantIdAndDeviceProfileId(tenantId, profileId, pageLink));
- } else {
- return checkNotNull(deviceService.findDeviceInfosByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(deviceService.findDeviceInfosByTenantIdAndType(tenantId, type, pageLink));
+ } else if (deviceProfileId != null && deviceProfileId.length() > 0) {
+ DeviceProfileId profileId = new DeviceProfileId(toUUID(deviceProfileId));
+ return checkNotNull(deviceService.findDeviceInfosByTenantIdAndDeviceProfileId(tenantId, profileId, pageLink));
+ } else {
+ return checkNotNull(deviceService.findDeviceInfosByTenantId(tenantId, pageLink));
}
}
@@ -368,12 +361,8 @@ public class DeviceController extends BaseController {
public Device getTenantDevice(
@ApiParam(value = DEVICE_NAME_DESCRIPTION)
@RequestParam String deviceName) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(deviceService.findDeviceByTenantIdAndName(tenantId, deviceName));
}
@ApiOperation(value = "Get Customer Devices (getCustomerDevices)",
@@ -398,18 +387,14 @@ public class DeviceController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
- } else {
- return checkNotNull(deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(deviceService.findDevicesByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
+ } else {
+ return checkNotNull(deviceService.findDevicesByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -437,21 +422,17 @@ public class DeviceController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
- } else if (deviceProfileId != null && deviceProfileId.length() > 0) {
- DeviceProfileId profileId = new DeviceProfileId(toUUID(deviceProfileId));
- return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndDeviceProfileId(tenantId, customerId, profileId, pageLink));
- } else {
- return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
+ } else if (deviceProfileId != null && deviceProfileId.length() > 0) {
+ DeviceProfileId profileId = new DeviceProfileId(toUUID(deviceProfileId));
+ return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerIdAndDeviceProfileId(tenantId, customerId, profileId, pageLink));
+ } else {
+ return checkNotNull(deviceService.findDeviceInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -462,26 +443,22 @@ public class DeviceController extends BaseController {
@ResponseBody
public List getDevicesByIds(
@ApiParam(value = "A list of devices ids, separated by comma ','")
- @RequestParam("deviceIds") String[] strDeviceIds) throws ThingsboardException {
+ @RequestParam("deviceIds") String[] strDeviceIds) throws ThingsboardException, ExecutionException, InterruptedException {
checkArrayParameter("deviceIds", strDeviceIds);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- CustomerId customerId = user.getCustomerId();
- List deviceIds = new ArrayList<>();
- for (String strDeviceId : strDeviceIds) {
- deviceIds.add(new DeviceId(toUUID(strDeviceId)));
- }
- ListenableFuture> devices;
- if (customerId == null || customerId.isNullUid()) {
- devices = deviceService.findDevicesByTenantIdAndIdsAsync(tenantId, deviceIds);
- } else {
- devices = deviceService.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, deviceIds);
- }
- return checkNotNull(devices.get());
- } catch (Exception e) {
- throw handleException(e);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ CustomerId customerId = user.getCustomerId();
+ List deviceIds = new ArrayList<>();
+ for (String strDeviceId : strDeviceIds) {
+ deviceIds.add(new DeviceId(toUUID(strDeviceId)));
+ }
+ ListenableFuture> devices;
+ if (customerId == null || customerId.isNullUid()) {
+ devices = deviceService.findDevicesByTenantIdAndIdsAsync(tenantId, deviceIds);
+ } else {
+ devices = deviceService.findDevicesByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, deviceIds);
}
+ return checkNotNull(devices.get());
}
@ApiOperation(value = "Find related devices (findByQuery)",
@@ -493,25 +470,21 @@ public class DeviceController extends BaseController {
@ResponseBody
public List findByQuery(
@ApiParam(value = "The device search query JSON")
- @RequestBody DeviceSearchQuery query) throws ThingsboardException {
+ @RequestBody DeviceSearchQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getDeviceTypes());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- List devices = checkNotNull(deviceService.findDevicesByQuery(getCurrentUser().getTenantId(), query).get());
- devices = devices.stream().filter(device -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.DEVICE, Operation.READ, device.getId(), device);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- return devices;
- } catch (Exception e) {
- throw handleException(e);
- }
+ List devices = checkNotNull(deviceService.findDevicesByQuery(getCurrentUser().getTenantId(), query).get());
+ devices = devices.stream().filter(device -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.DEVICE, Operation.READ, device.getId(), device);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ return devices;
}
@ApiOperation(value = "Get Device Types (getDeviceTypes)",
@@ -520,15 +493,11 @@ public class DeviceController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/device/types", method = RequestMethod.GET)
@ResponseBody
- public List getDeviceTypes() throws ThingsboardException {
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- ListenableFuture> deviceTypes = deviceService.findDeviceTypesByTenantId(tenantId);
- return checkNotNull(deviceTypes.get());
- } catch (Exception e) {
- throw handleException(e);
- }
+ public List getDeviceTypes() throws ThingsboardException, ExecutionException, InterruptedException {
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ ListenableFuture> deviceTypes = deviceService.findDeviceTypesByTenantId(tenantId);
+ return checkNotNull(deviceTypes.get());
}
@ApiOperation(value = "Claim device (claimDevice)",
@@ -722,33 +691,29 @@ public class DeviceController extends BaseController {
@ApiParam(value = "Timestamp. Devices with creation time after it won't be queried")
@RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- checkEdgeId(edgeId, Operation.READ);
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- PageData nonFilteredResult;
- if (type != null && type.trim().length() > 0) {
- nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
- } else {
- nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
- }
- List filteredDevices = nonFilteredResult.getData().stream().filter(device -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.DEVICE, Operation.READ, device.getId(), device);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- PageData filteredResult = new PageData<>(filteredDevices,
- nonFilteredResult.getTotalPages(),
- nonFilteredResult.getTotalElements(),
- nonFilteredResult.hasNext());
- return checkNotNull(filteredResult);
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ checkEdgeId(edgeId, Operation.READ);
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ PageData nonFilteredResult;
+ if (type != null && type.trim().length() > 0) {
+ nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
+ } else {
+ nonFilteredResult = deviceService.findDevicesByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
+ List filteredDevices = nonFilteredResult.getData().stream().filter(device -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.DEVICE, Operation.READ, device.getId(), device);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ PageData filteredResult = new PageData<>(filteredDevices,
+ nonFilteredResult.getTotalPages(),
+ nonFilteredResult.getTotalElements(),
+ nonFilteredResult.hasNext());
+ return checkNotNull(filteredResult);
}
@ApiOperation(value = "Count devices by device profile (countByDeviceProfileAndEmptyOtaPackage)",
@@ -766,14 +731,10 @@ public class DeviceController extends BaseController {
@PathVariable("deviceProfileId") String deviceProfileId) throws ThingsboardException {
checkParameter("OtaPackageType", otaPackageType);
checkParameter("DeviceProfileId", deviceProfileId);
- try {
- return deviceService.countDevicesByTenantIdAndDeviceProfileIdAndEmptyOtaPackage(
- getTenantId(),
- new DeviceProfileId(UUID.fromString(deviceProfileId)),
- OtaPackageType.valueOf(otaPackageType));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return deviceService.countDevicesByTenantIdAndDeviceProfileIdAndEmptyOtaPackage(
+ getTenantId(),
+ new DeviceProfileId(UUID.fromString(deviceProfileId)),
+ OtaPackageType.valueOf(otaPackageType));
}
@ApiOperation(value = "Import the bulk of devices (processDevicesBulkImport)",
diff --git a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java
index 78f80f059a..c888d67252 100644
--- a/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/DeviceProfileController.java
@@ -87,12 +87,8 @@ public class DeviceProfileController extends BaseController {
@ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException {
checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId);
- try {
- DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
- return checkDeviceProfileId(deviceProfileId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
+ return checkDeviceProfileId(deviceProfileId, Operation.READ);
}
@ApiOperation(value = "Get Device Profile Info (getDeviceProfileInfoById)",
@@ -106,12 +102,8 @@ public class DeviceProfileController extends BaseController {
@ApiParam(value = DEVICE_PROFILE_ID_PARAM_DESCRIPTION)
@PathVariable(DEVICE_PROFILE_ID) String strDeviceProfileId) throws ThingsboardException {
checkParameter(DEVICE_PROFILE_ID, strDeviceProfileId);
- try {
- DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
- return new DeviceProfileInfo(checkDeviceProfileId(deviceProfileId, Operation.READ));
- } catch (Exception e) {
- throw handleException(e);
- }
+ DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
+ return new DeviceProfileInfo(checkDeviceProfileId(deviceProfileId, Operation.READ));
}
@ApiOperation(value = "Get Default Device Profile (getDefaultDeviceProfileInfo)",
@@ -122,11 +114,7 @@ public class DeviceProfileController extends BaseController {
@RequestMapping(value = "/deviceProfileInfo/default", method = RequestMethod.GET)
@ResponseBody
public DeviceProfileInfo getDefaultDeviceProfileInfo() throws ThingsboardException {
- try {
- return checkNotNull(deviceProfileService.findDefaultDeviceProfileInfo(getTenantId()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(deviceProfileService.findDefaultDeviceProfileInfo(getTenantId()));
}
@ApiOperation(value = "Get time-series keys (getTimeseriesKeys)",
@@ -150,11 +138,7 @@ public class DeviceProfileController extends BaseController {
deviceProfileId = null;
}
- try {
- return timeseriesService.findAllKeysByDeviceProfileId(getTenantId(), deviceProfileId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return timeseriesService.findAllKeysByDeviceProfileId(getTenantId(), deviceProfileId);
}
@ApiOperation(value = "Get attribute keys (getAttributesKeys)",
@@ -178,11 +162,7 @@ public class DeviceProfileController extends BaseController {
deviceProfileId = null;
}
- try {
- return attributesService.findAllKeysByDeviceProfileId(getTenantId(), deviceProfileId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return attributesService.findAllKeysByDeviceProfileId(getTenantId(), deviceProfileId);
}
@ApiOperation(value = "Create Or Update Device Profile (saveDeviceProfile)",
@@ -256,12 +236,8 @@ public class DeviceProfileController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(deviceProfileService.findDeviceProfiles(getTenantId(), pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(deviceProfileService.findDeviceProfiles(getTenantId(), pageLink));
}
@ApiOperation(value = "Get Device Profiles for transport type (getDeviceProfileInfos)",
@@ -284,11 +260,7 @@ public class DeviceProfileController extends BaseController {
@RequestParam(required = false) String sortOrder,
@ApiParam(value = "Type of the transport", allowableValues = TRANSPORT_TYPE_ALLOWABLE_VALUES)
@RequestParam(required = false) String transportType) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(deviceProfileService.findDeviceProfileInfos(getTenantId(), pageLink, transportType));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(deviceProfileService.findDeviceProfileInfos(getTenantId(), pageLink, transportType));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java
index 4b7ac62fa0..5ef1c1b572 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EdgeController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EdgeController.java
@@ -68,6 +68,7 @@ import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID_PARAM_DESCRIPTION;
@@ -118,12 +119,8 @@ public class EdgeController extends BaseController {
public Edge getEdgeById(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- return checkEdgeId(edgeId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ return checkEdgeId(edgeId, Operation.READ);
}
@ApiOperation(value = "Get Edge Info (getEdgeInfoById)",
@@ -135,12 +132,8 @@ public class EdgeController extends BaseController {
public EdgeInfo getEdgeInfoById(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(EDGE_ID) String strEdgeId) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- return checkEdgeInfoId(edgeId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ return checkEdgeInfoId(edgeId, Operation.READ);
}
@ApiOperation(value = "Create Or Update Edge (saveEdge)",
@@ -205,13 +198,9 @@ public class EdgeController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(edgeService.findEdgesByTenantId(tenantId, pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(edgeService.findEdgesByTenantId(tenantId, pageLink));
}
@ApiOperation(value = "Assign edge to customer (assignEdgeToCustomer)",
@@ -287,16 +276,12 @@ public class EdgeController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(edgeService.findEdgesByTenantIdAndType(tenantId, type, pageLink));
- } else {
- return checkNotNull(edgeService.findEdgesByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(edgeService.findEdgesByTenantIdAndType(tenantId, type, pageLink));
+ } else {
+ return checkNotNull(edgeService.findEdgesByTenantId(tenantId, pageLink));
}
}
@@ -320,16 +305,12 @@ public class EdgeController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(edgeService.findEdgeInfosByTenantIdAndType(tenantId, type, pageLink));
- } else {
- return checkNotNull(edgeService.findEdgeInfosByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(edgeService.findEdgeInfosByTenantIdAndType(tenantId, type, pageLink));
+ } else {
+ return checkNotNull(edgeService.findEdgeInfosByTenantId(tenantId, pageLink));
}
}
@@ -342,12 +323,8 @@ public class EdgeController extends BaseController {
@ResponseBody
public Edge getTenantEdge(@ApiParam(value = "Unique name of the edge", required = true)
@RequestParam String edgeName) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(edgeService.findEdgeByTenantIdAndName(tenantId, edgeName));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(edgeService.findEdgeByTenantIdAndName(tenantId, edgeName));
}
@ApiOperation(value = "Set root rule chain for provided edge (setEdgeRootRuleChain)",
@@ -393,22 +370,18 @@ public class EdgeController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- PageData result;
- if (type != null && type.trim().length() > 0) {
- result = edgeService.findEdgesByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink);
- } else {
- result = edgeService.findEdgesByTenantIdAndCustomerId(tenantId, customerId, pageLink);
- }
- return checkNotNull(result);
- } catch (Exception e) {
- throw handleException(e);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ PageData result;
+ if (type != null && type.trim().length() > 0) {
+ result = edgeService.findEdgesByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink);
+ } else {
+ result = edgeService.findEdgesByTenantIdAndCustomerId(tenantId, customerId, pageLink);
}
+ return checkNotNull(result);
}
@ApiOperation(value = "Get Customer Edge Infos (getCustomerEdgeInfos)",
@@ -433,22 +406,18 @@ public class EdgeController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- PageData result;
- if (type != null && type.trim().length() > 0) {
- result = edgeService.findEdgeInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink);
- } else {
- result = edgeService.findEdgeInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink);
- }
- return checkNotNull(result);
- } catch (Exception e) {
- throw handleException(e);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ PageData result;
+ if (type != null && type.trim().length() > 0) {
+ result = edgeService.findEdgeInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink);
+ } else {
+ result = edgeService.findEdgeInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink);
}
+ return checkNotNull(result);
}
@ApiOperation(value = "Get Edges By Ids (getEdgesByIds)",
@@ -459,27 +428,23 @@ public class EdgeController extends BaseController {
@ResponseBody
public List getEdgesByIds(
@ApiParam(value = "A list of edges ids, separated by comma ','", required = true)
- @RequestParam("edgeIds") String[] strEdgeIds) throws ThingsboardException {
+ @RequestParam("edgeIds") String[] strEdgeIds) throws ThingsboardException, ExecutionException, InterruptedException {
checkArrayParameter("edgeIds", strEdgeIds);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- CustomerId customerId = user.getCustomerId();
- List edgeIds = new ArrayList<>();
- for (String strEdgeId : strEdgeIds) {
- edgeIds.add(new EdgeId(toUUID(strEdgeId)));
- }
- ListenableFuture> edgesFuture;
- if (customerId == null || customerId.isNullUid()) {
- edgesFuture = edgeService.findEdgesByTenantIdAndIdsAsync(tenantId, edgeIds);
- } else {
- edgesFuture = edgeService.findEdgesByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, edgeIds);
- }
- List edges = edgesFuture.get();
- return checkNotNull(edges);
- } catch (Exception e) {
- throw handleException(e);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ CustomerId customerId = user.getCustomerId();
+ List edgeIds = new ArrayList<>();
+ for (String strEdgeId : strEdgeIds) {
+ edgeIds.add(new EdgeId(toUUID(strEdgeId)));
+ }
+ ListenableFuture> edgesFuture;
+ if (customerId == null || customerId.isNullUid()) {
+ edgesFuture = edgeService.findEdgesByTenantIdAndIdsAsync(tenantId, edgeIds);
+ } else {
+ edgesFuture = edgeService.findEdgesByTenantIdCustomerIdAndIdsAsync(tenantId, customerId, edgeIds);
}
+ List edges = edgesFuture.get();
+ return checkNotNull(edges);
}
@ApiOperation(value = "Find related edges (findByQuery)",
@@ -490,27 +455,23 @@ public class EdgeController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edges", method = RequestMethod.POST)
@ResponseBody
- public List findByQuery(@RequestBody EdgeSearchQuery query) throws ThingsboardException {
+ public List findByQuery(@RequestBody EdgeSearchQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getEdgeTypes());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- List edges = checkNotNull(edgeService.findEdgesByQuery(tenantId, query).get());
- edges = edges.stream().filter(edge -> {
- try {
- accessControlService.checkPermission(user, Resource.EDGE, Operation.READ, edge.getId(), edge);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- return edges;
- } catch (Exception e) {
- throw handleException(e);
- }
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ List edges = checkNotNull(edgeService.findEdgesByQuery(tenantId, query).get());
+ edges = edges.stream().filter(edge -> {
+ try {
+ accessControlService.checkPermission(user, Resource.EDGE, Operation.READ, edge.getId(), edge);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ return edges;
}
@ApiOperation(value = "Get Edge Types (getEdgeTypes)",
@@ -520,15 +481,11 @@ public class EdgeController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/edge/types", method = RequestMethod.GET)
@ResponseBody
- public List getEdgeTypes() throws ThingsboardException {
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- ListenableFuture> edgeTypes = edgeService.findEdgeTypesByTenantId(tenantId);
- return checkNotNull(edgeTypes.get());
- } catch (Exception e) {
- throw handleException(e);
- }
+ public List getEdgeTypes() throws ThingsboardException, ExecutionException, InterruptedException {
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ ListenableFuture> edgeTypes = edgeService.findEdgeTypesByTenantId(tenantId);
+ return checkNotNull(edgeTypes.get());
}
@ApiOperation(value = "Sync edge (syncEdge)",
@@ -539,22 +496,18 @@ public class EdgeController extends BaseController {
public DeferredResult syncEdge(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("edgeId") String strEdgeId) throws ThingsboardException {
checkParameter("edgeId", strEdgeId);
- try {
- final DeferredResult response = new DeferredResult<>();
- if (isEdgesEnabled()) {
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- edgeId = checkNotNull(edgeId);
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- ToEdgeSyncRequest request = new ToEdgeSyncRequest(UUID.randomUUID(), tenantId, edgeId);
- edgeRpcService.processSyncRequest(request, fromEdgeSyncResponse -> reply(response, fromEdgeSyncResponse));
- } else {
- throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
- }
- return response;
- } catch (Exception e) {
- throw handleException(e);
+ final DeferredResult response = new DeferredResult<>();
+ if (isEdgesEnabled()) {
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ edgeId = checkNotNull(edgeId);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ ToEdgeSyncRequest request = new ToEdgeSyncRequest(UUID.randomUUID(), tenantId, edgeId);
+ edgeRpcService.processSyncRequest(request, fromEdgeSyncResponse -> reply(response, fromEdgeSyncResponse));
+ } else {
+ throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
}
+ return response;
}
private void reply(DeferredResult response, FromEdgeSyncResponse fromEdgeSyncResponse) {
@@ -572,15 +525,11 @@ public class EdgeController extends BaseController {
@ResponseBody
public String findMissingToRelatedRuleChains(@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("edgeId") String strEdgeId) throws ThingsboardException {
- try {
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- edgeId = checkNotNull(edgeId);
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- return edgeService.findMissingToRelatedRuleChains(tenantId, edgeId, TbRuleChainInputNode.class.getName());
- } catch (Exception e) {
- throw handleException(e);
- }
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ edgeId = checkNotNull(edgeId);
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ return edgeService.findMissingToRelatedRuleChains(tenantId, edgeId, TbRuleChainInputNode.class.getName());
}
@ApiOperation(value = "Import the bulk of edges (processEdgesBulkImport)",
@@ -608,13 +557,9 @@ public class EdgeController extends BaseController {
@ApiParam(value = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("edgeId") String strEdgeId,
HttpServletRequest request) throws ThingsboardException {
- try {
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- edgeId = checkNotNull(edgeId);
- Edge edge = checkEdgeId(edgeId, Operation.READ);
- return checkNotNull(edgeInstallService.getDockerInstallInstructions(getTenantId(), edge, request));
- } catch (Exception e) {
- throw handleException(e);
- }
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ edgeId = checkNotNull(edgeId);
+ Edge edge = checkEdgeId(edgeId, Operation.READ);
+ return checkNotNull(edgeInstallService.getDockerInstallInstructions(getTenantId(), edge, request));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/EdgeEventController.java b/application/src/main/java/org/thingsboard/server/controller/EdgeEventController.java
index 5197981876..fc85f439e0 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EdgeEventController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EdgeEventController.java
@@ -81,14 +81,10 @@ public class EdgeEventController extends BaseController {
@ApiParam(value = "Timestamp. Edge events with creation time after it won't be queried")
@RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- checkEdgeId(edgeId, Operation.READ);
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- return checkNotNull(edgeEventService.findEdgeEvents(tenantId, edgeId, pageLink, false));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ checkEdgeId(edgeId, Operation.READ);
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ return checkNotNull(edgeEventService.findEdgeEvents(tenantId, edgeId, pageLink, false));
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityQueryController.java b/application/src/main/java/org/thingsboard/server/controller/EntityQueryController.java
index 3fdc1bc236..fbb8901ca9 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EntityQueryController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EntityQueryController.java
@@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.page.PageData;
+import org.thingsboard.server.common.data.query.AlarmCountQuery;
import org.thingsboard.server.common.data.query.AlarmData;
import org.thingsboard.server.common.data.query.AlarmDataQuery;
import org.thingsboard.server.common.data.query.EntityCountQuery;
@@ -93,6 +94,20 @@ public class EntityQueryController extends BaseController {
return this.entityQueryService.findAlarmDataByQuery(getCurrentUser(), query);
}
+ @ApiOperation(value = "Count Alarms by Query (countAlarmsByQuery)", notes = "Returns the number of alarms that match the query definition.")
+ @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
+ @RequestMapping(value = "/alarmsQuery/count", method = RequestMethod.POST)
+ @ResponseBody
+ public long countAlarmsByQuery(@ApiParam(value = "A JSON value representing the alarm count query.")
+ @RequestBody AlarmCountQuery query) throws ThingsboardException {
+ checkNotNull(query);
+ UserId assigneeId = query.getAssigneeId();
+ if (assigneeId != null) {
+ checkUserId(assigneeId, Operation.READ);
+ }
+ return this.entityQueryService.countAlarmsByQuery(getCurrentUser(), query);
+ }
+
@ApiOperation(value = "Find Entity Keys by Query",
notes = "Uses entity data query (see 'Find Entity Data by Query') to find first 100 entities. Then fetch and return all unique time-series and/or attribute keys. Used mostly for UI hints.")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java
index 3e02868208..08448f1d28 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EntityRelationController.java
@@ -41,6 +41,7 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.permission.Operation;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.ENTITY_ID_PARAM_DESCRIPTION;
@@ -143,21 +144,17 @@ public class EntityRelationController extends BaseController {
@ApiParam(value = RELATION_TYPE_GROUP_PARAM_DESCRIPTION) @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup,
@ApiParam(value = ENTITY_ID_PARAM_DESCRIPTION, required = true) @RequestParam(TO_ID) String strToId,
@ApiParam(value = ENTITY_TYPE_PARAM_DESCRIPTION, required = true) @RequestParam(TO_TYPE) String strToType) throws ThingsboardException {
- try {
- checkParameter(FROM_ID, strFromId);
- checkParameter(FROM_TYPE, strFromType);
- checkParameter(RELATION_TYPE, strRelationType);
- checkParameter(TO_ID, strToId);
- checkParameter(TO_TYPE, strToType);
- EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
- EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
- checkEntityId(fromId, Operation.READ);
- checkEntityId(toId, Operation.READ);
- RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- return checkNotNull(relationService.getRelation(getTenantId(), fromId, toId, strRelationType, typeGroup));
- } catch (Exception e) {
- throw handleException(e);
- }
+ checkParameter(FROM_ID, strFromId);
+ checkParameter(FROM_TYPE, strFromType);
+ checkParameter(RELATION_TYPE, strRelationType);
+ checkParameter(TO_ID, strToId);
+ checkParameter(TO_TYPE, strToType);
+ EntityId fromId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
+ EntityId toId = EntityIdFactory.getByTypeAndId(strToType, strToId);
+ checkEntityId(fromId, Operation.READ);
+ checkEntityId(toId, Operation.READ);
+ RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
+ return checkNotNull(relationService.getRelation(getTenantId(), fromId, toId, strRelationType, typeGroup));
}
@ApiOperation(value = "Get List of Relations (findByFrom)",
@@ -176,11 +173,7 @@ public class EntityRelationController extends BaseController {
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findByFrom(getTenantId(), entityId, typeGroup)));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findByFrom(getTenantId(), entityId, typeGroup)));
}
@ApiOperation(value = "Get List of Relation Infos (findInfoByFrom)",
@@ -193,17 +186,13 @@ public class EntityRelationController extends BaseController {
public List findInfoByFrom(@ApiParam(value = ENTITY_ID_PARAM_DESCRIPTION, required = true) @RequestParam(FROM_ID) String strFromId,
@ApiParam(value = ENTITY_TYPE_PARAM_DESCRIPTION, required = true) @RequestParam(FROM_TYPE) String strFromType,
@ApiParam(value = RELATION_TYPE_GROUP_PARAM_DESCRIPTION)
- @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
+ @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException, ExecutionException, InterruptedException {
checkParameter(FROM_ID, strFromId);
checkParameter(FROM_TYPE, strFromType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByFrom(getTenantId(), entityId, typeGroup).get()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByFrom(getTenantId(), entityId, typeGroup).get()));
}
@ApiOperation(value = "Get List of Relations (findByFrom)",
@@ -224,11 +213,7 @@ public class EntityRelationController extends BaseController {
EntityId entityId = EntityIdFactory.getByTypeAndId(strFromType, strFromId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findByFromAndType(getTenantId(), entityId, strRelationType, typeGroup)));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findByFromAndType(getTenantId(), entityId, strRelationType, typeGroup)));
}
@ApiOperation(value = "Get List of Relations (findByTo)",
@@ -247,11 +232,7 @@ public class EntityRelationController extends BaseController {
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findByTo(getTenantId(), entityId, typeGroup)));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findByTo(getTenantId(), entityId, typeGroup)));
}
@ApiOperation(value = "Get List of Relation Infos (findInfoByTo)",
@@ -264,17 +245,13 @@ public class EntityRelationController extends BaseController {
public List findInfoByTo(@ApiParam(value = ENTITY_ID_PARAM_DESCRIPTION, required = true) @RequestParam(TO_ID) String strToId,
@ApiParam(value = ENTITY_TYPE_PARAM_DESCRIPTION, required = true) @RequestParam(TO_TYPE) String strToType,
@ApiParam(value = RELATION_TYPE_GROUP_PARAM_DESCRIPTION)
- @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException {
+ @RequestParam(value = "relationTypeGroup", required = false) String strRelationTypeGroup) throws ThingsboardException, ExecutionException, InterruptedException {
checkParameter(TO_ID, strToId);
checkParameter(TO_TYPE, strToType);
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByTo(getTenantId(), entityId, typeGroup).get()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByTo(getTenantId(), entityId, typeGroup).get()));
}
@ApiOperation(value = "Get List of Relations (findByTo)",
@@ -295,11 +272,7 @@ public class EntityRelationController extends BaseController {
EntityId entityId = EntityIdFactory.getByTypeAndId(strToType, strToId);
checkEntityId(entityId, Operation.READ);
RelationTypeGroup typeGroup = parseRelationTypeGroup(strRelationTypeGroup, RelationTypeGroup.COMMON);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findByToAndType(getTenantId(), entityId, strRelationType, typeGroup)));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findByToAndType(getTenantId(), entityId, strRelationType, typeGroup)));
}
@ApiOperation(value = "Find related entities (findByQuery)",
@@ -310,16 +283,12 @@ public class EntityRelationController extends BaseController {
@RequestMapping(value = "/relations", method = RequestMethod.POST)
@ResponseBody
public List findByQuery(@ApiParam(value = "A JSON value representing the entity relations query object.", required = true)
- @RequestBody EntityRelationsQuery query) throws ThingsboardException {
+ @RequestBody EntityRelationsQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getFilters());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findByQuery(getTenantId(), query).get()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findByQuery(getTenantId(), query).get()));
}
@ApiOperation(value = "Find related entity infos (findInfoByQuery)",
@@ -330,16 +299,12 @@ public class EntityRelationController extends BaseController {
@RequestMapping(value = "/relations/info", method = RequestMethod.POST)
@ResponseBody
public List findInfoByQuery(@ApiParam(value = "A JSON value representing the entity relations query object.", required = true)
- @RequestBody EntityRelationsQuery query) throws ThingsboardException {
+ @RequestBody EntityRelationsQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getFilters());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByQuery(getTenantId(), query).get()));
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkNotNull(filterRelationsByReadPermission(relationService.findInfoByQuery(getTenantId(), query).get()));
}
private void checkCanCreateRelation(EntityId entityId) throws ThingsboardException {
diff --git a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
index 64d0896c6a..b2904a0989 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
@@ -54,6 +54,7 @@ import org.thingsboard.server.service.security.permission.Operation;
import org.thingsboard.server.service.security.permission.Resource;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.thingsboard.server.controller.ControllerConstants.CUSTOMER_ID;
@@ -105,11 +106,7 @@ public class EntityViewController extends BaseController {
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
checkParameter(ENTITY_VIEW_ID, strEntityViewId);
- try {
- return checkEntityViewId(new EntityViewId(toUUID(strEntityViewId)), Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return checkEntityViewId(new EntityViewId(toUUID(strEntityViewId)), Operation.READ);
}
@ApiOperation(value = "Get Entity View info (getEntityViewInfoById)",
@@ -123,12 +120,8 @@ public class EntityViewController extends BaseController {
@ApiParam(value = ENTITY_VIEW_ID_PARAM_DESCRIPTION)
@PathVariable(ENTITY_VIEW_ID) String strEntityViewId) throws ThingsboardException {
checkParameter(ENTITY_VIEW_ID, strEntityViewId);
- try {
- EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
- return checkEntityViewInfoId(entityViewId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ EntityViewId entityViewId = new EntityViewId(toUUID(strEntityViewId));
+ return checkEntityViewInfoId(entityViewId, Operation.READ);
}
@ApiOperation(value = "Save or update entity view (saveEntityView)",
@@ -177,12 +170,8 @@ public class EntityViewController extends BaseController {
public EntityView getTenantEntityView(
@ApiParam(value = "Entity View name")
@RequestParam String entityViewName) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- return checkNotNull(entityViewService.findEntityViewByTenantIdAndName(tenantId, entityViewName));
- } catch (Exception e) {
- throw handleException(e);
- }
+ TenantId tenantId = getCurrentUser().getTenantId();
+ return checkNotNull(entityViewService.findEntityViewByTenantIdAndName(tenantId, entityViewName));
}
@ApiOperation(value = "Assign Entity View to customer (assignEntityViewToCustomer)",
@@ -249,18 +238,14 @@ public class EntityViewController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter(CUSTOMER_ID, strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(entityViewService.findEntityViewsByTenantIdAndCustomerIdAndType(tenantId, customerId, pageLink, type));
- } else {
- return checkNotNull(entityViewService.findEntityViewsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(entityViewService.findEntityViewsByTenantIdAndCustomerIdAndType(tenantId, customerId, pageLink, type));
+ } else {
+ return checkNotNull(entityViewService.findEntityViewsByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -286,18 +271,14 @@ public class EntityViewController extends BaseController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("customerId", strCustomerId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- CustomerId customerId = new CustomerId(toUUID(strCustomerId));
- checkCustomerId(customerId, Operation.READ);
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
- } else {
- return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ CustomerId customerId = new CustomerId(toUUID(strCustomerId));
+ checkCustomerId(customerId, Operation.READ);
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndCustomerIdAndType(tenantId, customerId, type, pageLink));
+ } else {
+ return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndCustomerId(tenantId, customerId, pageLink));
}
}
@@ -320,17 +301,13 @@ public class EntityViewController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
-
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(entityViewService.findEntityViewByTenantIdAndType(tenantId, pageLink, type));
- } else {
- return checkNotNull(entityViewService.findEntityViewByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(entityViewService.findEntityViewByTenantIdAndType(tenantId, pageLink, type));
+ } else {
+ return checkNotNull(entityViewService.findEntityViewByTenantId(tenantId, pageLink));
}
}
@@ -353,16 +330,12 @@ public class EntityViewController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- if (type != null && type.trim().length() > 0) {
- return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndType(tenantId, type, pageLink));
- } else {
- return checkNotNull(entityViewService.findEntityViewInfosByTenantId(tenantId, pageLink));
- }
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ if (type != null && type.trim().length() > 0) {
+ return checkNotNull(entityViewService.findEntityViewInfosByTenantIdAndType(tenantId, type, pageLink));
+ } else {
+ return checkNotNull(entityViewService.findEntityViewInfosByTenantId(tenantId, pageLink));
}
}
@@ -375,25 +348,21 @@ public class EntityViewController extends BaseController {
@ResponseBody
public List findByQuery(
@ApiParam(value = "The entity view search query JSON")
- @RequestBody EntityViewSearchQuery query) throws ThingsboardException {
+ @RequestBody EntityViewSearchQuery query) throws ThingsboardException, ExecutionException, InterruptedException {
checkNotNull(query);
checkNotNull(query.getParameters());
checkNotNull(query.getEntityViewTypes());
checkEntityId(query.getParameters().getEntityId(), Operation.READ);
- try {
- List entityViews = checkNotNull(entityViewService.findEntityViewsByQuery(getTenantId(), query).get());
- entityViews = entityViews.stream().filter(entityView -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.READ, entityView.getId(), entityView);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- return entityViews;
- } catch (Exception e) {
- throw handleException(e);
- }
+ List entityViews = checkNotNull(entityViewService.findEntityViewsByQuery(getTenantId(), query).get());
+ entityViews = entityViews.stream().filter(entityView -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.READ, entityView.getId(), entityView);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ return entityViews;
}
@ApiOperation(value = "Get Entity View Types (getEntityViewTypes)",
@@ -402,15 +371,11 @@ public class EntityViewController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/entityView/types", method = RequestMethod.GET)
@ResponseBody
- public List getEntityViewTypes() throws ThingsboardException {
- try {
- SecurityUser user = getCurrentUser();
- TenantId tenantId = user.getTenantId();
- ListenableFuture> entityViewTypes = entityViewService.findEntityViewTypesByTenantId(tenantId);
- return checkNotNull(entityViewTypes.get());
- } catch (Exception e) {
- throw handleException(e);
- }
+ public List getEntityViewTypes() throws ThingsboardException, ExecutionException, InterruptedException {
+ SecurityUser user = getCurrentUser();
+ TenantId tenantId = user.getTenantId();
+ ListenableFuture> entityViewTypes = entityViewService.findEntityViewTypesByTenantId(tenantId);
+ return checkNotNull(entityViewTypes.get());
}
@ApiOperation(value = "Make entity view publicly available (assignEntityViewToPublicCustomer)",
@@ -493,32 +458,28 @@ public class EntityViewController extends BaseController {
@RequestParam(required = false) Long startTime,
@RequestParam(required = false) Long endTime) throws ThingsboardException {
checkParameter(EDGE_ID, strEdgeId);
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
- checkEdgeId(edgeId, Operation.READ);
- TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
- PageData nonFilteredResult;
- if (type != null && type.trim().length() > 0) {
- nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
- } else {
- nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
- }
- List filteredEntityViews = nonFilteredResult.getData().stream().filter(entityView -> {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.READ, entityView.getId(), entityView);
- return true;
- } catch (ThingsboardException e) {
- return false;
- }
- }).collect(Collectors.toList());
- PageData filteredResult = new PageData<>(filteredEntityViews,
- nonFilteredResult.getTotalPages(),
- nonFilteredResult.getTotalElements(),
- nonFilteredResult.hasNext());
- return checkNotNull(filteredResult);
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
+ checkEdgeId(edgeId, Operation.READ);
+ TimePageLink pageLink = createTimePageLink(pageSize, page, textSearch, sortProperty, sortOrder, startTime, endTime);
+ PageData nonFilteredResult;
+ if (type != null && type.trim().length() > 0) {
+ nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeIdAndType(tenantId, edgeId, type, pageLink);
+ } else {
+ nonFilteredResult = entityViewService.findEntityViewsByTenantIdAndEdgeId(tenantId, edgeId, pageLink);
}
+ List filteredEntityViews = nonFilteredResult.getData().stream().filter(entityView -> {
+ try {
+ accessControlService.checkPermission(getCurrentUser(), Resource.ENTITY_VIEW, Operation.READ, entityView.getId(), entityView);
+ return true;
+ } catch (ThingsboardException e) {
+ return false;
+ }
+ }).collect(Collectors.toList());
+ PageData filteredResult = new PageData<>(filteredEntityViews,
+ nonFilteredResult.getTotalPages(),
+ nonFilteredResult.getTotalElements(),
+ nonFilteredResult.hasNext());
+ return checkNotNull(filteredResult);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/EventController.java b/application/src/main/java/org/thingsboard/server/controller/EventController.java
index f01af0558f..59fb18d82e 100644
--- a/application/src/main/java/org/thingsboard/server/controller/EventController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/EventController.java
@@ -248,14 +248,10 @@ public class EventController extends BaseController {
@RequestBody EventFilter eventFilter) throws ThingsboardException {
checkParameter("EntityId", strEntityId);
checkParameter("EntityType", strEntityType);
- try {
- EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId);
- checkEntityId(entityId, Operation.WRITE);
+ EntityId entityId = EntityIdFactory.getByTypeAndId(strEntityType, strEntityId);
+ checkEntityId(entityId, Operation.WRITE);
- eventService.removeEvents(getTenantId(), entityId, eventFilter, startTime, endTime);
- } catch (Exception e) {
- throw handleException(e);
- }
+ eventService.removeEvents(getTenantId(), entityId, eventFilter, startTime, endTime);
}
private static EventType resolveEventType(String eventType) throws ThingsboardException {
diff --git a/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java b/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java
index 18f01d553e..ae1dec43fe 100644
--- a/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/Lwm2mController.java
@@ -64,11 +64,7 @@ public class Lwm2mController extends BaseController {
public LwM2MServerSecurityConfigDefault getLwm2mBootstrapSecurityInfo(
@ApiParam(value = IS_BOOTSTRAP_SERVER_PARAM_DESCRIPTION)
@PathVariable(IS_BOOTSTRAP_SERVER) boolean bootstrapServer) throws ThingsboardException {
- try {
- return lwM2MService.getServerSecurityInfo(bootstrapServer);
- } catch (Exception e) {
- throw handleException(e);
- }
+ return lwM2MService.getServerSecurityInfo(bootstrapServer);
}
@ApiOperation(hidden = true, value = "Save device with credentials (Deprecated)")
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
index 24daab29f0..6c27887e1a 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java
@@ -42,10 +42,12 @@ import org.thingsboard.server.common.data.notification.NotificationDeliveryMetho
import org.thingsboard.server.common.data.notification.NotificationRequest;
import org.thingsboard.server.common.data.notification.NotificationRequestInfo;
import org.thingsboard.server.common.data.notification.NotificationRequestPreview;
-import org.thingsboard.server.common.data.notification.info.UserOriginatedNotificationInfo;
import org.thingsboard.server.common.data.notification.settings.NotificationSettings;
+import org.thingsboard.server.common.data.notification.targets.NotificationRecipient;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.targets.NotificationTargetType;
+import org.thingsboard.server.common.data.notification.targets.platform.PlatformUsersNotificationTargetConfig;
+import org.thingsboard.server.common.data.notification.targets.slack.SlackNotificationTargetConfig;
import org.thingsboard.server.common.data.notification.template.DeliveryMethodNotificationTemplate;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
import org.thingsboard.server.common.data.page.PageData;
@@ -62,7 +64,6 @@ import org.thingsboard.server.service.security.permission.Operation;
import org.thingsboard.server.service.security.permission.Resource;
import javax.validation.Valid;
-import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -187,14 +188,12 @@ public class NotificationController extends BaseController {
checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION);
notificationRequest.setOriginatorEntityId(user.getId());
- if (notificationRequest.getInfo() != null && !(notificationRequest.getInfo() instanceof UserOriginatedNotificationInfo)) {
- throw new IllegalArgumentException("Unsupported notification info type");
- }
+ notificationRequest.setInfo(null);
notificationRequest.setRuleId(null);
notificationRequest.setStatus(null);
notificationRequest.setStats(null);
- return doSaveAndLog(EntityType.NOTIFICATION_REQUEST, notificationRequest, notificationCenter::processNotificationRequest);
+ return doSaveAndLog(EntityType.NOTIFICATION_REQUEST, notificationRequest, (tenantId, request) -> notificationCenter.processNotificationRequest(tenantId, request, null));
}
@PostMapping("/notification/request/preview")
@@ -217,45 +216,49 @@ public class NotificationController extends BaseController {
NotificationProcessingContext tmpProcessingCtx = NotificationProcessingContext.builder()
.tenantId(user.getTenantId())
.request(request)
- .settings(null)
.template(template)
+ .settings(null)
.build();
Map processedTemplates = tmpProcessingCtx.getDeliveryMethods().stream()
.collect(Collectors.toMap(m -> m, deliveryMethod -> {
- Map templateContext;
+ NotificationRecipient recipient = null;
if (NotificationTargetType.PLATFORM_USERS.getSupportedDeliveryMethods().contains(deliveryMethod)) {
- templateContext = tmpProcessingCtx.createTemplateContext(user);
- } else {
- templateContext = Collections.emptyMap();
+ recipient = userService.findUserById(user.getTenantId(), user.getId());
}
- return tmpProcessingCtx.getProcessedTemplate(deliveryMethod, templateContext);
+ return tmpProcessingCtx.getProcessedTemplate(deliveryMethod, recipient);
}));
preview.setProcessedTemplates(processedTemplates);
// generic permission
- Set recipientsPreview = new LinkedHashSet<>();
+ Set recipientsPreview = new LinkedHashSet<>();
Map recipientsCountByTarget = new HashMap<>();
+
List targets = notificationTargetService.findNotificationTargetsByTenantIdAndIds(user.getTenantId(),
request.getTargets().stream().map(NotificationTargetId::new).collect(Collectors.toList()));
for (NotificationTarget target : targets) {
int recipientsCount;
+ List recipientsPart;
if (target.getConfiguration().getType() == NotificationTargetType.PLATFORM_USERS) {
- PageData recipients = notificationTargetService.findRecipientsForNotificationTargetConfig(user.getTenantId(), null,
- target.getConfiguration(), new PageLink(recipientsPreviewSize));
+ PageData recipients = notificationTargetService.findRecipientsForNotificationTargetConfig(user.getTenantId(),
+ (PlatformUsersNotificationTargetConfig) target.getConfiguration(), new PageLink(recipientsPreviewSize));
recipientsCount = (int) recipients.getTotalElements();
- for (User recipient : recipients.getData()) {
- if (recipientsPreview.size() < recipientsPreviewSize) {
- recipientsPreview.add(recipient);
- } else {
- break;
- }
- }
+ recipientsPart = recipients.getData().stream().map(r -> (NotificationRecipient) r).collect(Collectors.toList());
} else {
recipientsCount = 1;
+ recipientsPart = List.of(((SlackNotificationTargetConfig) target.getConfiguration()).getConversation());
+ }
+
+ for (NotificationRecipient recipient : recipientsPart) {
+ if (recipientsPreview.size() < recipientsPreviewSize) {
+ recipientsPreview.add(recipient.getTitle());
+ } else {
+ break;
+ }
}
recipientsCountByTarget.put(target.getName(), recipientsCount);
}
+
preview.setRecipientsPreview(recipientsPreview);
preview.setRecipientsCountByTarget(recipientsCountByTarget);
preview.setTotalRecipientsCount(recipientsCountByTarget.values().stream().mapToInt(Integer::intValue).sum());
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
index 4fdb0136f3..75e2b538a6 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
@@ -67,7 +67,11 @@ public class NotificationRuleController extends BaseController {
throw new IllegalArgumentException("Trigger type " + triggerType + " is not available");
}
- return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
+ boolean created = notificationRule.getId() == null;
+ notificationRule = doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
+ tbClusterService.broadcastEntityStateChangeEvent(user.getTenantId(), notificationRule.getId(), created ?
+ ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
+ return notificationRule;
}
@GetMapping("/rule/{id}")
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationTargetController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationTargetController.java
index 3107435e2d..4fd6b93022 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationTargetController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationTargetController.java
@@ -116,7 +116,7 @@ public class NotificationTargetController extends BaseController {
}
PageLink pageLink = createPageLink(pageSize, page, null, null, null);
- return notificationTargetService.findRecipientsForNotificationTargetConfig(user.getTenantId(), null, notificationTarget.getConfiguration(), pageLink);
+ return notificationTargetService.findRecipientsForNotificationTargetConfig(user.getTenantId(), (PlatformUsersNotificationTargetConfig) notificationTarget.getConfiguration(), pageLink);
}
@GetMapping(value = "/targets", params = {"ids"})
diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
index 5524255648..751b139bd3 100644
--- a/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
@@ -17,6 +17,7 @@ package org.thingsboard.server.controller;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
+import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
@@ -136,16 +137,20 @@ public class NotificationTemplateController extends BaseController {
@GetMapping("/slack/conversations")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')")
public List listSlackConversations(@RequestParam SlackConversationType type,
+ @RequestParam(required = false) String token,
@AuthenticationPrincipal SecurityUser user) {
// generic permission
- NotificationSettings settings = notificationSettingsService.findNotificationSettings(user.getTenantId());
- SlackNotificationDeliveryMethodConfig slackConfig = (SlackNotificationDeliveryMethodConfig)
- settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK);
- if (slackConfig == null) {
- throw new IllegalArgumentException("Slack is not configured");
+ if (StringUtils.isEmpty(token)) {
+ NotificationSettings settings = notificationSettingsService.findNotificationSettings(user.getTenantId());
+ SlackNotificationDeliveryMethodConfig slackConfig = (SlackNotificationDeliveryMethodConfig)
+ settings.getDeliveryMethodsConfigs().get(NotificationDeliveryMethod.SLACK);
+ if (slackConfig == null) {
+ throw new IllegalArgumentException("Slack is not configured");
+ }
+ token = slackConfig.getBotToken();
}
- return slackService.listConversations(user.getTenantId(), slackConfig.getBotToken(), type);
+ return slackService.listConversations(user.getTenantId(), token, type);
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/OAuth2ConfigTemplateController.java b/application/src/main/java/org/thingsboard/server/controller/OAuth2ConfigTemplateController.java
index 2fc2d30869..f547a5f0ad 100644
--- a/application/src/main/java/org/thingsboard/server/controller/OAuth2ConfigTemplateController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/OAuth2ConfigTemplateController.java
@@ -54,12 +54,8 @@ public class OAuth2ConfigTemplateController extends BaseController {
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public OAuth2ClientRegistrationTemplate saveClientRegistrationTemplate(@RequestBody OAuth2ClientRegistrationTemplate clientRegistrationTemplate) throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.WRITE);
- return oAuth2ConfigTemplateService.saveClientRegistrationTemplate(clientRegistrationTemplate);
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.WRITE);
+ return oAuth2ConfigTemplateService.saveClientRegistrationTemplate(clientRegistrationTemplate);
}
@ApiOperation(value = "Delete OAuth2 client registration template by id (deleteClientRegistrationTemplate)" + SYSTEM_AUTHORITY_PARAGRAPH,
@@ -70,13 +66,9 @@ public class OAuth2ConfigTemplateController extends BaseController {
public void deleteClientRegistrationTemplate(@ApiParam(value = "String representation of client registration template id to delete", example = "139b1f81-2f5d-11ec-9dbe-9b627e1a88f4")
@PathVariable(CLIENT_REGISTRATION_TEMPLATE_ID) String strClientRegistrationTemplateId) throws ThingsboardException {
checkParameter(CLIENT_REGISTRATION_TEMPLATE_ID, strClientRegistrationTemplateId);
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.DELETE);
- OAuth2ClientRegistrationTemplateId clientRegistrationTemplateId = new OAuth2ClientRegistrationTemplateId(toUUID(strClientRegistrationTemplateId));
- oAuth2ConfigTemplateService.deleteClientRegistrationTemplateById(clientRegistrationTemplateId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.DELETE);
+ OAuth2ClientRegistrationTemplateId clientRegistrationTemplateId = new OAuth2ClientRegistrationTemplateId(toUUID(strClientRegistrationTemplateId));
+ oAuth2ConfigTemplateService.deleteClientRegistrationTemplateById(clientRegistrationTemplateId);
}
@ApiOperation(value = "Get the list of all OAuth2 client registration templates (getClientRegistrationTemplates)" + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH,
@@ -85,12 +77,8 @@ public class OAuth2ConfigTemplateController extends BaseController {
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public List getClientRegistrationTemplates() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.READ);
- return oAuth2ConfigTemplateService.findAllClientRegistrationTemplates();
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_TEMPLATE, Operation.READ);
+ return oAuth2ConfigTemplateService.findAllClientRegistrationTemplates();
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/OAuth2Controller.java b/application/src/main/java/org/thingsboard/server/controller/OAuth2Controller.java
index db00287ee7..ef5739a481 100644
--- a/application/src/main/java/org/thingsboard/server/controller/OAuth2Controller.java
+++ b/application/src/main/java/org/thingsboard/server/controller/OAuth2Controller.java
@@ -69,25 +69,21 @@ public class OAuth2Controller extends BaseController {
"If platform type is not one of allowable values - it will just be ignored",
allowableValues = "WEB, ANDROID, IOS")
@RequestParam(required = false) String platform) throws ThingsboardException {
- try {
- if (log.isDebugEnabled()) {
- log.debug("Executing getOAuth2Clients: [{}][{}][{}]", request.getScheme(), request.getServerName(), request.getServerPort());
- Enumeration headerNames = request.getHeaderNames();
- while (headerNames.hasMoreElements()) {
- String header = headerNames.nextElement();
- log.debug("Header: {} {}", header, request.getHeader(header));
- }
+ if (log.isDebugEnabled()) {
+ log.debug("Executing getOAuth2Clients: [{}][{}][{}]", request.getScheme(), request.getServerName(), request.getServerPort());
+ Enumeration headerNames = request.getHeaderNames();
+ while (headerNames.hasMoreElements()) {
+ String header = headerNames.nextElement();
+ log.debug("Header: {} {}", header, request.getHeader(header));
}
- PlatformType platformType = null;
- if (StringUtils.isNotEmpty(platform)) {
- try {
- platformType = PlatformType.valueOf(platform);
- } catch (Exception e) {}
- }
- return oAuth2Service.getOAuth2Clients(MiscUtils.getScheme(request), MiscUtils.getDomainNameAndPort(request), pkgName, platformType);
- } catch (Exception e) {
- throw handleException(e);
}
+ PlatformType platformType = null;
+ if (StringUtils.isNotEmpty(platform)) {
+ try {
+ platformType = PlatformType.valueOf(platform);
+ } catch (Exception e) {}
+ }
+ return oAuth2Service.getOAuth2Clients(MiscUtils.getScheme(request), MiscUtils.getDomainNameAndPort(request), pkgName, platformType);
}
@ApiOperation(value = "Get current OAuth2 settings (getCurrentOAuth2Info)", notes = SYSTEM_AUTHORITY_PARAGRAPH)
@@ -95,12 +91,8 @@ public class OAuth2Controller extends BaseController {
@RequestMapping(value = "/oauth2/config", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public OAuth2Info getCurrentOAuth2Info() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.READ);
- return oAuth2Service.findOAuth2Info();
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.READ);
+ return oAuth2Service.findOAuth2Info();
}
@ApiOperation(value = "Save OAuth2 settings (saveOAuth2Info)", notes = SYSTEM_AUTHORITY_PARAGRAPH)
@@ -108,13 +100,9 @@ public class OAuth2Controller extends BaseController {
@RequestMapping(value = "/oauth2/config", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public OAuth2Info saveOAuth2Info(@RequestBody OAuth2Info oauth2Info) throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.WRITE);
- oAuth2Service.saveOAuth2Info(oauth2Info);
- return oAuth2Service.findOAuth2Info();
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.WRITE);
+ oAuth2Service.saveOAuth2Info(oauth2Info);
+ return oAuth2Service.findOAuth2Info();
}
@ApiOperation(value = "Get OAuth2 log in processing URL (getLoginProcessingUrl)", notes = "Returns the URL enclosed in " +
@@ -125,12 +113,8 @@ public class OAuth2Controller extends BaseController {
@RequestMapping(value = "/oauth2/loginProcessingUrl", method = RequestMethod.GET)
@ResponseBody
public String getLoginProcessingUrl() throws ThingsboardException {
- try {
- accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.READ);
- return "\"" + oAuth2Configuration.getLoginProcessingUrl() + "\"";
- } catch (Exception e) {
- throw handleException(e);
- }
+ accessControlService.checkPermission(getCurrentUser(), Resource.OAUTH2_CONFIGURATION_INFO, Operation.READ);
+ return "\"" + oAuth2Configuration.getLoginProcessingUrl() + "\"";
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java
index 326303110e..9b923e01dc 100644
--- a/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java
@@ -87,24 +87,20 @@ public class OtaPackageController extends BaseController {
public ResponseEntity downloadOtaPackage(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION)
@PathVariable(OTA_PACKAGE_ID) String strOtaPackageId) throws ThingsboardException {
checkParameter(OTA_PACKAGE_ID, strOtaPackageId);
- try {
- OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
- OtaPackage otaPackage = checkOtaPackageId(otaPackageId, Operation.READ);
-
- if (otaPackage.hasUrl()) {
- return ResponseEntity.badRequest().build();
- }
+ OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
+ OtaPackage otaPackage = checkOtaPackageId(otaPackageId, Operation.READ);
- ByteArrayResource resource = new ByteArrayResource(otaPackage.getData().array());
- return ResponseEntity.ok()
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + otaPackage.getFileName())
- .header("x-filename", otaPackage.getFileName())
- .contentLength(resource.contentLength())
- .contentType(parseMediaType(otaPackage.getContentType()))
- .body(resource);
- } catch (Exception e) {
- throw handleException(e);
+ if (otaPackage.hasUrl()) {
+ return ResponseEntity.badRequest().build();
}
+
+ ByteArrayResource resource = new ByteArrayResource(otaPackage.getData().array());
+ return ResponseEntity.ok()
+ .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + otaPackage.getFileName())
+ .header("x-filename", otaPackage.getFileName())
+ .contentLength(resource.contentLength())
+ .contentType(parseMediaType(otaPackage.getContentType()))
+ .body(resource);
}
@ApiOperation(value = "Get OTA Package Info (getOtaPackageInfoById)",
@@ -117,12 +113,8 @@ public class OtaPackageController extends BaseController {
public OtaPackageInfo getOtaPackageInfoById(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION)
@PathVariable(OTA_PACKAGE_ID) String strOtaPackageId) throws ThingsboardException {
checkParameter(OTA_PACKAGE_ID, strOtaPackageId);
- try {
- OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
- return checkNotNull(otaPackageService.findOtaPackageInfoById(getTenantId(), otaPackageId));
- } catch (Exception e) {
- throw handleException(e);
- }
+ OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
+ return checkNotNull(otaPackageService.findOtaPackageInfoById(getTenantId(), otaPackageId));
}
@ApiOperation(value = "Get OTA Package (getOtaPackageById)",
@@ -135,12 +127,8 @@ public class OtaPackageController extends BaseController {
public OtaPackage getOtaPackageById(@ApiParam(value = OTA_PACKAGE_ID_PARAM_DESCRIPTION)
@PathVariable(OTA_PACKAGE_ID) String strOtaPackageId) throws ThingsboardException {
checkParameter(OTA_PACKAGE_ID, strOtaPackageId);
- try {
- OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
- return checkOtaPackageId(otaPackageId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ OtaPackageId otaPackageId = new OtaPackageId(toUUID(strOtaPackageId));
+ return checkOtaPackageId(otaPackageId, Operation.READ);
}
@ApiOperation(value = "Create Or Update OTA Package Info (saveOtaPackageInfo)",
@@ -204,12 +192,8 @@ public class OtaPackageController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(otaPackageService.findTenantOtaPackagesByTenantId(getTenantId(), pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(otaPackageService.findTenantOtaPackagesByTenantId(getTenantId(), pageLink));
}
@ApiOperation(value = "Get OTA Package Infos (getOtaPackages)",
@@ -235,13 +219,9 @@ public class OtaPackageController extends BaseController {
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("deviceProfileId", strDeviceProfileId);
checkParameter("type", strType);
- try {
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- return checkNotNull(otaPackageService.findTenantOtaPackagesByTenantIdAndDeviceProfileIdAndTypeAndHasData(getTenantId(),
- new DeviceProfileId(toUUID(strDeviceProfileId)), OtaPackageType.valueOf(strType), pageLink));
- } catch (Exception e) {
- throw handleException(e);
- }
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ return checkNotNull(otaPackageService.findTenantOtaPackagesByTenantIdAndDeviceProfileIdAndTypeAndHasData(getTenantId(),
+ new DeviceProfileId(toUUID(strDeviceProfileId)), OtaPackageType.valueOf(strType), pageLink));
}
@ApiOperation(value = "Delete OTA Package (deleteOtaPackage)",
diff --git a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
index 916228147e..28f7f44e5f 100644
--- a/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
+++ b/application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
@@ -159,12 +159,8 @@ public class RpcV2Controller extends AbstractRpcController {
@ApiParam(value = RPC_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(RPC_ID) String strRpc) throws ThingsboardException {
checkParameter("RpcId", strRpc);
- try {
- RpcId rpcId = new RpcId(UUID.fromString(strRpc));
- return checkRpcId(rpcId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ RpcId rpcId = new RpcId(UUID.fromString(strRpc));
+ return checkRpcId(rpcId, Operation.READ);
}
@ApiOperation(value = "Get persistent RPC requests", notes = "Allows to query RPC calls for specific device using pagination." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@@ -187,43 +183,39 @@ public class RpcV2Controller extends AbstractRpcController {
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
checkParameter("DeviceId", strDeviceId);
- try {
- if (rpcStatus != null && rpcStatus.equals(RpcStatus.DELETED)) {
- throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "RpcStatus: DELETED");
- }
-
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- DeviceId deviceId = new DeviceId(UUID.fromString(strDeviceId));
- final DeferredResult response = new DeferredResult<>();
+ if (rpcStatus != null && rpcStatus.equals(RpcStatus.DELETED)) {
+ throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "RpcStatus: DELETED");
+ }
- accessValidator.validate(getCurrentUser(), Operation.RPC_CALL, deviceId, new HttpValidationCallback(response, new FutureCallback<>() {
- @Override
- public void onSuccess(@Nullable DeferredResult result) {
- PageData rpcCalls;
- if (rpcStatus != null) {
- rpcCalls = rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
- } else {
- rpcCalls = rpcService.findAllByDeviceId(tenantId, deviceId, pageLink);
- }
- response.setResult(new ResponseEntity<>(rpcCalls, HttpStatus.OK));
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ DeviceId deviceId = new DeviceId(UUID.fromString(strDeviceId));
+ final DeferredResult response = new DeferredResult<>();
+
+ accessValidator.validate(getCurrentUser(), Operation.RPC_CALL, deviceId, new HttpValidationCallback(response, new FutureCallback<>() {
+ @Override
+ public void onSuccess(@Nullable DeferredResult result) {
+ PageData rpcCalls;
+ if (rpcStatus != null) {
+ rpcCalls = rpcService.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
+ } else {
+ rpcCalls = rpcService.findAllByDeviceId(tenantId, deviceId, pageLink);
}
+ response.setResult(new ResponseEntity<>(rpcCalls, HttpStatus.OK));
+ }
- @Override
- public void onFailure(Throwable e) {
- ResponseEntity entity;
- if (e instanceof ToErrorResponseEntity) {
- entity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
- } else {
- entity = new ResponseEntity(HttpStatus.UNAUTHORIZED);
- }
- response.setResult(entity);
+ @Override
+ public void onFailure(Throwable e) {
+ ResponseEntity entity;
+ if (e instanceof ToErrorResponseEntity) {
+ entity = ((ToErrorResponseEntity) e).toErrorResponseEntity();
+ } else {
+ entity = new ResponseEntity(HttpStatus.UNAUTHORIZED);
}
- }));
- return response;
- } catch (Exception e) {
- throw handleException(e);
- }
+ response.setResult(entity);
+ }
+ }));
+ return response;
}
@ApiOperation(value = "Delete persistent RPC", notes = "Deletes the persistent RPC request." + TENANT_AUTHORITY_PARAGRAPH)
@@ -234,25 +226,21 @@ public class RpcV2Controller extends AbstractRpcController {
@ApiParam(value = RPC_ID_PARAM_DESCRIPTION, required = true)
@PathVariable(RPC_ID) String strRpc) throws ThingsboardException {
checkParameter("RpcId", strRpc);
- try {
- RpcId rpcId = new RpcId(UUID.fromString(strRpc));
- Rpc rpc = checkRpcId(rpcId, Operation.DELETE);
-
- if (rpc != null) {
- if (rpc.getStatus().equals(RpcStatus.QUEUED)) {
- RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId());
- log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc);
- tbClusterService.pushMsgToCore(removeMsg, null);
- }
+ RpcId rpcId = new RpcId(UUID.fromString(strRpc));
+ Rpc rpc = checkRpcId(rpcId, Operation.DELETE);
+
+ if (rpc != null) {
+ if (rpc.getStatus().equals(RpcStatus.QUEUED)) {
+ RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId());
+ log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc);
+ tbClusterService.pushMsgToCore(removeMsg, null);
+ }
- rpcService.deleteRpc(getTenantId(), rpcId);
- rpc.setStatus(RpcStatus.DELETED);
+ rpcService.deleteRpc(getTenantId(), rpcId);
+ rpc.setStatus(RpcStatus.DELETED);
- TbMsg msg = TbMsg.newMsg(RPC_DELETED, rpc.getDeviceId(), TbMsgMetaData.EMPTY, JacksonUtil.toString(rpc));
- tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null);
- }
- } catch (Exception e) {
- throw handleException(e);
+ TbMsg msg = TbMsg.newMsg(RPC_DELETED, rpc.getDeviceId(), TbMsgMetaData.EMPTY, JacksonUtil.toString(rpc));
+ tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null);
}
}
}
diff --git a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java
index 16e15969f4..81cf8be9fa 100644
--- a/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java
+++ b/application/src/main/java/org/thingsboard/server/controller/RuleChainController.java
@@ -15,6 +15,7 @@
*/
package org.thingsboard.server.controller;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -166,12 +167,8 @@ public class RuleChainController extends BaseController {
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
checkParameter(RULE_CHAIN_ID, strRuleChainId);
- try {
- RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
- return checkRuleChain(ruleChainId, Operation.READ);
- } catch (Exception e) {
- throw handleException(e);
- }
+ RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
+ return checkRuleChain(ruleChainId, Operation.READ);
}
@ApiOperation(value = "Get Rule Chain output labels (getRuleChainOutputLabels)",
@@ -184,13 +181,9 @@ public class RuleChainController extends BaseController {
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
checkParameter(RULE_CHAIN_ID, strRuleChainId);
- try {
- RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
- checkRuleChain(ruleChainId, Operation.READ);
- return tbRuleChainService.getRuleChainOutputLabels(getTenantId(), ruleChainId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
+ checkRuleChain(ruleChainId, Operation.READ);
+ return tbRuleChainService.getRuleChainOutputLabels(getTenantId(), ruleChainId);
}
@ApiOperation(value = "Get output labels usage (getRuleChainOutputLabelsUsage)",
@@ -203,13 +196,9 @@ public class RuleChainController extends BaseController {
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
checkParameter(RULE_CHAIN_ID, strRuleChainId);
- try {
- RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
- checkRuleChain(ruleChainId, Operation.READ);
- return tbRuleChainService.getOutputLabelUsage(getCurrentUser().getTenantId(), ruleChainId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
+ checkRuleChain(ruleChainId, Operation.READ);
+ return tbRuleChainService.getOutputLabelUsage(getCurrentUser().getTenantId(), ruleChainId);
}
@ApiOperation(value = "Get Rule Chain (getRuleChainById)",
@@ -221,13 +210,9 @@ public class RuleChainController extends BaseController {
@ApiParam(value = RULE_CHAIN_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_CHAIN_ID) String strRuleChainId) throws ThingsboardException {
checkParameter(RULE_CHAIN_ID, strRuleChainId);
- try {
- RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
- checkRuleChain(ruleChainId, Operation.READ);
- return ruleChainService.loadRuleChainMetaData(getTenantId(), ruleChainId);
- } catch (Exception e) {
- throw handleException(e);
- }
+ RuleChainId ruleChainId = new RuleChainId(toUUID(strRuleChainId));
+ checkRuleChain(ruleChainId, Operation.READ);
+ return ruleChainService.loadRuleChainMetaData(getTenantId(), ruleChainId);
}
@ApiOperation(value = "Create Or Update Rule Chain (saveRuleChain)",
@@ -319,17 +304,13 @@ public class RuleChainController extends BaseController {
@RequestParam(required = false) String sortProperty,
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES)
@RequestParam(required = false) String sortOrder) throws ThingsboardException {
- try {
- TenantId tenantId = getCurrentUser().getTenantId();
- PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
- RuleChainType type = RuleChainType.CORE;
- if (typeStr != null && typeStr.trim().length() > 0) {
- type = RuleChainType.valueOf(typeStr);
- }
- return checkNotNull(ruleChainService.findTenantRuleChainsByType(tenantId, type, pageLink));
- } catch (Exception e) {
- throw handleException(e);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
+ RuleChainType type = RuleChainType.CORE;
+ if (typeStr != null && typeStr.trim().length() > 0) {
+ type = RuleChainType.valueOf(typeStr);
}
+ return checkNotNull(ruleChainService.findTenantRuleChainsByType(tenantId, type, pageLink));
}
@ApiOperation(value = "Delete rule chain (deleteRuleChain)",
@@ -357,25 +338,21 @@ public class RuleChainController extends BaseController {
@ApiParam(value = RULE_NODE_ID_PARAM_DESCRIPTION)
@PathVariable(RULE_NODE_ID) String strRuleNodeId) throws ThingsboardException {
checkParameter(RULE_NODE_ID, strRuleNodeId);
- try {
- RuleNodeId ruleNodeId = new RuleNodeId(toUUID(strRuleNodeId));
- checkRuleNode(ruleNodeId, Operation.READ);
- TenantId tenantId = getCurrentUser().getTenantId();
- List events = eventService.findLatestEvents(tenantId, ruleNodeId, EventType.DEBUG_RULE_NODE, 2);
- JsonNode result = null;
- if (events != null) {
- for (EventInfo event : events) {
- JsonNode body = event.getBody();
- if (body.has("type") && body.get("type").asText().equals("IN")) {
- result = body;
- break;
- }
+ RuleNodeId ruleNodeId = new RuleNodeId(toUUID(strRuleNodeId));
+ checkRuleNode(ruleNodeId, Operation.READ);
+ TenantId tenantId = getCurrentUser().getTenantId();
+ List events = eventService.findLatestEvents(tenantId, ruleNodeId, EventType.DEBUG_RULE_NODE, 2);
+ JsonNode result = null;
+ if (events != null) {
+ for (EventInfo event : events) {
+ JsonNode body = event.getBody();
+ if (body.has("type") && body.get("type").asText().equals("IN")) {
+ result = body;
+ break;
}
}
- return result;
- } catch (Exception e) {
- throw handleException(e);
}
+ return result;
}
@ApiOperation(value = "Is TBEL script executor enabled",
@@ -396,74 +373,70 @@ public class RuleChainController extends BaseController {
@ApiParam(value = "Script language: JS or TBEL")
@RequestParam(required = false) ScriptLanguage scriptLang,
@ApiParam(value = "Test JS request. See API call description above.")
- @RequestBody JsonNode inputParams) throws ThingsboardException {
+ @RequestBody JsonNode inputParams) throws ThingsboardException, JsonProcessingException {
+ String script = inputParams.get("script").asText();
+ String scriptType = inputParams.get("scriptType").asText();
+ JsonNode argNamesJson = inputParams.get("argNames");
+ String[] argNames = objectMapper.treeToValue(argNamesJson, String[].class);
+
+ String data = inputParams.get("msg").asText();
+ JsonNode metadataJson = inputParams.get("metadata");
+ Map metadata = objectMapper.convertValue(metadataJson, new TypeReference