1585 changed files with 80840 additions and 20647 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,72 @@ |
|||||
|
-- |
||||
|
-- Copyright © 2016-2022 The Thingsboard Authors |
||||
|
-- |
||||
|
-- Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
-- you may not use this file except in compliance with the License. |
||||
|
-- You may obtain a copy of the License at |
||||
|
-- |
||||
|
-- http://www.apache.org/licenses/LICENSE-2.0 |
||||
|
-- |
||||
|
-- Unless required by applicable law or agreed to in writing, software |
||||
|
-- distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
-- See the License for the specific language governing permissions and |
||||
|
-- limitations under the License. |
||||
|
-- |
||||
|
|
||||
|
ALTER TABLE device |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE device_profile |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE asset |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE rule_chain |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE rule_node |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE dashboard |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE customer |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE widgets_bundle |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
ALTER TABLE entity_view |
||||
|
ADD COLUMN IF NOT EXISTS external_id UUID; |
||||
|
|
||||
|
CREATE INDEX IF NOT EXISTS idx_device_external_id ON device(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_device_profile_external_id ON device_profile(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_asset_external_id ON asset(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_rule_chain_external_id ON rule_chain(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_rule_node_external_id ON rule_node(rule_chain_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_dashboard_external_id ON dashboard(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_customer_external_id ON customer(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_widgets_bundle_external_id ON widgets_bundle(tenant_id, external_id); |
||||
|
CREATE INDEX IF NOT EXISTS idx_entity_view_external_id ON entity_view(tenant_id, external_id); |
||||
|
|
||||
|
CREATE INDEX IF NOT EXISTS idx_rule_node_type ON rule_node(type); |
||||
|
|
||||
|
ALTER TABLE admin_settings |
||||
|
ADD COLUMN IF NOT EXISTS tenant_id uuid NOT NULL DEFAULT '13814000-1dd2-11b2-8080-808080808080'; |
||||
|
|
||||
|
CREATE TABLE IF NOT EXISTS queue ( |
||||
|
id uuid NOT NULL CONSTRAINT queue_pkey PRIMARY KEY, |
||||
|
created_time bigint NOT NULL, |
||||
|
tenant_id uuid, |
||||
|
name varchar(255), |
||||
|
topic varchar(255), |
||||
|
poll_interval int, |
||||
|
partitions int, |
||||
|
consumer_per_partition boolean, |
||||
|
pack_processing_timeout bigint, |
||||
|
submit_strategy varchar(255), |
||||
|
processing_strategy varchar(255), |
||||
|
additional_info varchar |
||||
|
); |
||||
|
|
||||
|
CREATE TABLE IF NOT EXISTS user_auth_settings ( |
||||
|
id uuid NOT NULL CONSTRAINT user_auth_settings_pkey PRIMARY KEY, |
||||
|
created_time bigint NOT NULL, |
||||
|
user_id uuid UNIQUE NOT NULL CONSTRAINT fk_user_auth_settings_user_id REFERENCES tb_user(id), |
||||
|
two_fa_settings varchar |
||||
|
); |
||||
|
|
||||
@ -0,0 +1,49 @@ |
|||||
|
-- |
||||
|
-- Copyright © 2016-2022 The Thingsboard Authors |
||||
|
-- |
||||
|
-- Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
-- you may not use this file except in compliance with the License. |
||||
|
-- You may obtain a copy of the License at |
||||
|
-- |
||||
|
-- http://www.apache.org/licenses/LICENSE-2.0 |
||||
|
-- |
||||
|
-- Unless required by applicable law or agreed to in writing, software |
||||
|
-- distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
-- See the License for the specific language governing permissions and |
||||
|
-- limitations under the License. |
||||
|
-- |
||||
|
|
||||
|
ALTER TABLE device_profile |
||||
|
ADD COLUMN IF NOT EXISTS default_queue_id uuid; |
||||
|
|
||||
|
DO |
||||
|
$$ |
||||
|
BEGIN |
||||
|
IF EXISTS |
||||
|
(SELECT column_name |
||||
|
FROM information_schema.columns |
||||
|
WHERE table_name = 'device_profile' |
||||
|
AND column_name = 'default_queue_name' |
||||
|
) |
||||
|
THEN |
||||
|
UPDATE device_profile |
||||
|
SET default_queue_id = q.id |
||||
|
FROM queue as q |
||||
|
WHERE default_queue_name = q.name; |
||||
|
END IF; |
||||
|
END |
||||
|
$$; |
||||
|
|
||||
|
DO |
||||
|
$$ |
||||
|
BEGIN |
||||
|
IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conname = 'fk_default_queue_device_profile') THEN |
||||
|
ALTER TABLE device_profile |
||||
|
ADD CONSTRAINT fk_default_queue_device_profile FOREIGN KEY (default_queue_id) REFERENCES queue (id); |
||||
|
END IF; |
||||
|
END; |
||||
|
$$; |
||||
|
|
||||
|
ALTER TABLE device_profile |
||||
|
DROP COLUMN IF EXISTS default_queue_name; |
||||
@ -0,0 +1,348 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import com.google.common.util.concurrent.Futures; |
||||
|
import com.google.common.util.concurrent.ListenableFuture; |
||||
|
import com.google.common.util.concurrent.MoreExecutors; |
||||
|
import io.swagger.annotations.ApiOperation; |
||||
|
import io.swagger.annotations.ApiParam; |
||||
|
import lombok.Data; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.GetMapping; |
||||
|
import org.springframework.web.bind.annotation.PathVariable; |
||||
|
import org.springframework.web.bind.annotation.PostMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestBody; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestParam; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.springframework.web.context.request.async.DeferredResult; |
||||
|
import org.thingsboard.server.common.data.EntityType; |
||||
|
import org.thingsboard.server.common.data.StringUtils; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.id.EntityId; |
||||
|
import org.thingsboard.server.common.data.id.EntityIdFactory; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.page.PageLink; |
||||
|
import org.thingsboard.server.common.data.sync.vc.EntityDataDiff; |
||||
|
import org.thingsboard.server.common.data.sync.vc.EntityDataInfo; |
||||
|
import org.thingsboard.server.common.data.sync.vc.EntityVersion; |
||||
|
import org.thingsboard.server.common.data.sync.vc.VersionCreationResult; |
||||
|
import org.thingsboard.server.common.data.sync.vc.VersionLoadResult; |
||||
|
import org.thingsboard.server.common.data.sync.vc.VersionedEntityInfo; |
||||
|
import org.thingsboard.server.common.data.sync.vc.request.create.VersionCreateRequest; |
||||
|
import org.thingsboard.server.common.data.sync.vc.request.load.VersionLoadRequest; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
import org.thingsboard.server.service.security.permission.Operation; |
||||
|
import org.thingsboard.server.service.security.permission.Resource; |
||||
|
import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService; |
||||
|
|
||||
|
import java.util.ArrayList; |
||||
|
import java.util.List; |
||||
|
import java.util.UUID; |
||||
|
|
||||
|
import static org.thingsboard.server.controller.ControllerConstants.NEW_LINE; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DESCRIPTION; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.PAGE_NUMBER_DESCRIPTION; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.ENTITY_VERSION_TEXT_SEARCH_DESCRIPTION; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_ALLOWABLE_VALUES; |
||||
|
import static org.thingsboard.server.controller.ControllerConstants.VC_REQUEST_ID_PARAM_DESCRIPTION; |
||||
|
|
||||
|
@RestController |
||||
|
@TbCoreComponent |
||||
|
@RequestMapping("/api/entities/vc") |
||||
|
@PreAuthorize("hasAuthority('TENANT_ADMIN')") |
||||
|
@RequiredArgsConstructor |
||||
|
public class EntitiesVersionControlController extends BaseController { |
||||
|
|
||||
|
private final EntitiesVersionControlService versionControlService; |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"SINGLE_ENTITY:" + NEW_LINE + |
||||
|
"```\n{\n" + |
||||
|
" \"type\": \"SINGLE_ENTITY\",\n" + |
||||
|
"\n" + |
||||
|
" \"versionName\": \"Version 1.0\",\n" + |
||||
|
" \"branch\": \"dev\",\n" + |
||||
|
"\n" + |
||||
|
" \"entityId\": {\n" + |
||||
|
" \"entityType\": \"DEVICE\",\n" + |
||||
|
" \"id\": \"b79448e0-d4f4-11ec-847b-0f432358ab48\"\n" + |
||||
|
" },\n" + |
||||
|
" \"config\": {\n" + |
||||
|
" \"saveRelations\": true\n" + |
||||
|
" }\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"COMPLEX:" + NEW_LINE + |
||||
|
"```\n{\n" + |
||||
|
" \"type\": \"COMPLEX\",\n" + |
||||
|
"\n" + |
||||
|
" \"versionName\": \"Devices and profiles: release 2\",\n" + |
||||
|
" \"branch\": \"master\",\n" + |
||||
|
"\n" + |
||||
|
" \"syncStrategy\": \"OVERWRITE\",\n" + |
||||
|
" \"entityTypes\": {\n" + |
||||
|
" \"DEVICE\": {\n" + |
||||
|
" \"syncStrategy\": null,\n" + |
||||
|
" \"allEntities\": true,\n" + |
||||
|
" \"saveRelations\": true\n" + |
||||
|
" },\n" + |
||||
|
" \"DEVICE_PROFILE\": {\n" + |
||||
|
" \"syncStrategy\": \"MERGE\",\n" + |
||||
|
" \"allEntities\": false,\n" + |
||||
|
" \"entityIds\": [\n" + |
||||
|
" \"b79448e0-d4f4-11ec-847b-0f432358ab48\"\n" + |
||||
|
" ],\n" + |
||||
|
" \"saveRelations\": true\n" + |
||||
|
" }\n" + |
||||
|
" }\n" + |
||||
|
"}\n```") |
||||
|
@PostMapping("/version") |
||||
|
public DeferredResult<UUID> saveEntitiesVersion(@RequestBody VersionCreateRequest request) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.WRITE); |
||||
|
return wrapFuture(versionControlService.saveEntitiesVersion(user, request)); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "") |
||||
|
@GetMapping(value = "/version/{requestId}/status") |
||||
|
public VersionCreationResult getVersionCreateRequestStatus(@ApiParam(value = VC_REQUEST_ID_PARAM_DESCRIPTION, required = true) |
||||
|
@PathVariable UUID requestId) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
return versionControlService.getVersionCreateStatus(getCurrentUser(), requestId); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"```\n[\n" + |
||||
|
" {\n" + |
||||
|
" \"id\": \"c30c8bcaed3f0813649f0dee51a89d04d0a12b28\",\n" + |
||||
|
" \"name\": \"Device profile 1 version 1.0\"\n" + |
||||
|
" }\n" + |
||||
|
"]\n```") |
||||
|
@GetMapping(value = "/version/{branch}/{entityType}/{externalEntityUuid}", params = {"pageSize", "page"}) |
||||
|
public DeferredResult<PageData<EntityVersion>> listEntityVersions(@PathVariable String branch, |
||||
|
@PathVariable EntityType entityType, |
||||
|
@PathVariable UUID externalEntityUuid, |
||||
|
@ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) |
||||
|
@RequestParam int pageSize, |
||||
|
@ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) |
||||
|
@RequestParam int page, |
||||
|
@ApiParam(value = ENTITY_VERSION_TEXT_SEARCH_DESCRIPTION) |
||||
|
@RequestParam(required = false) String textSearch, |
||||
|
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = "timestamp") |
||||
|
@RequestParam(required = false) String sortProperty, |
||||
|
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) |
||||
|
@RequestParam(required = false) String sortOrder) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
EntityId externalEntityId = EntityIdFactory.getByTypeAndUuid(entityType, externalEntityUuid); |
||||
|
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); |
||||
|
return wrapFuture(versionControlService.listEntityVersions(getTenantId(), branch, externalEntityId, pageLink)); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"```\n[\n" + |
||||
|
" {\n" + |
||||
|
" \"id\": \"c30c8bcaed3f0813649f0dee51a89d04d0a12b28\",\n" + |
||||
|
" \"name\": \"Device profiles from dev\"\n" + |
||||
|
" }\n" + |
||||
|
"]\n```") |
||||
|
@GetMapping(value = "/version/{branch}/{entityType}", params = {"pageSize", "page"}) |
||||
|
public DeferredResult<PageData<EntityVersion>> listEntityTypeVersions(@PathVariable String branch, |
||||
|
@PathVariable EntityType entityType, |
||||
|
@ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) |
||||
|
@RequestParam int pageSize, |
||||
|
@ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) |
||||
|
@RequestParam int page, |
||||
|
@ApiParam(value = ENTITY_VERSION_TEXT_SEARCH_DESCRIPTION) |
||||
|
@RequestParam(required = false) String textSearch, |
||||
|
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = "timestamp") |
||||
|
@RequestParam(required = false) String sortProperty, |
||||
|
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) |
||||
|
@RequestParam(required = false) String sortOrder) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); |
||||
|
return wrapFuture(versionControlService.listEntityTypeVersions(getTenantId(), branch, entityType, pageLink)); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"```\n[\n" + |
||||
|
" {\n" + |
||||
|
" \"id\": \"ba9baaca1742b730e7331f31a6a51da5fc7da7f7\",\n" + |
||||
|
" \"name\": \"Device 1 removed\"\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"id\": \"b3c28d722d328324c7c15b0b30047b0c40011cf7\",\n" + |
||||
|
" \"name\": \"Device profiles added\"\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"id\": \"c30c8bcaed3f0813649f0dee51a89d04d0a12b28\",\n" + |
||||
|
" \"name\": \"Devices added\"\n" + |
||||
|
" }\n" + |
||||
|
"]\n```") |
||||
|
@GetMapping(value = "/version/{branch}", params = {"pageSize", "page"}) |
||||
|
public DeferredResult<PageData<EntityVersion>> listVersions(@PathVariable String branch, |
||||
|
@ApiParam(value = PAGE_SIZE_DESCRIPTION, required = true) |
||||
|
@RequestParam int pageSize, |
||||
|
@ApiParam(value = PAGE_NUMBER_DESCRIPTION, required = true) |
||||
|
@RequestParam int page, |
||||
|
@ApiParam(value = ENTITY_VERSION_TEXT_SEARCH_DESCRIPTION) |
||||
|
@RequestParam(required = false) String textSearch, |
||||
|
@ApiParam(value = SORT_PROPERTY_DESCRIPTION, allowableValues = "timestamp") |
||||
|
@RequestParam(required = false) String sortProperty, |
||||
|
@ApiParam(value = SORT_ORDER_DESCRIPTION, allowableValues = SORT_ORDER_ALLOWABLE_VALUES) |
||||
|
@RequestParam(required = false) String sortOrder) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder); |
||||
|
return wrapFuture(versionControlService.listVersions(getTenantId(), branch, pageLink)); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@GetMapping("/entity/{branch}/{entityType}/{versionId}") |
||||
|
public DeferredResult<List<VersionedEntityInfo>> listEntitiesAtVersion(@PathVariable String branch, |
||||
|
@PathVariable EntityType entityType, |
||||
|
@PathVariable String versionId) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
return wrapFuture(versionControlService.listEntitiesAtVersion(getTenantId(), branch, versionId, entityType)); |
||||
|
} |
||||
|
|
||||
|
@GetMapping("/entity/{branch}/{versionId}") |
||||
|
public DeferredResult<List<VersionedEntityInfo>> listAllEntitiesAtVersion(@PathVariable String branch, |
||||
|
@PathVariable String versionId) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
return wrapFuture(versionControlService.listAllEntitiesAtVersion(getTenantId(), branch, versionId)); |
||||
|
} |
||||
|
|
||||
|
@GetMapping("/info/{versionId}/{entityType}/{externalEntityUuid}") |
||||
|
public DeferredResult<EntityDataInfo> getEntityDataInfo(@PathVariable String versionId, |
||||
|
@PathVariable EntityType entityType, |
||||
|
@PathVariable UUID externalEntityUuid) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
EntityId entityId = EntityIdFactory.getByTypeAndUuid(entityType, externalEntityUuid); |
||||
|
return wrapFuture(versionControlService.getEntityDataInfo(getCurrentUser(), entityId, versionId)); |
||||
|
} |
||||
|
|
||||
|
@GetMapping("/diff/{branch}/{entityType}/{internalEntityUuid}") |
||||
|
public DeferredResult<EntityDataDiff> compareEntityDataToVersion(@PathVariable String branch, |
||||
|
@PathVariable EntityType entityType, |
||||
|
@PathVariable UUID internalEntityUuid, |
||||
|
@RequestParam String versionId) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
EntityId entityId = EntityIdFactory.getByTypeAndUuid(entityType, internalEntityUuid); |
||||
|
return wrapFuture(versionControlService.compareEntityDataToVersion(getCurrentUser(), branch, entityId, versionId)); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"SINGLE_ENTITY:" + NEW_LINE + |
||||
|
"```\n{\n" + |
||||
|
" \"type\": \"SINGLE_ENTITY\",\n" + |
||||
|
" \n" + |
||||
|
" \"branch\": \"dev\",\n" + |
||||
|
" \"versionId\": \"b3c28d722d328324c7c15b0b30047b0c40011cf7\",\n" + |
||||
|
" \n" + |
||||
|
" \"externalEntityId\": {\n" + |
||||
|
" \"entityType\": \"DEVICE\",\n" + |
||||
|
" \"id\": \"b7944123-d4f4-11ec-847b-0f432358ab48\"\n" + |
||||
|
" },\n" + |
||||
|
" \"config\": {\n" + |
||||
|
" \"loadRelations\": false,\n" + |
||||
|
" \"findExistingEntityByName\": false\n" + |
||||
|
" }\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"ENTITY_TYPE:" + NEW_LINE + |
||||
|
"```\n{\n" + |
||||
|
" \"type\": \"ENTITY_TYPE\",\n" + |
||||
|
"\n" + |
||||
|
" \"branch\": \"dev\",\n" + |
||||
|
" \"versionId\": \"b3c28d722d328324c7c15b0b30047b0c40011cf7\",\n" + |
||||
|
"\n" + |
||||
|
" \"entityTypes\": {\n" + |
||||
|
" \"DEVICE\": {\n" + |
||||
|
" \"loadRelations\": false,\n" + |
||||
|
" \"findExistingEntityByName\": false,\n" + |
||||
|
" \"removeOtherEntities\": true\n" + |
||||
|
" }\n" + |
||||
|
" }\n" + |
||||
|
"}\n```") |
||||
|
@PostMapping("/entity") |
||||
|
public UUID loadEntitiesVersion(@RequestBody VersionLoadRequest request) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
accessControlService.checkPermission(user, Resource.VERSION_CONTROL, Operation.WRITE); |
||||
|
return versionControlService.loadEntitiesVersion(user, request); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "", notes = "") |
||||
|
@GetMapping(value = "/entity/{requestId}/status") |
||||
|
public VersionLoadResult getVersionLoadRequestStatus(@ApiParam(value = VC_REQUEST_ID_PARAM_DESCRIPTION, required = true) |
||||
|
@PathVariable UUID requestId) throws Exception { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
return versionControlService.getVersionLoadStatus(getCurrentUser(), requestId); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "", notes = "" + |
||||
|
"```\n[\n" + |
||||
|
" {\n" + |
||||
|
" \"name\": \"master\",\n" + |
||||
|
" \"default\": true\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"name\": \"dev\",\n" + |
||||
|
" \"default\": false\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"name\": \"dev-2\",\n" + |
||||
|
" \"default\": false\n" + |
||||
|
" }\n" + |
||||
|
"]\n\n```") |
||||
|
@GetMapping("/branches") |
||||
|
public DeferredResult<List<BranchInfo>> listBranches() throws ThingsboardException { |
||||
|
try { |
||||
|
accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); |
||||
|
final TenantId tenantId = getTenantId(); |
||||
|
ListenableFuture<List<String>> branches = versionControlService.listBranches(tenantId); |
||||
|
return wrapFuture(Futures.transform(branches, remoteBranches -> { |
||||
|
List<BranchInfo> infos = new ArrayList<>(); |
||||
|
|
||||
|
String defaultBranch = versionControlService.getVersionControlSettings(tenantId).getDefaultBranch(); |
||||
|
if (StringUtils.isNotEmpty(defaultBranch)) { |
||||
|
infos.add(new BranchInfo(defaultBranch, true)); |
||||
|
} |
||||
|
|
||||
|
remoteBranches.forEach(branch -> { |
||||
|
if (!branch.equals(defaultBranch)) { |
||||
|
infos.add(new BranchInfo(branch, false)); |
||||
|
} |
||||
|
}); |
||||
|
return infos; |
||||
|
}, MoreExecutors.directExecutor())); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Data |
||||
|
public static class BranchInfo { |
||||
|
private final String name; |
||||
|
private final boolean isDefault; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,272 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import io.swagger.annotations.ApiOperation; |
||||
|
import io.swagger.annotations.ApiParam; |
||||
|
import lombok.Data; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.DeleteMapping; |
||||
|
import org.springframework.web.bind.annotation.GetMapping; |
||||
|
import org.springframework.web.bind.annotation.PostMapping; |
||||
|
import org.springframework.web.bind.annotation.PutMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestBody; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestParam; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.account.AccountTwoFaSettings; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; |
||||
|
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import javax.validation.Valid; |
||||
|
import java.util.Collections; |
||||
|
import java.util.List; |
||||
|
import java.util.stream.Collectors; |
||||
|
|
||||
|
import static org.thingsboard.server.controller.ControllerConstants.NEW_LINE; |
||||
|
|
||||
|
@RestController |
||||
|
@RequestMapping("/api/2fa") |
||||
|
@TbCoreComponent |
||||
|
@RequiredArgsConstructor |
||||
|
public class TwoFaConfigController extends BaseController { |
||||
|
|
||||
|
private final TwoFaConfigManager twoFaConfigManager; |
||||
|
private final TwoFactorAuthService twoFactorAuthService; |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Get account 2FA settings (getAccountTwoFaSettings)", |
||||
|
notes = "Get user's account 2FA configuration. Configuration contains configs for different 2FA providers." + NEW_LINE + |
||||
|
"Example:\n" + |
||||
|
"```\n{\n \"configs\": {\n" + |
||||
|
" \"EMAIL\": {\n \"providerType\": \"EMAIL\",\n \"useByDefault\": true,\n \"email\": \"tenant@thingsboard.org\"\n },\n" + |
||||
|
" \"TOTP\": {\n \"providerType\": \"TOTP\",\n \"useByDefault\": false,\n \"authUrl\": \"otpauth://totp/TB%202FA:tenant@thingsboard.org?issuer=TB+2FA&secret=P6Z2TLYTASOGP6LCJZAD24ETT5DACNNX\"\n },\n" + |
||||
|
" \"SMS\": {\n \"providerType\": \"SMS\",\n \"useByDefault\": false,\n \"phoneNumber\": \"+380501253652\"\n }\n" + |
||||
|
" }\n}\n```" + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@GetMapping("/account/settings") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public AccountTwoFaSettings getAccountTwoFaSettings() throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
return twoFaConfigManager.getAccountTwoFaSettings(user.getTenantId(), user.getId()).orElse(null); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Generate 2FA account config (generateTwoFaAccountConfig)", |
||||
|
notes = "Generate new 2FA account config template for specified provider type. " + NEW_LINE + |
||||
|
"For TOTP, this will return a corresponding account config template " + |
||||
|
"with a generated OTP auth URL (with new random secret key for each API call) that can be then " + |
||||
|
"converted to a QR code to scan with an authenticator app. Example:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providerType\": \"TOTP\",\n" + |
||||
|
" \"useByDefault\": false,\n" + |
||||
|
" \"authUrl\": \"otpauth://totp/TB%202FA:tenant@thingsboard.org?issuer=TB+2FA&secret=PNJDNWJVAK4ZTUYT7RFGPQLXA7XGU7PX\"\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"For EMAIL, the generated config will contain email from user's account:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providerType\": \"EMAIL\",\n" + |
||||
|
" \"useByDefault\": false,\n" + |
||||
|
" \"email\": \"tenant@thingsboard.org\"\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"For SMS 2FA this method will just return a config with empty/default values as there is nothing to generate/preset:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providerType\": \"SMS\",\n" + |
||||
|
" \"useByDefault\": false,\n" + |
||||
|
" \"phoneNumber\": null\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"Will throw an error (Bad Request) if the provider is not configured for usage. " + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@PostMapping("/account/config/generate") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public TwoFaAccountConfig generateTwoFaAccountConfig(@ApiParam(value = "2FA provider type to generate new account config for", defaultValue = "TOTP", required = true) |
||||
|
@RequestParam TwoFaProviderType providerType) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
return twoFactorAuthService.generateNewAccountConfig(user, providerType); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Submit 2FA account config (submitTwoFaAccountConfig)", |
||||
|
notes = "Submit 2FA account config to prepare for a future verification. " + |
||||
|
"Basically, this method will send a verification code for a given account config, if this has " + |
||||
|
"sense for a chosen 2FA provider. This code is needed to then verify and save the account config." + NEW_LINE + |
||||
|
"Example of EMAIL 2FA account config:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providerType\": \"EMAIL\",\n" + |
||||
|
" \"useByDefault\": true,\n" + |
||||
|
" \"email\": \"separate-email-for-2fa@thingsboard.org\"\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"Example of SMS 2FA account config:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providerType\": \"SMS\",\n" + |
||||
|
" \"useByDefault\": false,\n" + |
||||
|
" \"phoneNumber\": \"+38012312321\"\n" + |
||||
|
"}\n```" + NEW_LINE + |
||||
|
"For TOTP this method does nothing." + NEW_LINE + |
||||
|
"Will throw an error (Bad Request) if submitted account config is not valid, " + |
||||
|
"or if the provider is not configured for usage. " + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@PostMapping("/account/config/submit") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public void submitTwoFaAccountConfig(@Valid @RequestBody TwoFaAccountConfig accountConfig) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
twoFactorAuthService.prepareVerificationCode(user, accountConfig, false); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Verify and save 2FA account config (verifyAndSaveTwoFaAccountConfig)", |
||||
|
notes = "Checks the verification code for submitted config, and if it is correct, saves the provided account config. " + NEW_LINE + |
||||
|
"Returns whole account's 2FA settings object.\n" + |
||||
|
"Will throw an error (Bad Request) if the provider is not configured for usage. " + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@PostMapping("/account/config") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public AccountTwoFaSettings verifyAndSaveTwoFaAccountConfig(@Valid @RequestBody TwoFaAccountConfig accountConfig, |
||||
|
@RequestParam(required = false) String verificationCode) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
if (twoFaConfigManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig.getProviderType()).isPresent()) { |
||||
|
throw new IllegalArgumentException("2FA provider is already configured"); |
||||
|
} |
||||
|
|
||||
|
boolean verificationSuccess; |
||||
|
if (accountConfig.getProviderType() != TwoFaProviderType.BACKUP_CODE) { |
||||
|
verificationSuccess = twoFactorAuthService.checkVerificationCode(user, verificationCode, accountConfig, false); |
||||
|
} else { |
||||
|
verificationSuccess = true; |
||||
|
} |
||||
|
if (verificationSuccess) { |
||||
|
return twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig); |
||||
|
} else { |
||||
|
throw new IllegalArgumentException("Verification code is incorrect"); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Update 2FA account config (updateTwoFaAccountConfig)", notes = |
||||
|
"Update config for a given provider type. \n" + |
||||
|
"Update request example:\n" + |
||||
|
"```\n{\n \"useByDefault\": true\n}\n```\n" + |
||||
|
"Returns whole account's 2FA settings object.\n" + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@PutMapping("/account/config") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public AccountTwoFaSettings updateTwoFaAccountConfig(@RequestParam TwoFaProviderType providerType, |
||||
|
@RequestBody TwoFaAccountConfigUpdateRequest updateRequest) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
|
||||
|
TwoFaAccountConfig accountConfig = twoFaConfigManager.getTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType) |
||||
|
.orElseThrow(() -> new IllegalArgumentException("Config for " + providerType + " 2FA provider not found")); |
||||
|
accountConfig.setUseByDefault(updateRequest.isUseByDefault()); |
||||
|
return twoFaConfigManager.saveTwoFaAccountConfig(user.getTenantId(), user.getId(), accountConfig); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Delete 2FA account config (deleteTwoFaAccountConfig)", notes = |
||||
|
"Delete 2FA config for a given 2FA provider type. \n" + |
||||
|
"Returns whole account's 2FA settings object.\n" + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER) |
||||
|
@DeleteMapping("/account/config") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public AccountTwoFaSettings deleteTwoFaAccountConfig(@RequestParam TwoFaProviderType providerType) throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
return twoFaConfigManager.deleteTwoFaAccountConfig(user.getTenantId(), user.getId(), providerType); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Get available 2FA providers (getAvailableTwoFaProviders)", notes = |
||||
|
"Get the list of provider types available for user to use (the ones configured by tenant or sysadmin).\n" + |
||||
|
"Example of response:\n" + |
||||
|
"```\n[\n \"TOTP\",\n \"EMAIL\",\n \"SMS\"\n]\n```" + |
||||
|
ControllerConstants.AVAILABLE_FOR_ANY_AUTHORIZED_USER |
||||
|
) |
||||
|
@GetMapping("/providers") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") |
||||
|
public List<TwoFaProviderType> getAvailableTwoFaProviders() throws ThingsboardException { |
||||
|
return twoFaConfigManager.getPlatformTwoFaSettings(getTenantId(), true) |
||||
|
.map(PlatformTwoFaSettings::getProviders).orElse(Collections.emptyList()).stream() |
||||
|
.map(TwoFaProviderConfig::getProviderType) |
||||
|
.collect(Collectors.toList()); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Get platform 2FA settings (getPlatformTwoFaSettings)", |
||||
|
notes = "Get platform settings for 2FA. The settings are described for savePlatformTwoFaSettings API method. " + |
||||
|
"If 2FA is not configured, then an empty response will be returned." + |
||||
|
ControllerConstants.SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) |
||||
|
@GetMapping("/settings") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')") |
||||
|
public PlatformTwoFaSettings getPlatformTwoFaSettings() throws ThingsboardException { |
||||
|
return twoFaConfigManager.getPlatformTwoFaSettings(getTenantId(), false).orElse(null); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Save platform 2FA settings (savePlatformTwoFaSettings)", |
||||
|
notes = "Save 2FA settings for platform. The settings have following properties:\n" + |
||||
|
"- `providers` - the list of 2FA providers' configs. Users will only be allowed to use 2FA providers from this list. \n\n" + |
||||
|
"- `minVerificationCodeSendPeriod` - minimal period in seconds to wait after verification code send request to send next request. \n" + |
||||
|
"- `verificationCodeCheckRateLimit` - rate limit configuration for verification code checking.\n" + |
||||
|
"The format is standard: 'amountOfRequests:periodInSeconds'. The value of '1:60' would limit verification " + |
||||
|
"code checking requests to one per minute.\n" + |
||||
|
"- `maxVerificationFailuresBeforeUserLockout` - maximum number of verification failures before a user gets disabled.\n" + |
||||
|
"- `totalAllowedTimeForVerification` - total amount of time in seconds allotted for verification. " + |
||||
|
"Basically, this property sets a lifetime for pre-verification token. If not set, default value of 30 minutes is used.\n" + NEW_LINE + |
||||
|
"TOTP 2FA provider config has following settings:\n" + |
||||
|
"- `issuerName` - issuer name that will be displayed in an authenticator app near a username. Must not be blank.\n\n" + |
||||
|
"For SMS 2FA provider:\n" + |
||||
|
"- `smsVerificationMessageTemplate` - verification message template. Available template variables " + |
||||
|
"are ${code} and ${userEmail}. It must not be blank and must contain verification code variable.\n" + |
||||
|
"- `verificationCodeLifetime` - verification code lifetime in seconds. Required to be positive.\n\n" + |
||||
|
"For EMAIL provider type:\n" + |
||||
|
"- `verificationCodeLifetime` - the same as for SMS." + NEW_LINE + |
||||
|
"Example of the settings:\n" + |
||||
|
"```\n{\n" + |
||||
|
" \"providers\": [\n" + |
||||
|
" {\n" + |
||||
|
" \"providerType\": \"TOTP\",\n" + |
||||
|
" \"issuerName\": \"TB\"\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"providerType\": \"EMAIL\",\n" + |
||||
|
" \"verificationCodeLifetime\": 60\n" + |
||||
|
" },\n" + |
||||
|
" {\n" + |
||||
|
" \"providerType\": \"SMS\",\n" + |
||||
|
" \"verificationCodeLifetime\": 60,\n" + |
||||
|
" \"smsVerificationMessageTemplate\": \"Here is your verification code: ${code}\"\n" + |
||||
|
" }\n" + |
||||
|
" ],\n" + |
||||
|
" \"minVerificationCodeSendPeriod\": 60,\n" + |
||||
|
" \"verificationCodeCheckRateLimit\": \"3:900\",\n" + |
||||
|
" \"maxVerificationFailuresBeforeUserLockout\": 10,\n" + |
||||
|
" \"totalAllowedTimeForVerification\": 600\n" + |
||||
|
"}\n```" + |
||||
|
ControllerConstants.SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) |
||||
|
@PostMapping("/settings") |
||||
|
@PreAuthorize("hasAnyAuthority('SYS_ADMIN')") |
||||
|
public PlatformTwoFaSettings savePlatformTwoFaSettings(@ApiParam(value = "Settings value", required = true) |
||||
|
@RequestBody PlatformTwoFaSettings twoFaSettings) throws ThingsboardException { |
||||
|
return twoFaConfigManager.savePlatformTwoFaSettings(getTenantId(), twoFaSettings); |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@Data |
||||
|
public static class TwoFaAccountConfigUpdateRequest { |
||||
|
private boolean useByDefault; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,152 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.controller; |
||||
|
|
||||
|
import io.swagger.annotations.ApiOperation; |
||||
|
import lombok.AllArgsConstructor; |
||||
|
import lombok.Builder; |
||||
|
import lombok.Data; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.springframework.security.access.prepost.PreAuthorize; |
||||
|
import org.springframework.web.bind.annotation.GetMapping; |
||||
|
import org.springframework.web.bind.annotation.PostMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestMapping; |
||||
|
import org.springframework.web.bind.annotation.RequestParam; |
||||
|
import org.springframework.web.bind.annotation.RestController; |
||||
|
import org.thingsboard.server.common.data.StringUtils; |
||||
|
import org.thingsboard.server.common.data.audit.ActionType; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.account.EmailTwoFaAccountConfig; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.account.SmsTwoFaAccountConfig; |
||||
|
import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; |
||||
|
import org.thingsboard.server.dao.user.UserService; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; |
||||
|
import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; |
||||
|
import org.thingsboard.server.service.security.auth.rest.RestAuthenticationDetails; |
||||
|
import org.thingsboard.server.service.security.model.JwtTokenPair; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; |
||||
|
import org.thingsboard.server.service.security.system.SystemSecurityService; |
||||
|
|
||||
|
import javax.servlet.http.HttpServletRequest; |
||||
|
import java.util.Collections; |
||||
|
import java.util.List; |
||||
|
import java.util.Optional; |
||||
|
import java.util.stream.Collectors; |
||||
|
|
||||
|
import static org.thingsboard.server.controller.ControllerConstants.NEW_LINE; |
||||
|
|
||||
|
@RestController |
||||
|
@RequestMapping("/api/auth/2fa") |
||||
|
@TbCoreComponent |
||||
|
@RequiredArgsConstructor |
||||
|
public class TwoFactorAuthController extends BaseController { |
||||
|
|
||||
|
private final TwoFactorAuthService twoFactorAuthService; |
||||
|
private final TwoFaConfigManager twoFaConfigManager; |
||||
|
private final JwtTokenFactory tokenFactory; |
||||
|
private final SystemSecurityService systemSecurityService; |
||||
|
private final UserService userService; |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Request 2FA verification code (requestTwoFaVerificationCode)", |
||||
|
notes = "Request 2FA verification code." + NEW_LINE + |
||||
|
"To make a request to this endpoint, you need an access token with the scope of PRE_VERIFICATION_TOKEN, " + |
||||
|
"which is issued on username/password auth if 2FA is enabled." + NEW_LINE + |
||||
|
"The API method is rate limited (using rate limit config from TwoFactorAuthSettings). " + |
||||
|
"Will return a Bad Request error if provider is not configured for usage, " + |
||||
|
"and Too Many Requests error if rate limits are exceeded.") |
||||
|
@PostMapping("/verification/send") |
||||
|
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
||||
|
public void requestTwoFaVerificationCode(@RequestParam TwoFaProviderType providerType) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
twoFactorAuthService.prepareVerificationCode(user, providerType, true); |
||||
|
} |
||||
|
|
||||
|
@ApiOperation(value = "Check 2FA verification code (checkTwoFaVerificationCode)", |
||||
|
notes = "Checks 2FA verification code, and if it is correct the method returns a regular access and refresh token pair." + NEW_LINE + |
||||
|
"The API method is rate limited (using rate limit config from TwoFactorAuthSettings), and also will block a user " + |
||||
|
"after X unsuccessful verification attempts if such behavior is configured (in TwoFactorAuthSettings)." + NEW_LINE + |
||||
|
"Will return a Bad Request error if provider is not configured for usage, " + |
||||
|
"and Too Many Requests error if rate limits are exceeded.") |
||||
|
@PostMapping("/verification/check") |
||||
|
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
||||
|
public JwtTokenPair checkTwoFaVerificationCode(@RequestParam TwoFaProviderType providerType, |
||||
|
@RequestParam String verificationCode, HttpServletRequest servletRequest) throws Exception { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
boolean verificationSuccess = twoFactorAuthService.checkVerificationCode(user, providerType, verificationCode, true); |
||||
|
if (verificationSuccess) { |
||||
|
systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(servletRequest), ActionType.LOGIN, null); |
||||
|
user = new SecurityUser(userService.findUserById(user.getTenantId(), user.getId()), true, user.getUserPrincipal()); |
||||
|
return tokenFactory.createTokenPair(user); |
||||
|
} else { |
||||
|
ThingsboardException error = new ThingsboardException("Verification code is incorrect", ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(servletRequest), ActionType.LOGIN, error); |
||||
|
throw error; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
@ApiOperation(value = "Get available 2FA providers (getAvailableTwoFaProviders)", notes = |
||||
|
"Get the list of 2FA provider infos available for user to use. Example:\n" + |
||||
|
"```\n[\n" + |
||||
|
" {\n \"type\": \"EMAIL\",\n \"default\": true,\n \"contact\": \"ab*****ko@gmail.com\"\n },\n" + |
||||
|
" {\n \"type\": \"TOTP\",\n \"default\": false,\n \"contact\": null\n },\n" + |
||||
|
" {\n \"type\": \"SMS\",\n \"default\": false,\n \"contact\": \"+38********12\"\n }\n" + |
||||
|
"]\n```") |
||||
|
@GetMapping("/providers") |
||||
|
@PreAuthorize("hasAuthority('PRE_VERIFICATION_TOKEN')") |
||||
|
public List<TwoFaProviderInfo> getAvailableTwoFaProviders() throws ThingsboardException { |
||||
|
SecurityUser user = getCurrentUser(); |
||||
|
Optional<PlatformTwoFaSettings> platformTwoFaSettings = twoFaConfigManager.getPlatformTwoFaSettings(user.getTenantId(), true); |
||||
|
return twoFaConfigManager.getAccountTwoFaSettings(user.getTenantId(), user.getId()) |
||||
|
.map(settings -> settings.getConfigs().values()).orElse(Collections.emptyList()) |
||||
|
.stream().map(config -> { |
||||
|
String contact = null; |
||||
|
switch (config.getProviderType()) { |
||||
|
case SMS: |
||||
|
String phoneNumber = ((SmsTwoFaAccountConfig) config).getPhoneNumber(); |
||||
|
contact = StringUtils.obfuscate(phoneNumber, 2, '*', phoneNumber.indexOf('+') + 1, phoneNumber.length()); |
||||
|
break; |
||||
|
case EMAIL: |
||||
|
String email = ((EmailTwoFaAccountConfig) config).getEmail(); |
||||
|
contact = StringUtils.obfuscate(email, 2, '*', 0, email.indexOf('@')); |
||||
|
break; |
||||
|
} |
||||
|
return TwoFaProviderInfo.builder() |
||||
|
.type(config.getProviderType()) |
||||
|
.isDefault(config.isUseByDefault()) |
||||
|
.contact(contact) |
||||
|
.minVerificationCodeSendPeriod(platformTwoFaSettings.get().getMinVerificationCodeSendPeriod()) |
||||
|
.build(); |
||||
|
}) |
||||
|
.collect(Collectors.toList()); |
||||
|
} |
||||
|
|
||||
|
@Data |
||||
|
@AllArgsConstructor |
||||
|
@Builder |
||||
|
public static class TwoFaProviderInfo { |
||||
|
private TwoFaProviderType type; |
||||
|
private boolean isDefault; |
||||
|
private String contact; |
||||
|
private Integer minVerificationCodeSendPeriod; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,76 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.apiusage; |
||||
|
|
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import org.apache.commons.lang3.StringUtils; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; |
||||
|
import org.thingsboard.server.common.msg.tools.TbRateLimits; |
||||
|
import org.thingsboard.server.dao.tenant.TbTenantProfileCache; |
||||
|
|
||||
|
import java.util.Map; |
||||
|
import java.util.concurrent.ConcurrentHashMap; |
||||
|
import java.util.function.Function; |
||||
|
|
||||
|
@Service |
||||
|
@RequiredArgsConstructor |
||||
|
public class DefaultRateLimitService implements RateLimitService { |
||||
|
|
||||
|
private final TbTenantProfileCache tenantProfileCache; |
||||
|
|
||||
|
private final Map<String, Map<TenantId, TbRateLimits>> rateLimits = new ConcurrentHashMap<>(); |
||||
|
|
||||
|
@Override |
||||
|
public boolean checkEntityExportLimit(TenantId tenantId) { |
||||
|
return checkLimit(tenantId, "entityExport", DefaultTenantProfileConfiguration::getTenantEntityExportRateLimit); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public boolean checkEntityImportLimit(TenantId tenantId) { |
||||
|
return checkLimit(tenantId, "entityImport", DefaultTenantProfileConfiguration::getTenantEntityImportRateLimit); |
||||
|
} |
||||
|
|
||||
|
private boolean checkLimit(TenantId tenantId, String rateLimitsKey, Function<DefaultTenantProfileConfiguration, String> rateLimitConfigExtractor) { |
||||
|
String rateLimitConfig = tenantProfileCache.get(tenantId).getProfileConfiguration() |
||||
|
.map(rateLimitConfigExtractor).orElse(null); |
||||
|
|
||||
|
Map<TenantId, TbRateLimits> rateLimits = this.rateLimits.get(rateLimitsKey); |
||||
|
if (StringUtils.isEmpty(rateLimitConfig)) { |
||||
|
if (rateLimits != null) { |
||||
|
rateLimits.remove(tenantId); |
||||
|
if (rateLimits.isEmpty()) { |
||||
|
this.rateLimits.remove(rateLimitsKey); |
||||
|
} |
||||
|
} |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
if (rateLimits == null) { |
||||
|
rateLimits = new ConcurrentHashMap<>(); |
||||
|
this.rateLimits.put(rateLimitsKey, rateLimits); |
||||
|
} |
||||
|
TbRateLimits rateLimit = rateLimits.get(tenantId); |
||||
|
if (rateLimit == null || !rateLimit.getConfiguration().equals(rateLimitConfig)) { |
||||
|
rateLimit = new TbRateLimits(rateLimitConfig); |
||||
|
rateLimits.put(tenantId, rateLimit); |
||||
|
} |
||||
|
|
||||
|
return rateLimit.tryConsume(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,26 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.apiusage; |
||||
|
|
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
|
||||
|
public interface RateLimitService { |
||||
|
|
||||
|
boolean checkEntityExportLimit(TenantId tenantId); |
||||
|
|
||||
|
boolean checkEntityImportLimit(TenantId tenantId); |
||||
|
|
||||
|
} |
||||
@ -1,48 +0,0 @@ |
|||||
/** |
|
||||
* Copyright © 2016-2022 The Thingsboard Authors |
|
||||
* |
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|
||||
* you may not use this file except in compliance with the License. |
|
||||
* You may obtain a copy of the License at |
|
||||
* |
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||
* |
|
||||
* Unless required by applicable law or agreed to in writing, software |
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|
||||
* See the License for the specific language governing permissions and |
|
||||
* limitations under the License. |
|
||||
*/ |
|
||||
package org.thingsboard.server.service.edge.rpc; |
|
||||
|
|
||||
import com.fasterxml.jackson.databind.JsonNode; |
|
||||
import org.thingsboard.server.common.data.edge.EdgeEvent; |
|
||||
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
|
||||
import org.thingsboard.server.common.data.edge.EdgeEventType; |
|
||||
import org.thingsboard.server.common.data.id.EdgeId; |
|
||||
import org.thingsboard.server.common.data.id.EntityId; |
|
||||
import org.thingsboard.server.common.data.id.TenantId; |
|
||||
|
|
||||
public final class EdgeEventUtils { |
|
||||
|
|
||||
private EdgeEventUtils() { |
|
||||
} |
|
||||
|
|
||||
public static EdgeEvent constructEdgeEvent(TenantId tenantId, |
|
||||
EdgeId edgeId, |
|
||||
EdgeEventType type, |
|
||||
EdgeEventActionType action, |
|
||||
EntityId entityId, |
|
||||
JsonNode body) { |
|
||||
EdgeEvent edgeEvent = new EdgeEvent(); |
|
||||
edgeEvent.setTenantId(tenantId); |
|
||||
edgeEvent.setEdgeId(edgeId); |
|
||||
edgeEvent.setType(type); |
|
||||
edgeEvent.setAction(action); |
|
||||
if (entityId != null) { |
|
||||
edgeEvent.setEntityId(entityId.getId()); |
|
||||
} |
|
||||
edgeEvent.setBody(body); |
|
||||
return edgeEvent; |
|
||||
} |
|
||||
} |
|
||||
@ -0,0 +1,77 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.edge.rpc.constructor; |
||||
|
|
||||
|
import com.google.protobuf.ByteString; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
import org.thingsboard.common.util.JacksonUtil; |
||||
|
import org.thingsboard.server.common.data.OtaPackage; |
||||
|
import org.thingsboard.server.common.data.id.OtaPackageId; |
||||
|
import org.thingsboard.server.gen.edge.v1.OtaPackageUpdateMsg; |
||||
|
import org.thingsboard.server.gen.edge.v1.UpdateMsgType; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
|
||||
|
@Component |
||||
|
@TbCoreComponent |
||||
|
public class OtaPackageMsgConstructor { |
||||
|
|
||||
|
public OtaPackageUpdateMsg constructOtaPackageUpdatedMsg(UpdateMsgType msgType, OtaPackage otaPackage) { |
||||
|
OtaPackageUpdateMsg.Builder builder = OtaPackageUpdateMsg.newBuilder() |
||||
|
.setMsgType(msgType) |
||||
|
.setIdMSB(otaPackage.getId().getId().getMostSignificantBits()) |
||||
|
.setIdLSB(otaPackage.getId().getId().getLeastSignificantBits()) |
||||
|
.setDeviceProfileIdMSB(otaPackage.getDeviceProfileId().getId().getMostSignificantBits()) |
||||
|
.setDeviceProfileIdLSB(otaPackage.getDeviceProfileId().getId().getLeastSignificantBits()) |
||||
|
.setType(otaPackage.getType().name()) |
||||
|
.setTitle(otaPackage.getTitle()) |
||||
|
.setVersion(otaPackage.getVersion()) |
||||
|
.setTag(otaPackage.getTag()); |
||||
|
|
||||
|
if (otaPackage.getUrl() != null) { |
||||
|
builder.setUrl(otaPackage.getUrl()); |
||||
|
} |
||||
|
if (otaPackage.getAdditionalInfo() != null) { |
||||
|
builder.setAdditionalInfo(JacksonUtil.toString(otaPackage.getAdditionalInfo())); |
||||
|
} |
||||
|
if (otaPackage.getFileName() != null) { |
||||
|
builder.setFileName(otaPackage.getFileName()); |
||||
|
} |
||||
|
if (otaPackage.getContentType() != null) { |
||||
|
builder.setContentType(otaPackage.getContentType()); |
||||
|
} |
||||
|
if (otaPackage.getChecksumAlgorithm() != null) { |
||||
|
builder.setChecksumAlgorithm(otaPackage.getChecksumAlgorithm().name()); |
||||
|
} |
||||
|
if (otaPackage.getChecksum() != null) { |
||||
|
builder.setChecksum(otaPackage.getChecksum()); |
||||
|
} |
||||
|
if (otaPackage.getDataSize() != null) { |
||||
|
builder.setDataSize(otaPackage.getDataSize()); |
||||
|
} |
||||
|
if (otaPackage.getData() != null) { |
||||
|
builder.setData(ByteString.copyFrom(otaPackage.getData().array())); |
||||
|
} |
||||
|
return builder.build(); |
||||
|
} |
||||
|
|
||||
|
public OtaPackageUpdateMsg constructOtaPackageDeleteMsg(OtaPackageId otaPackageId) { |
||||
|
return OtaPackageUpdateMsg.newBuilder() |
||||
|
.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE) |
||||
|
.setIdMSB(otaPackageId.getId().getMostSignificantBits()) |
||||
|
.setIdLSB(otaPackageId.getId().getLeastSignificantBits()).build(); |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,47 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.edge.rpc.fetch; |
||||
|
|
||||
|
import lombok.AllArgsConstructor; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.thingsboard.server.common.data.EdgeUtils; |
||||
|
import org.thingsboard.server.common.data.OtaPackageInfo; |
||||
|
import org.thingsboard.server.common.data.edge.Edge; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEvent; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventType; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.page.PageLink; |
||||
|
import org.thingsboard.server.dao.ota.OtaPackageService; |
||||
|
|
||||
|
@AllArgsConstructor |
||||
|
@Slf4j |
||||
|
public class OtaPackagesEdgeEventFetcher extends BasePageableEdgeEventFetcher<OtaPackageInfo> { |
||||
|
|
||||
|
private final OtaPackageService otaPackageService; |
||||
|
|
||||
|
@Override |
||||
|
PageData<OtaPackageInfo> fetchPageData(TenantId tenantId, Edge edge, PageLink pageLink) { |
||||
|
return otaPackageService.findTenantOtaPackagesByTenantId(tenantId, pageLink); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
EdgeEvent constructEdgeEvent(TenantId tenantId, Edge edge, OtaPackageInfo otaPackageInfo) { |
||||
|
return EdgeUtils.constructEdgeEvent(tenantId, edge.getId(), EdgeEventType.OTA_PACKAGE, |
||||
|
EdgeEventActionType.ADDED, otaPackageInfo.getId(), null); |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,63 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.edge.rpc.processor; |
||||
|
|
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.stereotype.Component; |
||||
|
import org.thingsboard.server.common.data.EdgeUtils; |
||||
|
import org.thingsboard.server.common.data.OtaPackage; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEvent; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
||||
|
import org.thingsboard.server.common.data.id.OtaPackageId; |
||||
|
import org.thingsboard.server.gen.edge.v1.DownlinkMsg; |
||||
|
import org.thingsboard.server.gen.edge.v1.OtaPackageUpdateMsg; |
||||
|
import org.thingsboard.server.gen.edge.v1.UpdateMsgType; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
|
||||
|
@Component |
||||
|
@Slf4j |
||||
|
@TbCoreComponent |
||||
|
public class OtaPackageEdgeProcessor extends BaseEdgeProcessor { |
||||
|
|
||||
|
public DownlinkMsg processOtaPackageToEdge(EdgeEvent edgeEvent, UpdateMsgType msgType, EdgeEventActionType action) { |
||||
|
OtaPackageId otaPackageId = new OtaPackageId(edgeEvent.getEntityId()); |
||||
|
DownlinkMsg downlinkMsg = null; |
||||
|
switch (action) { |
||||
|
case ADDED: |
||||
|
case UPDATED: |
||||
|
OtaPackage otaPackage = otaPackageService.findOtaPackageById(edgeEvent.getTenantId(), otaPackageId); |
||||
|
if (otaPackage != null) { |
||||
|
OtaPackageUpdateMsg otaPackageUpdateMsg = |
||||
|
otaPackageMsgConstructor.constructOtaPackageUpdatedMsg(msgType, otaPackage); |
||||
|
downlinkMsg = DownlinkMsg.newBuilder() |
||||
|
.setDownlinkMsgId(EdgeUtils.nextPositiveInt()) |
||||
|
.addOtaPackageUpdateMsg(otaPackageUpdateMsg) |
||||
|
.build(); |
||||
|
} |
||||
|
break; |
||||
|
case DELETED: |
||||
|
OtaPackageUpdateMsg otaPackageUpdateMsg = |
||||
|
otaPackageMsgConstructor.constructOtaPackageDeleteMsg(otaPackageId); |
||||
|
downlinkMsg = DownlinkMsg.newBuilder() |
||||
|
.setDownlinkMsgId(EdgeUtils.nextPositiveInt()) |
||||
|
.addOtaPackageUpdateMsg(otaPackageUpdateMsg) |
||||
|
.build(); |
||||
|
break; |
||||
|
} |
||||
|
return downlinkMsg; |
||||
|
} |
||||
|
|
||||
|
} |
||||
@ -0,0 +1,248 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.entitiy; |
||||
|
|
||||
|
import com.google.common.util.concurrent.Futures; |
||||
|
import com.google.common.util.concurrent.ListenableFuture; |
||||
|
import lombok.Getter; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.beans.factory.annotation.Autowired; |
||||
|
import org.springframework.beans.factory.annotation.Value; |
||||
|
import org.thingsboard.server.cluster.TbClusterService; |
||||
|
import org.thingsboard.server.common.data.EntityType; |
||||
|
import org.thingsboard.server.common.data.HasName; |
||||
|
import org.thingsboard.server.common.data.User; |
||||
|
import org.thingsboard.server.common.data.alarm.AlarmInfo; |
||||
|
import org.thingsboard.server.common.data.alarm.AlarmQuery; |
||||
|
import org.thingsboard.server.common.data.audit.ActionType; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.id.AlarmId; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.EdgeId; |
||||
|
import org.thingsboard.server.common.data.id.EntityId; |
||||
|
import org.thingsboard.server.common.data.id.EntityIdFactory; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.page.PageData; |
||||
|
import org.thingsboard.server.common.data.page.PageDataIterableByTenantIdEntityId; |
||||
|
import org.thingsboard.server.common.data.page.TimePageLink; |
||||
|
import org.thingsboard.server.dao.alarm.AlarmService; |
||||
|
import org.thingsboard.server.dao.asset.AssetService; |
||||
|
import org.thingsboard.server.dao.attributes.AttributesService; |
||||
|
import org.thingsboard.server.dao.customer.CustomerService; |
||||
|
import org.thingsboard.server.dao.dashboard.DashboardService; |
||||
|
import org.thingsboard.server.dao.device.ClaimDevicesService; |
||||
|
import org.thingsboard.server.dao.device.DeviceCredentialsService; |
||||
|
import org.thingsboard.server.dao.device.DeviceProfileService; |
||||
|
import org.thingsboard.server.dao.device.DeviceService; |
||||
|
import org.thingsboard.server.dao.edge.EdgeService; |
||||
|
import org.thingsboard.server.dao.entityview.EntityViewService; |
||||
|
import org.thingsboard.server.dao.exception.DataValidationException; |
||||
|
import org.thingsboard.server.dao.exception.IncorrectParameterException; |
||||
|
import org.thingsboard.server.dao.model.ModelConstants; |
||||
|
import org.thingsboard.server.dao.ota.OtaPackageService; |
||||
|
import org.thingsboard.server.dao.queue.QueueService; |
||||
|
import org.thingsboard.server.dao.relation.RelationService; |
||||
|
import org.thingsboard.server.dao.rule.RuleChainService; |
||||
|
import org.thingsboard.server.dao.tenant.TbTenantProfileCache; |
||||
|
import org.thingsboard.server.dao.tenant.TenantService; |
||||
|
import org.thingsboard.server.dao.user.UserService; |
||||
|
import org.thingsboard.server.dao.widget.WidgetsBundleService; |
||||
|
import org.thingsboard.server.service.action.EntityActionService; |
||||
|
import org.thingsboard.server.service.edge.EdgeNotificationService; |
||||
|
import org.thingsboard.server.service.executors.DbCallbackExecutorService; |
||||
|
import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService; |
||||
|
import org.thingsboard.server.service.install.InstallScripts; |
||||
|
import org.thingsboard.server.service.ota.OtaPackageStateService; |
||||
|
import org.thingsboard.server.service.resource.TbResourceService; |
||||
|
import org.thingsboard.server.service.rule.TbRuleChainService; |
||||
|
import org.thingsboard.server.service.security.permission.AccessControlService; |
||||
|
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
||||
|
|
||||
|
import javax.mail.MessagingException; |
||||
|
import java.util.ArrayList; |
||||
|
import java.util.Collections; |
||||
|
import java.util.List; |
||||
|
import java.util.Optional; |
||||
|
import java.util.stream.Collectors; |
||||
|
|
||||
|
@Slf4j |
||||
|
public abstract class AbstractTbEntityService { |
||||
|
|
||||
|
protected static final int DEFAULT_PAGE_SIZE = 1000; |
||||
|
|
||||
|
@Value("${server.log_controller_error_stack_trace}") |
||||
|
@Getter |
||||
|
private boolean logControllerErrorStackTrace; |
||||
|
@Value("${edges.enabled}") |
||||
|
@Getter |
||||
|
protected boolean edgesEnabled; |
||||
|
|
||||
|
@Autowired |
||||
|
protected DbCallbackExecutorService dbExecutor; |
||||
|
@Autowired |
||||
|
protected TbNotificationEntityService notificationEntityService; |
||||
|
@Autowired(required = false) |
||||
|
protected EdgeService edgeService; |
||||
|
@Autowired |
||||
|
protected AlarmService alarmService; |
||||
|
@Autowired |
||||
|
protected EntityActionService entityActionService; |
||||
|
@Autowired |
||||
|
protected DeviceService deviceService; |
||||
|
@Autowired |
||||
|
protected AssetService assetService; |
||||
|
@Autowired |
||||
|
protected DeviceCredentialsService deviceCredentialsService; |
||||
|
@Autowired |
||||
|
protected TenantService tenantService; |
||||
|
@Autowired |
||||
|
protected CustomerService customerService; |
||||
|
@Autowired |
||||
|
protected ClaimDevicesService claimDevicesService; |
||||
|
@Autowired |
||||
|
protected TbTenantProfileCache tenantProfileCache; |
||||
|
@Autowired |
||||
|
protected RuleChainService ruleChainService; |
||||
|
@Autowired |
||||
|
protected TbRuleChainService tbRuleChainService; |
||||
|
@Autowired |
||||
|
protected EdgeNotificationService edgeNotificationService; |
||||
|
@Autowired |
||||
|
protected QueueService queueService; |
||||
|
@Autowired |
||||
|
protected DashboardService dashboardService; |
||||
|
@Autowired |
||||
|
protected EntitiesVersionControlService vcService; |
||||
|
@Autowired |
||||
|
protected EntityViewService entityViewService; |
||||
|
@Autowired |
||||
|
protected TelemetrySubscriptionService tsSubService; |
||||
|
@Autowired |
||||
|
protected AttributesService attributesService; |
||||
|
@Autowired |
||||
|
protected AccessControlService accessControlService; |
||||
|
@Autowired |
||||
|
protected DeviceProfileService deviceProfileService; |
||||
|
@Autowired |
||||
|
protected TbClusterService tbClusterService; |
||||
|
@Autowired |
||||
|
protected OtaPackageStateService otaPackageStateService; |
||||
|
@Autowired |
||||
|
protected RelationService relationService; |
||||
|
@Autowired |
||||
|
protected OtaPackageService otaPackageService; |
||||
|
@Autowired |
||||
|
protected InstallScripts installScripts; |
||||
|
@Autowired |
||||
|
protected UserService userService; |
||||
|
@Autowired |
||||
|
protected TbResourceService resourceService; |
||||
|
@Autowired |
||||
|
protected WidgetsBundleService widgetsBundleService; |
||||
|
|
||||
|
protected ListenableFuture<Void> removeAlarmsByEntityId(TenantId tenantId, EntityId entityId) { |
||||
|
ListenableFuture<PageData<AlarmInfo>> alarmsFuture = |
||||
|
alarmService.findAlarms(tenantId, new AlarmQuery(entityId, new TimePageLink(Integer.MAX_VALUE), null, null, false)); |
||||
|
|
||||
|
ListenableFuture<List<AlarmId>> alarmIdsFuture = Futures.transform(alarmsFuture, page -> |
||||
|
page.getData().stream().map(AlarmInfo::getId).collect(Collectors.toList()), dbExecutor); |
||||
|
|
||||
|
return Futures.transform(alarmIdsFuture, ids -> { |
||||
|
ids.stream().map(alarmId -> alarmService.deleteAlarm(tenantId, alarmId)).collect(Collectors.toList()); |
||||
|
return null; |
||||
|
}, dbExecutor); |
||||
|
} |
||||
|
|
||||
|
protected <E extends HasName, I extends EntityId> void logEntityAction(User user, TenantId tenantId, I entityId, E entity, CustomerId customerId, |
||||
|
ActionType actionType, Exception e, Object... additionalInfo) throws ThingsboardException { |
||||
|
if (user != null) { |
||||
|
entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); |
||||
|
} else if (e == null) { |
||||
|
entityActionService.pushEntityActionToRuleEngine(entityId, entity, tenantId, customerId, actionType, null, additionalInfo); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected <T> T checkNotNull(T reference) throws ThingsboardException { |
||||
|
return checkNotNull(reference, "Requested item wasn't found!"); |
||||
|
} |
||||
|
|
||||
|
protected <T> T checkNotNull(T reference, String notFoundMessage) throws ThingsboardException { |
||||
|
if (reference == null) { |
||||
|
throw new ThingsboardException(notFoundMessage, ThingsboardErrorCode.ITEM_NOT_FOUND); |
||||
|
} |
||||
|
return reference; |
||||
|
} |
||||
|
|
||||
|
protected <T> T checkNotNull(Optional<T> reference) throws ThingsboardException { |
||||
|
return checkNotNull(reference, "Requested item wasn't found!"); |
||||
|
} |
||||
|
|
||||
|
protected <T> T checkNotNull(Optional<T> reference, String notFoundMessage) throws ThingsboardException { |
||||
|
if (reference.isPresent()) { |
||||
|
return reference.get(); |
||||
|
} else { |
||||
|
throw new ThingsboardException(notFoundMessage, ThingsboardErrorCode.ITEM_NOT_FOUND); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
protected ThingsboardException handleException(Exception exception) { |
||||
|
return handleException(exception, true); |
||||
|
} |
||||
|
|
||||
|
protected ThingsboardException handleException(Exception exception, boolean logException) { |
||||
|
if (logException && logControllerErrorStackTrace) { |
||||
|
log.error("Error [{}]", exception.getMessage(), exception); |
||||
|
} |
||||
|
|
||||
|
String cause = ""; |
||||
|
if (exception.getCause() != null) { |
||||
|
cause = exception.getCause().getClass().getCanonicalName(); |
||||
|
} |
||||
|
|
||||
|
if (exception instanceof ThingsboardException) { |
||||
|
return (ThingsboardException) exception; |
||||
|
} else if (exception instanceof IllegalArgumentException || exception instanceof IncorrectParameterException |
||||
|
|| exception instanceof DataValidationException || cause.contains("IncorrectParameterException")) { |
||||
|
return new ThingsboardException(exception.getMessage(), ThingsboardErrorCode.BAD_REQUEST_PARAMS); |
||||
|
} else if (exception instanceof MessagingException) { |
||||
|
return new ThingsboardException("Unable to send mail: " + exception.getMessage(), ThingsboardErrorCode.GENERAL); |
||||
|
} else { |
||||
|
return new ThingsboardException(exception.getMessage(), exception, ThingsboardErrorCode.GENERAL); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@SuppressWarnings("unchecked") |
||||
|
protected <I extends EntityId> I emptyId(EntityType entityType) { |
||||
|
return (I) EntityIdFactory.getByTypeAndUuid(entityType, ModelConstants.NULL_UUID); |
||||
|
} |
||||
|
|
||||
|
protected List<EdgeId> findRelatedEdgeIds(TenantId tenantId, EntityId entityId) { |
||||
|
if (!edgesEnabled) { |
||||
|
return null; |
||||
|
} |
||||
|
if (EntityType.EDGE.equals(entityId.getEntityType())) { |
||||
|
return Collections.singletonList(new EdgeId(entityId.getId())); |
||||
|
} |
||||
|
PageDataIterableByTenantIdEntityId<EdgeId> relatedEdgeIdsIterator = |
||||
|
new PageDataIterableByTenantIdEntityId<>(edgeService::findRelatedEdgeIdsByEntityId, tenantId, entityId, DEFAULT_PAGE_SIZE); |
||||
|
List<EdgeId> result = new ArrayList<>(); |
||||
|
for (EdgeId edgeId : relatedEdgeIdsIterator) { |
||||
|
result.add(edgeId); |
||||
|
} |
||||
|
return result; |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,365 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.entitiy; |
||||
|
|
||||
|
import com.fasterxml.jackson.core.JsonProcessingException; |
||||
|
import com.fasterxml.jackson.databind.ObjectMapper; |
||||
|
import lombok.RequiredArgsConstructor; |
||||
|
import lombok.extern.slf4j.Slf4j; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.thingsboard.rule.engine.api.msg.DeviceCredentialsUpdateNotificationMsg; |
||||
|
import org.thingsboard.server.cluster.TbClusterService; |
||||
|
import org.thingsboard.server.common.data.DataConstants; |
||||
|
import org.thingsboard.server.common.data.Device; |
||||
|
import org.thingsboard.server.common.data.EntityType; |
||||
|
import org.thingsboard.server.common.data.HasName; |
||||
|
import org.thingsboard.server.common.data.Tenant; |
||||
|
import org.thingsboard.server.common.data.alarm.Alarm; |
||||
|
import org.thingsboard.server.common.data.audit.ActionType; |
||||
|
import org.thingsboard.server.common.data.edge.Edge; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventType; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.DeviceId; |
||||
|
import org.thingsboard.server.common.data.id.EdgeId; |
||||
|
import org.thingsboard.server.common.data.id.EntityId; |
||||
|
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.data.relation.EntityRelation; |
||||
|
import org.thingsboard.server.common.data.rule.RuleChain; |
||||
|
import org.thingsboard.server.common.data.rule.RuleChainType; |
||||
|
import org.thingsboard.server.common.data.security.DeviceCredentials; |
||||
|
import org.thingsboard.server.common.msg.TbMsg; |
||||
|
import org.thingsboard.server.common.msg.TbMsgDataType; |
||||
|
import org.thingsboard.server.common.msg.TbMsgMetaData; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.action.EntityActionService; |
||||
|
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
@Slf4j |
||||
|
@Service |
||||
|
@TbCoreComponent |
||||
|
@RequiredArgsConstructor |
||||
|
public class DefaultTbNotificationEntityService implements TbNotificationEntityService { |
||||
|
private static final ObjectMapper json = new ObjectMapper(); |
||||
|
|
||||
|
private final EntityActionService entityActionService; |
||||
|
private final TbClusterService tbClusterService; |
||||
|
private final GatewayNotificationsService gatewayNotificationsService; |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, |
||||
|
ActionType actionType, SecurityUser user, Exception e, |
||||
|
Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, e, additionalInfo); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyDeleteEntity(TenantId tenantId, I entityId, E entity, |
||||
|
CustomerId customerId, ActionType actionType, |
||||
|
List<EdgeId> relatedEdgeIds, |
||||
|
SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); |
||||
|
sendDeleteNotificationMsg(tenantId, entityId, entity, relatedEdgeIds); |
||||
|
} |
||||
|
|
||||
|
public void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, |
||||
|
CustomerId customerId, |
||||
|
List<EdgeId> relatedEdgeIds, |
||||
|
SecurityUser user, |
||||
|
String body, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, originatorId, alarm, customerId, ActionType.DELETED, user, additionalInfo); |
||||
|
sendAlarmDeleteNotificationMsg(tenantId, alarm, relatedEdgeIds, body); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyDeleteRuleChain(TenantId tenantId, RuleChain ruleChain, |
||||
|
List<EdgeId> relatedEdgeIds, SecurityUser user) { |
||||
|
RuleChainId ruleChainId = ruleChain.getId(); |
||||
|
logEntityAction(tenantId, ruleChainId, ruleChain, null, ActionType.DELETED, user, null, ruleChainId.toString()); |
||||
|
if (RuleChainType.EDGE.equals(ruleChain.getType())) { |
||||
|
sendDeleteNotificationMsg(tenantId, ruleChainId, relatedEdgeIds, null); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <I extends EntityId> void notifySendMsgToEdgeService(TenantId tenantId, I entityId, EdgeEventActionType edgeEventActionType) { |
||||
|
sendEntityNotificationMsg(tenantId, entityId, edgeEventActionType); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyAssignOrUnassignEntityToCustomer(TenantId tenantId, I entityId, |
||||
|
CustomerId customerId, E entity, |
||||
|
ActionType actionType, |
||||
|
EdgeEventActionType edgeActionType, |
||||
|
SecurityUser user, boolean sendToEdge, |
||||
|
Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); |
||||
|
|
||||
|
if (sendToEdge) { |
||||
|
sendEntityAssignToCustomerNotificationMsg(tenantId, entityId, customerId, edgeActionType); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyAssignOrUnassignEntityToEdge(TenantId tenantId, I entityId, |
||||
|
CustomerId customerId, EdgeId edgeId, |
||||
|
E entity, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); |
||||
|
sendEntityAssignToEdgeNotificationMsg(tenantId, edgeId, entityId, edgeTypeByActionType(actionType)); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyCreateOruUpdateTenant(Tenant tenant, ComponentLifecycleEvent event) { |
||||
|
tbClusterService.onTenantChange(tenant, null); |
||||
|
tbClusterService.broadcastEntityStateChangeEvent(tenant.getId(), tenant.getId(), event); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyDeleteTenant(Tenant tenant) { |
||||
|
tbClusterService.onTenantDelete(tenant, null); |
||||
|
tbClusterService.broadcastEntityStateChangeEvent(tenant.getId(), tenant.getId(), ComponentLifecycleEvent.DELETED); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyCreateOrUpdateDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, |
||||
|
Device device, Device oldDevice, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo) { |
||||
|
tbClusterService.onDeviceUpdated(device, oldDevice); |
||||
|
logEntityAction(tenantId, deviceId, device, customerId, actionType, user, additionalInfo); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyDeleteDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, |
||||
|
List<EdgeId> relatedEdgeIds, SecurityUser user, Object... additionalInfo) { |
||||
|
gatewayNotificationsService.onDeviceDeleted(device); |
||||
|
tbClusterService.onDeviceDeleted(device, null); |
||||
|
|
||||
|
notifyDeleteEntity(tenantId, deviceId, device, customerId, ActionType.DELETED, relatedEdgeIds, user, additionalInfo); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyUpdateDeviceCredentials(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, |
||||
|
DeviceCredentials deviceCredentials, SecurityUser user) { |
||||
|
tbClusterService.pushMsgToCore(new DeviceCredentialsUpdateNotificationMsg(tenantId, deviceCredentials.getDeviceId(), deviceCredentials), null); |
||||
|
sendEntityNotificationMsg(tenantId, deviceId, EdgeEventActionType.CREDENTIALS_UPDATED); |
||||
|
logEntityAction(tenantId, deviceId, device, customerId, ActionType.CREDENTIALS_UPDATED, user, deviceCredentials); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyAssignDeviceToTenant(TenantId tenantId, TenantId newTenantId, DeviceId deviceId, CustomerId customerId, |
||||
|
Device device, Tenant tenant, SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, deviceId, device, customerId, ActionType.ASSIGNED_TO_TENANT, user, additionalInfo); |
||||
|
pushAssignedFromNotification(tenant, newTenantId, device); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyCreateOrUpdateEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, ActionType actionType, SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, additionalInfo); |
||||
|
if (actionType == ActionType.UPDATED) { |
||||
|
sendEntityNotificationMsg(tenantId, entityId, EdgeEventActionType.UPDATED); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyEdge(TenantId tenantId, EdgeId edgeId, CustomerId customerId, Edge edge, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo) { |
||||
|
ComponentLifecycleEvent lifecycleEvent; |
||||
|
EdgeEventActionType edgeEventActionType = null; |
||||
|
switch (actionType) { |
||||
|
case ADDED: |
||||
|
lifecycleEvent = ComponentLifecycleEvent.CREATED; |
||||
|
break; |
||||
|
case UPDATED: |
||||
|
lifecycleEvent = ComponentLifecycleEvent.UPDATED; |
||||
|
break; |
||||
|
case ASSIGNED_TO_CUSTOMER: |
||||
|
lifecycleEvent = ComponentLifecycleEvent.UPDATED; |
||||
|
edgeEventActionType = EdgeEventActionType.ASSIGNED_TO_CUSTOMER; |
||||
|
break; |
||||
|
case UNASSIGNED_FROM_CUSTOMER: |
||||
|
lifecycleEvent = ComponentLifecycleEvent.UPDATED; |
||||
|
edgeEventActionType = EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER; |
||||
|
break; |
||||
|
case DELETED: |
||||
|
lifecycleEvent = ComponentLifecycleEvent.DELETED; |
||||
|
break; |
||||
|
default: |
||||
|
throw new IllegalArgumentException("Unknown actionType: " + actionType); |
||||
|
} |
||||
|
|
||||
|
tbClusterService.broadcastEntityStateChangeEvent(tenantId, edgeId, lifecycleEvent); |
||||
|
logEntityAction(tenantId, edgeId, edge, customerId, actionType, user, additionalInfo); |
||||
|
|
||||
|
//Send notification to edge
|
||||
|
if (edgeEventActionType != null) { |
||||
|
sendEntityAssignToCustomerNotificationMsg(tenantId, edgeId, customerId, edgeEventActionType); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(alarm.getTenantId(), alarm.getOriginator(), alarm, alarm.getCustomerId(), actionType, user, additionalInfo); |
||||
|
sendEntityNotificationMsg(alarm.getTenantId(), alarm.getId(), edgeTypeByActionType(actionType)); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public <E extends HasName, I extends EntityId> void notifyCreateOrUpdateOrDelete(TenantId tenantId, CustomerId customerId, |
||||
|
I entityId, E entity, SecurityUser user, |
||||
|
ActionType actionType, boolean sendNotifyMsgToEdge, Exception e, |
||||
|
Object... additionalInfo) { |
||||
|
notifyEntity(tenantId, entityId, entity, customerId, actionType, user, e, additionalInfo); |
||||
|
if (sendNotifyMsgToEdge) { |
||||
|
sendEntityNotificationMsg(tenantId, entityId, edgeTypeByActionType(actionType)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void notifyCreateOrUpdateOrDeleteRelation(TenantId tenantId, CustomerId customerId, |
||||
|
EntityRelation relation, SecurityUser user, |
||||
|
ActionType actionType, Exception e, |
||||
|
Object... additionalInfo) { |
||||
|
notifyEntity(tenantId, relation.getFrom(), null, customerId, actionType, user, e, additionalInfo); |
||||
|
notifyEntity(tenantId, relation.getTo(), null, customerId, actionType, user, e, additionalInfo); |
||||
|
if (e == null) { |
||||
|
try { |
||||
|
if (!relation.getFrom().getEntityType().equals(EntityType.EDGE) && |
||||
|
!relation.getTo().getEntityType().equals(EntityType.EDGE)) { |
||||
|
sendNotificationMsgToEdge(tenantId, null, null, json.writeValueAsString(relation), |
||||
|
EdgeEventType.RELATION, edgeTypeByActionType(actionType)); |
||||
|
} |
||||
|
} catch (Exception e1) { |
||||
|
log.warn("Failed to push relation to core: {}", relation, e1); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private <E extends HasName, I extends EntityId> void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, |
||||
|
ActionType actionType, SecurityUser user, Object... additionalInfo) { |
||||
|
logEntityAction(tenantId, entityId, entity, customerId, actionType, user, null, additionalInfo); |
||||
|
} |
||||
|
|
||||
|
private <E extends HasName, I extends EntityId> void logEntityAction(TenantId tenantId, I entityId, E entity, CustomerId customerId, |
||||
|
ActionType actionType, SecurityUser user, Exception e, Object... additionalInfo) { |
||||
|
if (user != null) { |
||||
|
entityActionService.logEntityAction(user, entityId, entity, customerId, actionType, e, additionalInfo); |
||||
|
} else if (e == null) { |
||||
|
entityActionService.pushEntityActionToRuleEngine(entityId, entity, tenantId, customerId, actionType, null, additionalInfo); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void sendEntityNotificationMsg(TenantId tenantId, EntityId entityId, EdgeEventActionType action) { |
||||
|
sendNotificationMsgToEdge(tenantId, null, entityId, null, null, action); |
||||
|
} |
||||
|
|
||||
|
private void sendEntityAssignToCustomerNotificationMsg(TenantId tenantId, EntityId entityId, CustomerId customerId, EdgeEventActionType action) { |
||||
|
try { |
||||
|
sendNotificationMsgToEdge(tenantId, null, entityId, json.writeValueAsString(customerId), null, action); |
||||
|
} catch (Exception e) { |
||||
|
log.warn("Failed to push assign/unassign to/from customer to core: {}", customerId, e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void sendAlarmDeleteNotificationMsg(TenantId tenantId, Alarm alarm, List<EdgeId> edgeIds, String body) { |
||||
|
try { |
||||
|
sendDeleteNotificationMsg(tenantId, alarm.getId(), edgeIds, body); |
||||
|
} catch (Exception e) { |
||||
|
log.warn("Failed to push delete msg to core: {}", alarm, e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private <E extends HasName, I extends EntityId> void sendDeleteNotificationMsg(TenantId tenantId, I entityId, E entity, List<EdgeId> edgeIds) { |
||||
|
try { |
||||
|
sendDeleteNotificationMsg(tenantId, entityId, edgeIds, null); |
||||
|
} catch (Exception e) { |
||||
|
log.warn("Failed to push delete msg to core: {}", entity, e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void sendDeleteNotificationMsg(TenantId tenantId, EntityId entityId, List<EdgeId> edgeIds, String body) { |
||||
|
if (edgeIds != null && !edgeIds.isEmpty()) { |
||||
|
for (EdgeId edgeId : edgeIds) { |
||||
|
sendNotificationMsgToEdge(tenantId, edgeId, entityId, body, null, EdgeEventActionType.DELETED); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private void sendEntityAssignToEdgeNotificationMsg(TenantId tenantId, EdgeId edgeId, EntityId entityId, EdgeEventActionType action) { |
||||
|
sendNotificationMsgToEdge(tenantId, edgeId, entityId, null, null, action); |
||||
|
} |
||||
|
|
||||
|
private void sendNotificationMsgToEdge(TenantId tenantId, EdgeId edgeId, EntityId entityId, String body, EdgeEventType type, EdgeEventActionType action) { |
||||
|
tbClusterService.sendNotificationMsgToEdge(tenantId, edgeId, entityId, body, type, action); |
||||
|
} |
||||
|
|
||||
|
private void pushAssignedFromNotification(Tenant currentTenant, TenantId newTenantId, Device assignedDevice) { |
||||
|
String data = entityToStr(assignedDevice); |
||||
|
if (data != null) { |
||||
|
TbMsg tbMsg = TbMsg.newMsg(DataConstants.ENTITY_ASSIGNED_FROM_TENANT, assignedDevice.getId(), assignedDevice.getCustomerId(), getMetaDataForAssignedFrom(currentTenant), TbMsgDataType.JSON, data); |
||||
|
tbClusterService.pushMsgToRuleEngine(newTenantId, assignedDevice.getId(), tbMsg, null); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
private TbMsgMetaData getMetaDataForAssignedFrom(Tenant tenant) { |
||||
|
TbMsgMetaData metaData = new TbMsgMetaData(); |
||||
|
metaData.putValue("assignedFromTenantId", tenant.getId().getId().toString()); |
||||
|
metaData.putValue("assignedFromTenantName", tenant.getName()); |
||||
|
return metaData; |
||||
|
} |
||||
|
|
||||
|
private <E extends HasName> String entityToStr(E entity) { |
||||
|
try { |
||||
|
return json.writeValueAsString(json.valueToTree(entity)); |
||||
|
} catch (JsonProcessingException e) { |
||||
|
log.warn("[{}] Failed to convert entity to string!", entity, e); |
||||
|
} |
||||
|
return null; |
||||
|
} |
||||
|
|
||||
|
public static EdgeEventActionType edgeTypeByActionType(ActionType actionType) { |
||||
|
switch (actionType) { |
||||
|
case ADDED: |
||||
|
return EdgeEventActionType.ADDED; |
||||
|
case UPDATED: |
||||
|
return EdgeEventActionType.UPDATED; |
||||
|
case ALARM_ACK: |
||||
|
return EdgeEventActionType.ALARM_ACK; |
||||
|
case ALARM_CLEAR: |
||||
|
return EdgeEventActionType.ALARM_CLEAR; |
||||
|
case DELETED: |
||||
|
return EdgeEventActionType.DELETED; |
||||
|
case RELATION_ADD_OR_UPDATE: |
||||
|
return EdgeEventActionType.RELATION_ADD_OR_UPDATE; |
||||
|
case RELATION_DELETED: |
||||
|
return EdgeEventActionType.RELATION_DELETED; |
||||
|
case ASSIGNED_TO_CUSTOMER: |
||||
|
return EdgeEventActionType.ASSIGNED_TO_CUSTOMER; |
||||
|
case UNASSIGNED_FROM_CUSTOMER: |
||||
|
return EdgeEventActionType.UNASSIGNED_FROM_CUSTOMER; |
||||
|
case ASSIGNED_TO_EDGE: |
||||
|
return EdgeEventActionType.ASSIGNED_TO_EDGE; |
||||
|
case UNASSIGNED_FROM_EDGE: |
||||
|
return EdgeEventActionType.UNASSIGNED_FROM_EDGE; |
||||
|
default: |
||||
|
return null; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
@ -0,0 +1,105 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.entitiy; |
||||
|
|
||||
|
import org.thingsboard.server.common.data.Device; |
||||
|
import org.thingsboard.server.common.data.HasName; |
||||
|
import org.thingsboard.server.common.data.Tenant; |
||||
|
import org.thingsboard.server.common.data.alarm.Alarm; |
||||
|
import org.thingsboard.server.common.data.audit.ActionType; |
||||
|
import org.thingsboard.server.common.data.edge.Edge; |
||||
|
import org.thingsboard.server.common.data.edge.EdgeEventActionType; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.DeviceId; |
||||
|
import org.thingsboard.server.common.data.id.EdgeId; |
||||
|
import org.thingsboard.server.common.data.id.EntityId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; |
||||
|
import org.thingsboard.server.common.data.relation.EntityRelation; |
||||
|
import org.thingsboard.server.common.data.rule.RuleChain; |
||||
|
import org.thingsboard.server.common.data.security.DeviceCredentials; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
public interface TbNotificationEntityService { |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyEntity(TenantId tenantId, I entityId, E entity, CustomerId customerId, |
||||
|
ActionType actionType, SecurityUser user, Exception e, |
||||
|
Object... additionalInfo); |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyCreateOrUpdateEntity(TenantId tenantId, I entityId, E entity, |
||||
|
CustomerId customerId, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyDeleteEntity(TenantId tenantId, I entityId, E entity, |
||||
|
CustomerId customerId, ActionType actionType, |
||||
|
List<EdgeId> relatedEdgeIds, |
||||
|
SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyDeleteAlarm(TenantId tenantId, Alarm alarm, EntityId originatorId, |
||||
|
CustomerId customerId, List<EdgeId> relatedEdgeIds, |
||||
|
SecurityUser user, String body, Object... additionalInfo); |
||||
|
|
||||
|
void notifyDeleteRuleChain(TenantId tenantId, RuleChain ruleChain, |
||||
|
List<EdgeId> relatedEdgeIds, SecurityUser user); |
||||
|
|
||||
|
<I extends EntityId> void notifySendMsgToEdgeService(TenantId tenantId, I entityId, EdgeEventActionType edgeEventActionType); |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyAssignOrUnassignEntityToCustomer(TenantId tenantId, I entityId, |
||||
|
CustomerId customerId, E entity, |
||||
|
ActionType actionType, |
||||
|
EdgeEventActionType edgeActionType, |
||||
|
SecurityUser user, boolean sendToEdge, |
||||
|
Object... additionalInfo); |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyAssignOrUnassignEntityToEdge(TenantId tenantId, I entityId, |
||||
|
CustomerId customerId, EdgeId edgeId, |
||||
|
E entity, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyCreateOruUpdateTenant(Tenant tenant, ComponentLifecycleEvent event); |
||||
|
|
||||
|
|
||||
|
void notifyDeleteTenant(Tenant tenant); |
||||
|
|
||||
|
void notifyCreateOrUpdateDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, |
||||
|
Device oldDevice, ActionType actionType, SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyDeleteDevice(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, |
||||
|
List<EdgeId> relatedEdgeIds, SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyUpdateDeviceCredentials(TenantId tenantId, DeviceId deviceId, CustomerId customerId, Device device, |
||||
|
DeviceCredentials deviceCredentials, SecurityUser user); |
||||
|
|
||||
|
void notifyAssignDeviceToTenant(TenantId tenantId, TenantId newTenantId, DeviceId deviceId, CustomerId customerId, |
||||
|
Device device, Tenant tenant, SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyEdge(TenantId tenantId, EdgeId edgeId, CustomerId customerId, Edge edge, ActionType actionType, |
||||
|
SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
void notifyCreateOrUpdateAlarm(Alarm alarm, ActionType actionType, SecurityUser user, Object... additionalInfo); |
||||
|
|
||||
|
<E extends HasName, I extends EntityId> void notifyCreateOrUpdateOrDelete(TenantId tenantId, CustomerId customerId, |
||||
|
I entityId, E entity, SecurityUser user, |
||||
|
ActionType actionType, boolean sendNotifyMsgToEdge, Exception e, |
||||
|
Object... additionalInfo); |
||||
|
|
||||
|
void notifyCreateOrUpdateOrDeleteRelation(TenantId tenantId, CustomerId customerId, |
||||
|
EntityRelation relation, SecurityUser user, |
||||
|
ActionType actionType, Exception e, |
||||
|
Object... additionalInfo); |
||||
|
} |
||||
@ -0,0 +1,100 @@ |
|||||
|
/** |
||||
|
* Copyright © 2016-2022 The Thingsboard Authors |
||||
|
* |
||||
|
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
* you may not use this file except in compliance with the License. |
||||
|
* You may obtain a copy of the License at |
||||
|
* |
||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
* |
||||
|
* Unless required by applicable law or agreed to in writing, software |
||||
|
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
|
* See the License for the specific language governing permissions and |
||||
|
* limitations under the License. |
||||
|
*/ |
||||
|
package org.thingsboard.server.service.entitiy.alarm; |
||||
|
|
||||
|
import lombok.AllArgsConstructor; |
||||
|
import org.springframework.stereotype.Service; |
||||
|
import org.thingsboard.common.util.JacksonUtil; |
||||
|
import org.thingsboard.server.common.data.EntityType; |
||||
|
import org.thingsboard.server.common.data.alarm.Alarm; |
||||
|
import org.thingsboard.server.common.data.alarm.AlarmStatus; |
||||
|
import org.thingsboard.server.common.data.audit.ActionType; |
||||
|
import org.thingsboard.server.common.data.exception.ThingsboardException; |
||||
|
import org.thingsboard.server.common.data.id.CustomerId; |
||||
|
import org.thingsboard.server.common.data.id.EdgeId; |
||||
|
import org.thingsboard.server.common.data.id.TenantId; |
||||
|
import org.thingsboard.server.queue.util.TbCoreComponent; |
||||
|
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
||||
|
import org.thingsboard.server.service.security.model.SecurityUser; |
||||
|
|
||||
|
import java.util.List; |
||||
|
|
||||
|
@Service |
||||
|
@TbCoreComponent |
||||
|
@AllArgsConstructor |
||||
|
public class DefaultTbAlarmService extends AbstractTbEntityService implements TbAlarmService { |
||||
|
|
||||
|
@Override |
||||
|
public Alarm save(Alarm alarm, SecurityUser user) throws ThingsboardException { |
||||
|
ActionType actionType = alarm.getId() == null ? ActionType.ADDED : ActionType.UPDATED; |
||||
|
TenantId tenantId = alarm.getTenantId(); |
||||
|
try { |
||||
|
Alarm savedAlarm = checkNotNull(alarmService.createOrUpdateAlarm(alarm).getAlarm()); |
||||
|
notificationEntityService.notifyCreateOrUpdateAlarm(savedAlarm, actionType, user); |
||||
|
return savedAlarm; |
||||
|
} catch (Exception e) { |
||||
|
notificationEntityService.notifyEntity(tenantId, emptyId(EntityType.ALARM), alarm, null, actionType, user, e); |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void ack(Alarm alarm, SecurityUser user) throws ThingsboardException { |
||||
|
try { |
||||
|
long ackTs = System.currentTimeMillis(); |
||||
|
alarmService.ackAlarm(alarm.getTenantId(), alarm.getId(), ackTs).get(); |
||||
|
alarm.setAckTs(ackTs); |
||||
|
alarm.setStatus(alarm.getStatus().isCleared() ? AlarmStatus.CLEARED_ACK : AlarmStatus.ACTIVE_ACK); |
||||
|
notificationEntityService.notifyCreateOrUpdateAlarm(alarm, ActionType.ALARM_ACK, user); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public void clear(Alarm alarm, SecurityUser user) throws ThingsboardException { |
||||
|
try { |
||||
|
long clearTs = System.currentTimeMillis(); |
||||
|
alarmService.clearAlarm(alarm.getTenantId(), alarm.getId(), null, clearTs).get(); |
||||
|
alarm.setClearTs(clearTs); |
||||
|
alarm.setStatus(alarm.getStatus().isAck() ? AlarmStatus.CLEARED_ACK : AlarmStatus.CLEARED_UNACK); |
||||
|
notificationEntityService.notifyCreateOrUpdateAlarm(alarm, ActionType.ALARM_CLEAR, user); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Boolean delete(Alarm alarm, SecurityUser user) throws ThingsboardException { |
||||
|
return delete(alarm, user.getCustomerId(), user); |
||||
|
} |
||||
|
|
||||
|
@Override |
||||
|
public Boolean delete(Alarm alarm, CustomerId customerId) throws ThingsboardException { |
||||
|
return delete(alarm, customerId, null); |
||||
|
} |
||||
|
|
||||
|
private Boolean delete(Alarm alarm, CustomerId customerId, SecurityUser user) throws ThingsboardException { |
||||
|
try { |
||||
|
List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(alarm.getTenantId(), alarm.getOriginator()); |
||||
|
notificationEntityService.notifyDeleteAlarm(alarm.getTenantId(), alarm, alarm.getOriginator(), customerId, |
||||
|
relatedEdgeIds, user, JacksonUtil.OBJECT_MAPPER.writeValueAsString(alarm)); |
||||
|
return alarmService.deleteAlarm(alarm.getTenantId(), alarm.getId()).isSuccessful(); |
||||
|
} catch (Exception e) { |
||||
|
throw handleException(e); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue