diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 2568911c90..92e1a6f2de 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -29,6 +29,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import jakarta.servlet.http.HttpServletRequest; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.page.PageData; @@ -58,8 +59,9 @@ public class IotHubController extends BaseController { @PostMapping("/versions/{versionId}/install") @ResponseBody public InstallItemVersionResult installItemVersion(@PathVariable String versionId, - @RequestBody(required = false) JsonNode data) throws ThingsboardException { - return iotHubService.installItemVersion(getCurrentUser(), versionId, data); + @RequestBody(required = false) JsonNode data, + HttpServletRequest request) throws ThingsboardException { + return iotHubService.installItemVersion(getCurrentUser(), versionId, data, request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @@ -67,8 +69,9 @@ public class IotHubController extends BaseController { @ResponseBody public UpdateItemVersionResult updateItemVersion(@PathVariable UUID installedItemId, @PathVariable String versionId, - @RequestParam(required = false, defaultValue = "false") boolean force) throws ThingsboardException { - return iotHubService.updateItemVersion(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, force); + @RequestParam(required = false, defaultValue = "false") boolean force, + HttpServletRequest request) throws ThingsboardException { + return iotHubService.updateItemVersion(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, force, request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index af5e966c13..5c2dfd937a 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -16,6 +16,7 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -32,7 +33,10 @@ import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; +import org.thingsboard.server.service.solutions.SolutionService; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.NodeConnectionInfo; import org.thingsboard.server.common.data.rule.RuleChainMetaData; @@ -76,9 +80,10 @@ public class DefaultIotHubService implements IotHubService { private final DashboardService dashboardService; private final CalculatedFieldService calculatedFieldService; private final DeviceProfileService deviceProfileService; + private final SolutionService solutionService; @Override - public InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data) { + public InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Installing IoT Hub item version: {}", tenantId, versionId); @@ -99,6 +104,7 @@ public class DefaultIotHubService implements IotHubService { case "CALCULATED_FIELD" -> installCalculatedField(user, tenantId, fileData, data); case "RULE_CHAIN" -> installRuleChain(tenantId, fileData); case "DEVICE" -> installDeviceProfile(user, tenantId, fileData); + case "SOLUTION_TEMPLATE" -> installSolution(user, tenantId, fileData, request); default -> throw new IllegalArgumentException("Unsupported IoT Hub item type: " + itemType); }; @@ -220,8 +226,22 @@ public class DefaultIotHubService implements IotHubService { return new DeviceInstalledItemDescriptor(); } + private SolutionTemplateInstalledItemDescriptor installSolution(SecurityUser user, TenantId tenantId, byte[] fileData, HttpServletRequest request) throws Exception { + SolutionInstallResponse response = solutionService.installSolution(user, tenantId, fileData, request); + if (!response.isSuccess()) { + throw new RuntimeException(response.getDetails()); + } + SolutionTemplateInstalledItemDescriptor descriptor = new SolutionTemplateInstalledItemDescriptor(); + descriptor.setCreatedEntityIds(response.getCreatedEntityIds()); + descriptor.setDashboardId(response.getDashboardId()); + descriptor.setPublicId(response.getPublicId()); + descriptor.setMainDashboardPublic(response.isMainDashboardPublic()); + descriptor.setDetails(response.getDetails()); + return descriptor; + } + @Override - public UpdateItemVersionResult updateItemVersion(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, boolean force) { + public UpdateItemVersionResult updateItemVersion(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, boolean force, HttpServletRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Updating IoT Hub installed item {} to version: {}", tenantId, installedItemId, versionId); @@ -231,17 +251,23 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item not found"); } - JsonNode installedVersionInfo = iotHubRestClient.getVersionInfo(installedItem.getItemVersionId().toString()); - String installedChecksum = installedVersionInfo.has("checksum") ? installedVersionInfo.get("checksum").asText() : null; - log.info("[{}] Installed version info: name={}, version={}, checksum={}", tenantId, installedItem.getItemName(), installedItem.getVersion(), installedChecksum); + String itemType = installedItem.getItemType(); + IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); + + // Skip checksum validation for solution templates + if (!"SOLUTION_TEMPLATE".equals(itemType)) { + JsonNode installedVersionInfo = iotHubRestClient.getVersionInfo(installedItem.getItemVersionId().toString()); + String installedChecksum = installedVersionInfo.has("checksum") ? installedVersionInfo.get("checksum").asText() : null; + log.info("[{}] Installed version info: name={}, version={}, checksum={}", tenantId, installedItem.getItemName(), installedItem.getVersion(), installedChecksum); - if (!force) { - String entityChecksum = calculateEntityChecksum(tenantId, installedItem); - boolean entityModified = installedChecksum != null && !installedChecksum.equals(entityChecksum); - log.info("[{}] Entity checksum: {}, modified: {}", tenantId, entityChecksum, entityModified); + if (!force) { + String entityChecksum = calculateEntityChecksum(tenantId, installedItem); + boolean entityModified = installedChecksum != null && !installedChecksum.equals(entityChecksum); + log.info("[{}] Entity checksum: {}, modified: {}", tenantId, entityChecksum, entityModified); - if (entityModified) { - return UpdateItemVersionResult.entityModified(); + if (entityModified) { + return UpdateItemVersionResult.entityModified(); + } } } @@ -252,14 +278,25 @@ public class DefaultIotHubService implements IotHubService { byte[] fileData = iotHubRestClient.getVersionFileData(versionId); log.info("[{}] Fetched update file data, size: {} bytes", tenantId, fileData != null ? fileData.length : 0); - IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); - String itemType = installedItem.getItemType(); switch (itemType) { case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData); case "DASHBOARD" -> updateDashboard(user, tenantId, (DashboardInstalledItemDescriptor) descriptor, fileData); case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData); case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); case "DEVICE" -> updateDeviceProfile(user, tenantId, fileData); + case "SOLUTION_TEMPLATE" -> { + SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor; + solutionService.deleteSolution(tenantId, stDescriptor.getCreatedEntityIds(), user); + SolutionInstallResponse response = solutionService.installSolution(user, tenantId, fileData, request); + if (!response.isSuccess()) { + throw new RuntimeException(response.getDetails()); + } + stDescriptor.setCreatedEntityIds(response.getCreatedEntityIds()); + stDescriptor.setDashboardId(response.getDashboardId()); + stDescriptor.setPublicId(response.getPublicId()); + stDescriptor.setMainDashboardPublic(response.isMainDashboardPublic()); + stDescriptor.setDetails(response.getDetails()); + } default -> throw new IllegalArgumentException("Unsupported IoT Hub item type: " + itemType); } @@ -470,6 +507,8 @@ public class DefaultIotHubService implements IotHubService { } } else if (descriptor instanceof DeviceInstalledItemDescriptor) { // no entity to delete for now + } else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) { + solutionService.deleteSolution(tenantId, st.getCreatedEntityIds(), user); } iotHubInstalledItemService.deleteById(tenantId, installedItemId); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index c7faf14bae..0abc8f7756 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -16,14 +16,15 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.service.security.model.SecurityUser; public interface IotHubService { - InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data); + InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); - UpdateItemVersionResult updateItemVersion(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, boolean force); + UpdateItemVersionResult updateItemVersion(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, boolean force, HttpServletRequest request); void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); } diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java new file mode 100644 index 0000000000..b340702385 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -0,0 +1,1462 @@ +/** + * Copyright © 2016-2026 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.solutions; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.JsonParser; +import jakarta.annotation.PreDestroy; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.common.util.ThingsBoardExecutors; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.adaptor.JsonConverter; +import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.alarm.AlarmInfo; +import org.thingsboard.server.common.data.alarm.AlarmQuery; +import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.data.security.UserCredentials; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.cf.configuration.BaseCalculatedFieldConfiguration; +import org.thingsboard.server.common.data.debug.DebugSettings; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.AlarmId; +import org.thingsboard.server.common.data.id.AssetId; +import org.thingsboard.server.common.data.id.EntityIdFactory; +import org.thingsboard.server.common.data.id.AssetProfileId; +import org.thingsboard.server.common.data.id.CalculatedFieldId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.UserId; +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.relation.EntityRelation; +import org.thingsboard.server.common.data.relation.EntitySearchDirection; +import org.thingsboard.server.common.data.relation.RelationTypeGroup; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.dao.alarm.AlarmService; +import org.thingsboard.server.dao.asset.AssetProfileService; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.cf.CalculatedFieldService; +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.relation.RelationService; +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.user.UserService; +import org.thingsboard.server.dao.rule.RuleChainService; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.queue.provider.TbQueueProducerProvider; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.action.EntityActionService; +import org.thingsboard.server.service.entitiy.asset.TbAssetService; +import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService; +import org.thingsboard.server.service.entitiy.device.TbDeviceService; +import org.thingsboard.server.service.entitiy.edge.TbEdgeService; +import org.thingsboard.server.service.rule.TbRuleChainService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.security.system.SystemSecurityService; +import org.thingsboard.server.service.solutions.data.CreatedAlarmRuleInfo; +import org.thingsboard.server.service.solutions.data.CreatedCalculatedFieldInfo; +import org.thingsboard.server.service.solutions.data.CreatedEntityInfo; +import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; +import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; +import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; +import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; +import org.thingsboard.server.service.solutions.data.definition.AssetProfileDefinition; +import org.thingsboard.server.service.solutions.data.definition.DeviceDefinition; +import org.thingsboard.server.service.solutions.data.definition.CustomerDefinition; +import org.thingsboard.server.service.solutions.data.definition.DashboardUserDetailsDefinition; +import org.thingsboard.server.service.solutions.data.definition.CalculatedFieldDefinition; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.solutions.data.definition.UserDefinition; +import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; +import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; +import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; +import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; +import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; +import org.thingsboard.server.service.solutions.data.emulator.AssetEmulatorLauncher; +import org.thingsboard.server.service.solutions.data.emulator.DeviceEmulatorLauncher; +import org.thingsboard.server.service.solutions.data.names.RandomNameData; +import org.thingsboard.server.service.solutions.data.names.RandomNameUtil; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; +import org.thingsboard.server.service.solutions.data.solution.TenantSolutionTemplateInstructions; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ExecutorService; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +@Service +@TbCoreComponent +@RequiredArgsConstructor +@Slf4j +public class DefaultSolutionService implements SolutionService { + + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") + private String docsBaseUrl; + + private final RuleChainService ruleChainService; + private final TbRuleChainService tbRuleChainService; + private final DeviceProfileService deviceProfileService; + private final DeviceService deviceService; + private final TbDeviceService tbDeviceService; + private final DeviceCredentialsService deviceCredentialsService; + private final AssetProfileService assetProfileService; + private final AssetService assetService; + private final TbAssetService tbAssetService; + private final CustomerService customerService; + private final UserService userService; + private final DashboardService dashboardService; + private final EdgeService edgeService; + private final TbEdgeService tbEdgeService; + private final RelationService relationService; + private final AlarmService alarmService; + private final CalculatedFieldService calculatedFieldService; + private final TbCalculatedFieldService tbCalculatedFieldService; + private final AttributesService attributesService; + private final EntityActionService entityActionService; + private final SystemSecurityService systemSecurityService; + private final TbClusterService tbClusterService; + private final PartitionService partitionService; + private final TbQueueProducerProvider tbQueueProducerProvider; + private final TbServiceInfoProvider serviceInfoProvider; + private final TelemetrySubscriptionService tsSubService; + private final BCryptPasswordEncoder passwordEncoder; + + private final ExecutorService emulatorExecutor = ThingsBoardExecutors.newWorkStealingPool(10, "solution-emulators-executor"); + + @PreDestroy + private void destroy() { + emulatorExecutor.shutdownNow(); + } + + @Override + public SolutionInstallResponse installSolution(SecurityUser user, TenantId tenantId, byte[] zipData, HttpServletRequest request) throws Exception { + Path tempDir = Files.createTempDirectory("iot-hub-solution-"); + SolutionInstallContext ctx = new SolutionInstallContext(tenantId, tempDir, user); + try { + extractZip(zipData, tempDir); + + registerEmulatorsAndComputeOldestTelemetryTs(ctx); + + provisionTenantDetails(ctx); + + provisionRuleChains(ctx); + provisionDeviceProfiles(ctx); + provisionAssetProfiles(ctx); + + List customers = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "customers.json", new TypeReference<>() {}); + provisionCustomers(ctx, customers); + + var assets = provisionAssets(ctx); + var devices = provisionDevices(ctx); + + provisionDashboards(ctx); + + provisionCustomerUsers(ctx, customers); + + provisionRelations(ctx); + updateRuleChains(ctx); + provisionEdges(ctx); + + provisionAlarmRules(ctx); + + Set> telemetryLoading = launchEmulators(ctx, devices, assets); + + waitForTelemetryCompletion(telemetryLoading); + + provisionCalculatedFields(ctx); + + ctx.getSolutionInstructions().setDetails(prepareInstructions(ctx, request)); + + List ruleChainDefs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "rule_chains.json", new TypeReference<>() {}); + if (ruleChainDefs.stream().anyMatch(r -> StringUtils.isNotEmpty(r.getUpdate()))) { + long timeout = loadInstallTimeoutMs(ctx.getTempDir()); + Thread.sleep(timeout); + finalUpdateRuleChains(ctx); + } + + log.info("[{}] Solution template installed, created {} entities", tenantId, ctx.getCreatedEntitiesList().size()); + + return new SolutionInstallResponse( + new TenantSolutionTemplateInstructions(ctx.getSolutionInstructions()), + true, + ctx.getCreatedEntitiesList() + ); + } catch (Throwable e) { + log.error("[{}] Failed to install solution template", tenantId, e); + rollback(tenantId, ctx, e); + return new SolutionInstallResponse( + new TenantSolutionTemplateInstructions(ctx.getSolutionInstructions()), + false, + ctx.getCreatedEntitiesList() + ); + } finally { + deleteDirectory(tempDir); + } + } + + @Override + public void deleteSolution(TenantId tenantId, List createdEntityIds, SecurityUser user) { + if (createdEntityIds == null || createdEntityIds.isEmpty()) { + return; + } + List reversed = new ArrayList<>(createdEntityIds); + Collections.reverse(reversed); + for (EntityId entityId : reversed) { + try { + deleteEntity(tenantId, entityId, user); + } catch (Exception e) { + log.error("[{}] Failed to delete entity: {}", tenantId, entityId, e); + } + } + } + + private void provisionRuleChains(SolutionInstallContext ctx) { + List ruleChainDefs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "rule_chains.json", new TypeReference<>() {}); + for (ReferenceableEntityDefinition entityDef : ruleChainDefs) { + Path ruleChainPath = ctx.getTempDir().resolve("rule_chains").resolve(entityDef.getFile()); + if (!Files.exists(ruleChainPath)) { + log.warn("[{}] Rule chain file not found: {}", ctx.getTenantId(), entityDef.getFile()); + continue; + } + JsonNode ruleChainJson = replaceIds(ctx, JacksonUtil.toJsonNode(ruleChainPath)); + + RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson.get("ruleChain"), RuleChain.class); + ruleChain.setId(null); + ruleChain.setTenantId(ctx.getTenantId()); + String metadataStr = JacksonUtil.toString(ruleChainJson.get("metadata")); + RuleChainMetaData metadata = JacksonUtil.treeToValue(JacksonUtil.toJsonNode(metadataStr), RuleChainMetaData.class); + + RuleChain savedRuleChain = ruleChainService.saveRuleChain(ruleChain); + metadata.setRuleChainId(savedRuleChain.getId()); + metadata.setVersion(savedRuleChain.getVersion()); + ruleChainService.saveRuleChainMetaData(ctx.getTenantId(), metadata, tbRuleChainService::updateRuleNodeConfiguration); + if (ruleChain.isRoot()) { + ruleChainService.setRootRuleChain(ctx.getTenantId(), savedRuleChain.getId()); + } + + ctx.register(entityDef.getJsonId(), savedRuleChain); + log.debug("[{}] Rule chain provisioned: {}", ctx.getTenantId(), savedRuleChain.getName()); + } + } + + private void updateRuleChains(SolutionInstallContext ctx) { + List ruleChainDefs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "rule_chains.json", new TypeReference<>() {}); + for (ReferenceableEntityDefinition entityDef : ruleChainDefs) { + Path ruleChainPath = ctx.getTempDir().resolve("rule_chains").resolve(entityDef.getFile()); + if (!Files.exists(ruleChainPath)) { + continue; + } + String realId = ctx.getRealIds().get(entityDef.getJsonId()); + if (realId == null) { + continue; + } + RuleChainId ruleChainId = new RuleChainId(UUID.fromString(realId)); + RuleChain savedRuleChain = ruleChainService.findRuleChainById(ctx.getTenantId(), ruleChainId); + if (savedRuleChain == null) { + continue; + } + JsonNode ruleChainJson = JacksonUtil.toJsonNode(ruleChainPath); + String metadataStr = JacksonUtil.toString(ruleChainJson.get("metadata")); + String oldMetadataStr = metadataStr; + for (var entry : ctx.getRealIds().entrySet()) { + metadataStr = metadataStr.replace(entry.getKey(), entry.getValue()); + } + if (metadataStr.equals(oldMetadataStr)) { + continue; + } + RuleChainMetaData metadata = JacksonUtil.treeToValue(JacksonUtil.toJsonNode(metadataStr), RuleChainMetaData.class); + metadata.setRuleChainId(ruleChainId); + metadata.setVersion(savedRuleChain.getVersion()); + ruleChainService.saveRuleChainMetaData(ctx.getTenantId(), metadata, tbRuleChainService::updateRuleNodeConfiguration); + } + } + + private void finalUpdateRuleChains(SolutionInstallContext ctx) { + List ruleChains = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "rule_chains.json", new TypeReference<>() {}); + for (ReferenceableEntityDefinition entityDefinition : ruleChains) { + if (StringUtils.isEmpty(entityDefinition.getUpdate())) { + continue; + } + Path ruleChainPath = ctx.getTempDir().resolve("rule_chains").resolve(entityDefinition.getUpdate()); + JsonNode ruleChainJson = JacksonUtil.toJsonNode(ruleChainPath); + RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson.get("ruleChain"), RuleChain.class); + ruleChain.setTenantId(ctx.getTenantId()); + String metadataStr = JacksonUtil.toString(ruleChainJson.get("metadata")); + for (var entry : ctx.getRealIds().entrySet()) { + metadataStr = metadataStr.replace(entry.getKey(), entry.getValue()); + } + RuleChainMetaData ruleChainMetaData = JacksonUtil.treeToValue(JacksonUtil.toJsonNode(metadataStr), RuleChainMetaData.class); + + String realRuleChainId = ctx.getRealIds().get(entityDefinition.getJsonId()); + if (StringUtils.isEmpty(realRuleChainId)) { + continue; + } + RuleChainId ruleChainId = new RuleChainId(UUID.fromString(realRuleChainId)); + RuleChain savedRuleChain = ruleChainService.findRuleChainById(ctx.getTenantId(), ruleChainId); + ruleChainMetaData.setRuleChainId(savedRuleChain.getId()); + ruleChainMetaData.setVersion(savedRuleChain.getVersion()); + ruleChainService.saveRuleChainMetaData(ctx.getTenantId(), ruleChainMetaData, tbRuleChainService::updateRuleNodeConfiguration); + } + } + + private long loadInstallTimeoutMs(Path tempDir) { + Path solutionJson = tempDir.resolve("solution.json"); + if (Files.exists(solutionJson)) { + JsonNode node = JacksonUtil.toJsonNode(solutionJson); + if (node != null && node.has("installTimeoutMs")) { + return node.get("installTimeoutMs").asLong(0L); + } + } + return 0L; + } + + private void provisionDeviceProfiles(SolutionInstallContext ctx) { + List deviceProfiles = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "device_profiles.json", new TypeReference<>() {}); + deviceProfiles.addAll(loadListOfEntitiesFromDirectory(ctx.getTempDir(), "device_profiles", DeviceProfileDefinition.class)); + deviceProfiles.forEach(deviceProfile -> { + deviceProfile.setId(null); + deviceProfile.setCreatedTime(0L); + deviceProfile.setTenantId(ctx.getTenantId()); + if (deviceProfile.getDefaultRuleChainId() != null) { + String newId = ctx.getRealIds().get(deviceProfile.getDefaultRuleChainId().getId().toString()); + if (newId != null) { + deviceProfile.setDefaultRuleChainId(new RuleChainId(UUID.fromString(newId))); + } else { + log.error("[{}] Device profile: {} references non existing rule chain.", ctx.getTenantId(), deviceProfile.getName()); + throw new RuntimeException("Device profile: " + deviceProfile.getName() + " references non existing rule chain."); + } + } + if (deviceProfile.getDefaultEdgeRuleChainId() != null) { + String newId = ctx.getRealIds().get(deviceProfile.getDefaultEdgeRuleChainId().getId().toString()); + if (StringUtils.isEmpty(newId)) { + deviceProfile.setDefaultEdgeRuleChainId(null); + } else { + deviceProfile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.fromString(newId))); + } + } + if (deviceProfile.getDefaultDashboardId() != null) { + String newId = ctx.getRealIds().get(deviceProfile.getDefaultDashboardId().getId().toString()); + if (newId != null) { + deviceProfile.setDefaultDashboardId(new DashboardId(UUID.fromString(newId))); + } + } + }); + + deviceProfiles.forEach(deviceProfileDefinition -> { + DeviceProfile deviceProfile = new DeviceProfile(deviceProfileDefinition); + deviceProfile = deviceProfileService.saveDeviceProfile(deviceProfile); + ctx.register(deviceProfileDefinition, deviceProfile); + }); + } + + private void provisionAssetProfiles(SolutionInstallContext ctx) { + List assetProfiles = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "asset_profiles.json", new TypeReference<>() {}); + assetProfiles.addAll(loadListOfEntitiesFromDirectory(ctx.getTempDir(), "asset_profiles", AssetProfileDefinition.class)); + assetProfiles.forEach(assetProfile -> { + assetProfile.setId(null); + assetProfile.setCreatedTime(0L); + assetProfile.setTenantId(ctx.getTenantId()); + if (assetProfile.getDefaultRuleChainId() != null) { + String newId = ctx.getRealIds().get(assetProfile.getDefaultRuleChainId().getId().toString()); + if (newId != null) { + assetProfile.setDefaultRuleChainId(new RuleChainId(UUID.fromString(newId))); + } else { + log.error("[{}] Asset profile: {} references non existing rule chain.", ctx.getTenantId(), assetProfile.getName()); + throw new RuntimeException("Asset profile: " + assetProfile.getName() + " references non existing rule chain."); + } + } + if (assetProfile.getDefaultEdgeRuleChainId() != null) { + String newId = ctx.getRealIds().get(assetProfile.getDefaultEdgeRuleChainId().getId().toString()); + if (StringUtils.isEmpty(newId)) { + assetProfile.setDefaultEdgeRuleChainId(null); + } else { + assetProfile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.fromString(newId))); + } + } + }); + + assetProfiles.forEach(assetProfileDefinition -> { + AssetProfile assetProfile = new AssetProfile(assetProfileDefinition); + assetProfile = assetProfileService.saveAssetProfile(assetProfile); + ctx.register(assetProfileDefinition, assetProfile); + }); + } + + private Map provisionAssets(SolutionInstallContext ctx) { + Map result = new HashMap<>(); + Set assetTypeSet = new HashSet<>(); + List assets = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "assets.json", new TypeReference<>() {}); + for (AssetDefinition entityDef : assets) { + Asset entity = new Asset(); + entity.setTenantId(ctx.getTenantId()); + entity.setName(entityDef.getName()); + entity.setLabel(entityDef.getLabel()); + entity.setType(entityDef.getType()); + if (entityDef.isMakePublic()) { + entity.setCustomerId(getPublicCustomerId(ctx)); + } else { + entity.setCustomerId(ctx.getIdFromMap(EntityType.CUSTOMER, entityDef.getCustomer())); + } + ensureAssetProfileExists(ctx, assetTypeSet, entityDef); + entity = assetService.saveAsset(entity); + ctx.register(entityDef, entity); + log.info("[{}] Saved asset: {}", entity.getId(), entity); + AssetId entityId = entity.getId(); + ctx.putIdToMap(entityDef, entityId); + saveServerSideAttributes(ctx, entityId, entityDef.getAttributes()); + ctx.put(entityId, entityDef.getRelations()); + result.put(entity, entityDef); + } + return result; + } + + private void ensureAssetProfileExists(SolutionInstallContext ctx, Set assetTypeSet, AssetDefinition entityDef) { + if (!assetTypeSet.contains(entityDef.getType())) { + AssetProfile assetProfile = assetProfileService.findAssetProfileByName(ctx.getTenantId(), entityDef.getType()); + if (assetProfile == null) { + AssetProfile created = assetProfileService.findOrCreateAssetProfile(ctx.getTenantId(), entityDef.getType()); + ctx.register(created.getId()); + log.info("Saved asset profile: {}", created.getId()); + } + assetTypeSet.add(entityDef.getType()); + } + } + + private CustomerId getPublicCustomerId(SolutionInstallContext ctx) { + CustomerId publicId = ctx.getSolutionInstructions().getPublicId(); + if (publicId != null) { + return publicId; + } + Customer publicCustomer = customerService.findOrCreatePublicCustomer(ctx.getTenantId()); + ctx.getSolutionInstructions().setPublicId(publicCustomer.getId()); + return publicCustomer.getId(); + } + + private Map provisionDevices(SolutionInstallContext ctx) { + Map result = new HashMap<>(); + Set deviceTypeSet = new HashSet<>(); + List devices = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "devices.json", new TypeReference<>() {}); + for (DeviceDefinition entityDef : devices) { + CustomerId customerId = entityDef.isMakePublic() ? getPublicCustomerId(ctx) : ctx.getIdFromMap(EntityType.CUSTOMER, entityDef.getCustomer()); + Device entity = new Device(); + entity.setTenantId(ctx.getTenantId()); + entity.setName(entityDef.getName()); + entity.setLabel(entityDef.getLabel()); + ensureDeviceProfileExists(ctx, deviceTypeSet, entityDef); + entity.setType(entityDef.getType()); + entity.setCustomerId(customerId); + entity.setAdditionalInfo(entityDef.getAdditionalInfo()); + entity = deviceService.saveDevice(entity); + entityActionService.logEntityAction(ctx.getUser(), entity.getId(), entity, customerId, ActionType.ADDED, null); + ctx.register(entityDef, entity); + log.info("[{}] Saved device: {}", entity.getId(), entity); + DeviceId entityId = entity.getId(); + ctx.putIdToMap(entityDef, entityId); + saveServerSideAttributes(ctx, entityId, entityDef.getAttributes()); + saveSharedAttributes(ctx, entityId, entityDef.getSharedAttributes()); + ctx.put(entityId, entityDef.getRelations()); + + DeviceCredentialsInfo deviceCredentialsInfo = new DeviceCredentialsInfo(); + deviceCredentialsInfo.setName(entity.getName()); + deviceCredentialsInfo.setType(entity.getType()); + deviceCredentialsInfo.setCustomerName(entityDef.getCustomer()); + deviceCredentialsInfo.setCredentials(deviceCredentialsService.findDeviceCredentialsByDeviceId(ctx.getTenantId(), entityId)); + JsonNode additionalInfo = entity.getAdditionalInfo(); + boolean isGateway = additionalInfo != null && additionalInfo.hasNonNull("gateway") && additionalInfo.get("gateway").asBoolean(); + deviceCredentialsInfo.setGateway(isGateway); + ctx.addDeviceCredentials(deviceCredentialsInfo); + + result.put(entity, entityDef); + } + return result; + } + + private void ensureDeviceProfileExists(SolutionInstallContext ctx, Set deviceTypeSet, DeviceDefinition entityDef) { + if (!deviceTypeSet.contains(entityDef.getType())) { + DeviceProfile deviceProfile = deviceProfileService.findDeviceProfileByName(ctx.getTenantId(), entityDef.getType()); + if (deviceProfile == null) { + DeviceProfile created = deviceProfileService.findOrCreateDeviceProfile(ctx.getTenantId(), entityDef.getType()); + ctx.register(created.getId()); + log.info("Saved device profile: {}", created.getId()); + } + deviceTypeSet.add(entityDef.getType()); + } + } + + private void provisionCustomers(SolutionInstallContext ctx, List customers) { + for (CustomerDefinition entityDef : customers) { + entityDef.setRandomNameData(generateRandomName(ctx)); + Customer customer = new Customer(); + customer.setTenantId(ctx.getTenantId()); + customer.setTitle(randomize(entityDef.getName(), entityDef.getRandomNameData())); + customer.setEmail(randomize(entityDef.getEmail(), entityDef.getRandomNameData())); + customer.setCountry(entityDef.getCountry()); + customer.setCity(entityDef.getCity()); + customer.setState(entityDef.getState()); + customer.setZip(entityDef.getZip()); + customer.setAddress(entityDef.getAddress()); + customer = customerService.saveCustomer(customer); + log.info("[{}] Saved customer: {}", customer.getId(), customer); + ctx.register(entityDef, customer); + CustomerId entityId = customer.getId(); + ctx.putIdToMap(entityDef, entityId); + saveServerSideAttributes(ctx, entityId, entityDef.getAttributes(), entityDef.getRandomNameData()); + ctx.put(entityId, entityDef.getRelations()); + entityDef.setName(customer.getName()); + } + } + + private void provisionCustomerUsers(SolutionInstallContext ctx, List customers) { + for (CustomerDefinition entityDef : customers) { + Customer customer = customerService.findCustomerByTenantIdAndTitle(ctx.getTenantId(), entityDef.getName()).get(); + for (UserDefinition uDef : entityDef.getUsers()) { + String originalName = uDef.getName(); + User user = createUser(ctx, customer, uDef, entityDef); + + UserCredentials credentials = userService.findUserCredentialsByUserId(ctx.getTenantId(), user.getId()); + credentials.setEnabled(true); + credentials.setActivateToken(null); + credentials.setPassword(passwordEncoder.encode(uDef.getPassword())); + userService.saveUserCredentials(ctx.getTenantId(), credentials); + + DashboardUserDetailsDefinition dd = uDef.getDashboard(); + if (dd != null) { + DashboardId dashboardId = ctx.getIdFromMap(EntityType.DASHBOARD, dd.getName()); + ObjectNode additionalInfo = JacksonUtil.newObjectNode(); + additionalInfo.put("defaultDashboardId", dashboardId.getId().toString()); + additionalInfo.put("defaultDashboardFullscreen", dd.isFullScreen()); + user.setAdditionalInfo(additionalInfo); + userService.saveUser(ctx.getTenantId(), user); + log.info("[{}] Added default dashboard for user {}", customer.getId(), user.getEmail()); + } + + UserCredentialsInfo credentialsInfo = new UserCredentialsInfo(); + credentialsInfo.setName(user.getFirstName() + " " + user.getLastName()); + credentialsInfo.setLogin(uDef.getName()); + credentialsInfo.setPassword(uDef.getPassword()); + credentialsInfo.setCustomerName(entityDef.getName()); + ctx.addUserCredentials(credentialsInfo); + ctx.register(entityDef, user); + ctx.put(user.getId(), uDef.getRelations()); + ctx.putIdToMap(EntityType.USER, originalName, user.getId()); + ctx.putIdToMap(EntityType.USER, uDef.getName(), user.getId()); + saveServerSideAttributes(ctx, user.getId(), uDef.getAttributes()); + } + } + } + + private User createUser(SolutionInstallContext ctx, Customer customer, UserDefinition uDef, CustomerDefinition cDef) { + int maxAttempts = 10; + int attempts = 0; + Exception finalE = null; + while (attempts < maxAttempts) { + try { + boolean lastAttempt = maxAttempts == (attempts + 1); + var randomName = lastAttempt ? RandomNameUtil.nextSuperRandom() : RandomNameUtil.next(); + User user = new User(); + if (!StringUtils.isEmpty(uDef.getFirstname())) { + user.setFirstName(randomize(uDef.getFirstname(), randomName, cDef.getRandomNameData())); + } else { + user.setFirstName(randomName.getFirstName()); + } + if (!StringUtils.isEmpty(uDef.getLastname())) { + user.setLastName(randomize(uDef.getLastname(), randomName, cDef.getRandomNameData())); + } else { + user.setLastName(randomName.getLastName()); + } + user.setAuthority(Authority.CUSTOMER_USER); + user.setEmail(randomize(uDef.getName(), randomName, cDef.getRandomNameData())); + user.setCustomerId(customer.getId()); + user.setTenantId(ctx.getTenantId()); + log.info("[{}] Saving user: {}", customer.getId(), user); + user = userService.saveUser(ctx.getTenantId(), user); + uDef.setName(user.getEmail()); + return user; + } catch (Exception e) { + finalE = e; + attempts++; + } + } + throw new RuntimeException(finalE); + } + + private void provisionEdges(SolutionInstallContext ctx) throws Exception { + List edges = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "edges.json", new TypeReference<>() {}); + RuleChain edgeTemplateRootRuleChain = ruleChainService.getEdgeTemplateRootRuleChain(ctx.getTenantId()); + for (EdgeDefinition entityDef : edges) { + CustomerId customerId = entityDef.isMakePublic() ? getPublicCustomerId(ctx) : ctx.getIdFromMap(EntityType.CUSTOMER, entityDef.getCustomer()); + Edge entity = new Edge(); + entity.setTenantId(ctx.getTenantId()); + entity.setName(entityDef.getName()); + entity.setLabel(entityDef.getLabel()); + entity.setType(entityDef.getType()); + entity.setCustomerId(customerId); + entity.setRoutingKey(UUID.randomUUID().toString()); + entity.setSecret(StringUtils.randomAlphanumeric(20)); + RuleChainId rootRuleChainId = edgeTemplateRootRuleChain.getId(); + if (StringUtils.isNotBlank(entityDef.getRootRuleChainId())) { + String newId = ctx.getRealIds().get(entityDef.getRootRuleChainId()); + if (newId != null) { + rootRuleChainId = new RuleChainId(UUID.fromString(newId)); + } else { + log.error("[{}] Edge: {} references non existing rule chain.", ctx.getTenantId(), entity.getName()); + throw new RuntimeException("Edge: " + entity.getName() + " references non existing rule chain."); + } + } + entity.setRootRuleChainId(rootRuleChainId); + RuleChain rootRuleChain = ruleChainService.findRuleChainById(ctx.getTenantId(), rootRuleChainId); + entity = tbEdgeService.save(entity, rootRuleChain, ctx.getUser()); + ctx.register(entityDef, entity); + assignRuleChainsToEdge(ctx, entityDef.getRuleChainIds(), entity); + assignAssetsToEdge(ctx, entityDef.getAssetIds(), entity); + assignDevicesToEdge(ctx, entityDef.getDeviceIds(), entity); + log.info("[{}] Saved edge: {}", entity.getId(), entity); + EdgeId entityId = entity.getId(); + ctx.putIdToMap(entityDef, entityId); + saveServerSideAttributes(ctx, entityId, entityDef.getAttributes()); + ctx.put(entityId, entityDef.getRelations()); + ctx.addEdgeLinkInfo(entity.getName(), new EdgeLinkInfo(entity.getId(), customerId != null ? customerId : ctx.getTenantId())); + } + } + + private void assignRuleChainsToEdge(SolutionInstallContext ctx, List ruleChainIds, Edge entity) { + if (ruleChainIds == null || ruleChainIds.isEmpty()) { + return; + } + for (String strRuleChainId : ruleChainIds) { + String newId = ctx.getRealIds().get(strRuleChainId); + if (newId != null) { + RuleChainId ruleChainId = new RuleChainId(UUID.fromString(newId)); + ruleChainService.assignRuleChainToEdge(ctx.getTenantId(), ruleChainId, entity.getId()); + } else { + log.error("[{}] Edge: {} references non existing edge rule chain.", ctx.getTenantId(), entity.getName()); + throw new RuntimeException("Edge: " + entity.getName() + " references non existing edge rule chain."); + } + } + } + + private void assignAssetsToEdge(SolutionInstallContext ctx, List assetIds, Edge entity) { + if (assetIds == null || assetIds.isEmpty()) { + return; + } + for (String strAssetId : assetIds) { + String newId = ctx.getRealIds().get(strAssetId); + if (newId != null) { + AssetId assetId = new AssetId(UUID.fromString(newId)); + assetService.assignAssetToEdge(ctx.getTenantId(), assetId, entity.getId()); + } else { + log.error("[{}] Edge: {} references non existing asset.", ctx.getTenantId(), entity.getName()); + throw new RuntimeException("Edge: " + entity.getName() + " references non existing asset."); + } + } + } + + private void assignDevicesToEdge(SolutionInstallContext ctx, List deviceIds, Edge entity) { + if (deviceIds == null || deviceIds.isEmpty()) { + return; + } + for (String strDeviceId : deviceIds) { + String newId = ctx.getRealIds().get(strDeviceId); + if (newId != null) { + DeviceId deviceId = new DeviceId(UUID.fromString(newId)); + deviceService.assignDeviceToEdge(ctx.getTenantId(), deviceId, entity.getId()); + } else { + log.error("[{}] Edge: {} references non existing device.", ctx.getTenantId(), entity.getName()); + throw new RuntimeException("Edge: " + entity.getName() + " references non existing device."); + } + } + } + + private void provisionAlarmRules(SolutionInstallContext ctx) { + List cfs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "alarm_rules.json", new TypeReference<>() {}); + cfs.addAll(loadListOfEntitiesFromDirectory(ctx.getTempDir(), "alarm_rules", CalculatedField.class)); + cfs.forEach(cf -> ctx.register(createCalculatedField(cf, ctx))); + } + + private void provisionCalculatedFields(SolutionInstallContext ctx) { + List cfs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "calculated_fields.json", new TypeReference<>() { + }); + cfs.addAll(loadListOfEntitiesFromDirectory(ctx.getTempDir(), "calculated_fields", CalculatedFieldDefinition.class)); + + List createOnly = new ArrayList<>(); + TreeMap> ordered = new TreeMap<>(); + + for (CalculatedFieldDefinition cf : cfs) { + if (cf.getReprocessingOrder() == null || cf.getReprocessingOrder() < 0) { + createOnly.add(cf); + } else { + ordered.computeIfAbsent(cf.getReprocessingOrder(), integer -> new ArrayList<>()).add(cf); + } + } + + createOnly.forEach(cf -> ctx.register(createCalculatedField(cf, ctx))); + + for (Map.Entry> entry : ordered.entrySet()) { + List cfDefs = entry.getValue(); + for (CalculatedFieldDefinition cfDef : cfDefs) { + CalculatedField calculatedField = createCalculatedField(cfDef, ctx); + ctx.register(calculatedField); + } + } + } + + private CalculatedField createCalculatedField(CalculatedField cf, SolutionInstallContext ctx) { + cf.setId(null); + cf.setCreatedTime(0L); + cf.setTenantId(ctx.getTenantId()); + cf.setDebugSettings(new DebugSettings(true, System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(15))); + + Map realIds = ctx.getRealIds(); + + EntityId entityId = cf.getEntityId(); + if (entityId != null) { + String newEntityId = realIds.get(entityId.getId().toString()); + if (newEntityId != null) { + cf.setEntityId(EntityIdFactory.getByTypeAndUuid(entityId.getEntityType(), newEntityId)); + } else { + log.error("[{}] Calculated field: {} references non existing entity.", ctx.getTenantId(), cf.getName()); + throw new RuntimeException("Calculated field: " + cf.getName() + " references non existing entity."); + } + } + if (cf.getConfiguration() instanceof BaseCalculatedFieldConfiguration baseCfg) { + baseCfg.getArguments().forEach((key, argument) -> { + EntityId refEntityId = argument.getRefEntityId(); + if (refEntityId != null) { + if (refEntityId.getEntityType() == EntityType.TENANT) { + argument.setRefEntityId(ctx.getTenantId()); + } else { + String newId = realIds.get(refEntityId.getId().toString()); + if (newId != null) { + argument.setRefEntityId(EntityIdFactory.getByTypeAndUuid(refEntityId.getEntityType(), newId)); + } else { + log.error("[{}] Calculated field: {} references non existing entity.", ctx.getTenantId(), cf.getName()); + throw new RuntimeException("Calculated field: " + cf.getName() + " references non existing entity."); + } + } + } + }); + } + + CalculatedField calculatedField = new CalculatedField(cf); + return calculatedFieldService.save(calculatedField); + } + + private void provisionTenantDetails(SolutionInstallContext ctx) { + TenantDefinition tenant = loadEntityIfFileExists(ctx.getTempDir(), "tenant.json", TenantDefinition.class); + if (tenant != null) { + saveServerSideAttributes(ctx, ctx.getTenantId(), tenant.getAttributes()); + ctx.put(ctx.getTenantId(), tenant.getRelations()); + } + } + + private void registerEmulatorsAndComputeOldestTelemetryTs(SolutionInstallContext ctx) { + List emulatorDefinitions = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "device_emulators.json", new TypeReference<>() { + }); + Map deviceEmulators = emulatorDefinitions.stream().collect(Collectors.toMap(EmulatorDefinition::getName, Function.identity())); + emulatorDefinitions.stream().filter(ed -> StringUtils.isNotEmpty(ed.getExtendz())) + .forEach(ed -> { + EmulatorDefinition parent = deviceEmulators.get(ed.getExtendz()); + if (parent != null) { + ed.enrich(parent); + } + }); + Map assetEmulators = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "asset_emulators.json", new TypeReference>() { + }).stream().collect(Collectors.toMap(EmulatorDefinition::getName, Function.identity())); + + ctx.setDeviceEmulators(deviceEmulators); + ctx.setAssetEmulators(assetEmulators); + + long solutionInstallTs = ctx.getInstallTs(); + long oldestDeviceEmulatorsTs = deviceEmulators.values().stream() + .mapToLong(value -> value.getOldestTs(solutionInstallTs)) + .min().orElse(solutionInstallTs); + long oldestAssetEmulatorsTs = assetEmulators.values().stream() + .mapToLong(value -> value.getOldestTs(solutionInstallTs)) + .min().orElse(solutionInstallTs); + long solutionOldestTs = Math.min(oldestDeviceEmulatorsTs, oldestAssetEmulatorsTs); + + ctx.setOldestTelemetryTs(solutionOldestTs); + } + + private Set> launchEmulators(SolutionInstallContext ctx, Map devicesMap, Map assets) throws Exception { + Set> results = new HashSet<>(); + + for (var entry : devicesMap.entrySet().stream().filter(e -> StringUtils.isNotBlank(e.getValue().getEmulator())).collect(Collectors.toSet())) { + results.add(DeviceEmulatorLauncher.builder() + .entity(entry.getKey()) + .emulatorDefinition(ctx.getDeviceEmulators().get(entry.getValue().getEmulator())) + .oldTelemetryExecutor(emulatorExecutor) + .tbClusterService(tbClusterService) + .partitionService(partitionService) + .tbQueueProducerProvider(tbQueueProducerProvider) + .serviceInfoProvider(serviceInfoProvider) + .tsSubService(tsSubService) + .build().launch()); + } + + for (var entry : assets.entrySet().stream().filter(e -> StringUtils.isNotBlank(e.getValue().getEmulator())).collect(Collectors.toSet())) { + results.add(AssetEmulatorLauncher.builder() + .entity(entry.getKey()) + .emulatorDefinition(ctx.getAssetEmulators().get(entry.getValue().getEmulator())) + .oldTelemetryExecutor(emulatorExecutor) + .tbClusterService(tbClusterService) + .partitionService(partitionService) + .tbQueueProducerProvider(tbQueueProducerProvider) + .serviceInfoProvider(serviceInfoProvider) + .tsSubService(tsSubService) + .build().launch()); + } + + return results; + } + + private void waitForTelemetryCompletion(Set> futures) throws InterruptedException { + CompletableFuture all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); + try { + all.get(); + Thread.sleep(futures.size() * 100L); + } catch (ExecutionException e) { + throw new RuntimeException("Telemetry processing failed", e.getCause()); + } + } + + private void provisionDashboards(SolutionInstallContext ctx) { + List dashboardDefs = loadListOfEntitiesIfFileExists(ctx.getTempDir(), "dashboards.json", new TypeReference<>() {}); + for (DashboardDefinition entityDef : dashboardDefs) { + CustomerId customerId = entityDef.isMakePublic() ? getPublicCustomerId(ctx) : ctx.getIdFromMap(EntityType.CUSTOMER, entityDef.getCustomer()); + Path dashboardPath = ctx.getTempDir().resolve("dashboards").resolve(entityDef.getFile()); + if (!Files.exists(dashboardPath)) { + log.warn("[{}] Dashboard file not found: {}", ctx.getTenantId(), entityDef.getFile()); + continue; + } + JsonNode dashboardJson = replaceIds(ctx, JacksonUtil.toJsonNode(dashboardPath)); + Dashboard dashboardTemplate = JacksonUtil.treeToValue(dashboardJson, Dashboard.class); + + Dashboard dashboard = new Dashboard(); + dashboard.setTenantId(ctx.getTenantId()); + dashboard.setTitle(entityDef.getName()); + dashboard.setConfiguration(dashboardTemplate.getConfiguration()); + dashboard.setImage(dashboardTemplate.getImage()); + dashboard.setResources(dashboardTemplate.getResources()); + if (dashboardJson.has("mobileHide") && dashboardJson.get("mobileHide").isBoolean()) { + dashboard.setMobileHide(dashboardJson.get("mobileHide").asBoolean()); + } + if (dashboardJson.has("mobileOrder") && dashboardJson.get("mobileOrder").isInt()) { + dashboard.setMobileOrder(dashboardJson.get("mobileOrder").asInt()); + } + + dashboard = dashboardService.saveDashboard(dashboard); + if (customerId != null) { + dashboardService.assignDashboardToCustomer(ctx.getTenantId(), dashboard.getId(), customerId); + } + ctx.register(entityDef, dashboard); + ctx.putIdToMap(EntityType.DASHBOARD, entityDef.getName(), dashboard.getId()); + + if (entityDef.isMain()) { + ctx.getSolutionInstructions().setDashboardId(dashboard.getId()); + ctx.getSolutionInstructions().setMainDashboardPublic(entityDef.isMakePublic()); + } + ctx.getDashboardLinks().add(new DashboardLinkInfo(dashboard.getTitle(), dashboard.getId(), entityDef.isMakePublic())); + + log.debug("[{}] Dashboard provisioned: {}", ctx.getTenantId(), dashboard.getTitle()); + } + } + + private void provisionRelations(SolutionInstallContext ctx) { + for (var entry : ctx.getRelationDefinitions().entrySet()) { + EntityId entityId = entry.getKey(); + for (RelationDefinition relationDef : entry.getValue()) { + EntityId targetId = resolveRelatedEntityId(ctx, relationDef); + if (targetId == null) { + log.warn("[{}] Relation target not found: {} '{}'", ctx.getTenantId(), relationDef.getEntityType(), relationDef.getEntityName()); + continue; + } + EntityRelation relation = new EntityRelation(); + if (relationDef.getDirection() == EntitySearchDirection.FROM) { + relation.setFrom(entityId); + relation.setTo(targetId); + } else { + relation.setFrom(targetId); + relation.setTo(entityId); + } + relation.setType(relationDef.getType()); + relation.setTypeGroup(RelationTypeGroup.COMMON); + relationService.saveRelation(ctx.getTenantId(), relation); + } + } + } + + private EntityId resolveRelatedEntityId(SolutionInstallContext ctx, RelationDefinition relationDef) { + if (relationDef.getEntityType() == EntityType.TENANT) { + return ctx.getTenantId(); + } + return ctx.getIdFromMap(relationDef.getEntityType(), relationDef.getEntityName()); + } + + private String prepareInstructions(SolutionInstallContext ctx, HttpServletRequest request) { + Path instructionsFile = ctx.getTempDir().resolve("instructions.md"); + if (!Files.exists(instructionsFile)) { + return null; + } + String template; + try { + template = Files.readString(instructionsFile); + } catch (IOException e) { + log.warn("[{}] Failed to read instructions.md", ctx.getTenantId(), e); + return null; + } + + String baseUrl = systemSecurityService.getBaseUrl(ctx.getTenantId(), null, request); + + // Inject edge instructions first, then run the full replacement logic on the combined string + if (template.contains("${edge_instructions}")) { + if (ctx.getCreatedEdges().isEmpty()) { + template = template.replace("${edge_instructions}", ""); + } else { + Path edgeFile = ctx.getTempDir().resolve("edge_instructions.md"); + String edgeTemplate = Files.exists(edgeFile) ? readFileContent(edgeFile) : ""; + template = template.replace("${edge_instructions}", edgeTemplate); + } + } + + template = template.replace("${DOCS_BASE_URL}", docsBaseUrl); + template = template.replace("${BASE_URL}", baseUrl); + + TenantSolutionTemplateInstructions solutionInstructions = ctx.getSolutionInstructions(); + + if (solutionInstructions.getDashboardId() != null) { + template = template.replace("${MAIN_DASHBOARD_URL}", + getDashboardLink(solutionInstructions, solutionInstructions.getDashboardId(), false)); + if (solutionInstructions.isMainDashboardPublic()) { + template = template.replace("${MAIN_DASHBOARD_PUBLIC_URL}", + getDashboardLink(solutionInstructions, solutionInstructions.getDashboardId(), true)); + } + } + + for (DashboardLinkInfo dashboardLinkInfo : ctx.getDashboardLinks()) { + template = template.replace("${" + dashboardLinkInfo.getName() + "DASHBOARD_URL}", + getDashboardLink(solutionInstructions, dashboardLinkInfo.getDashboardId(), false)); + if (dashboardLinkInfo.isPublic()) { + template = template.replace("${" + dashboardLinkInfo.getName() + "DASHBOARD_PUBLIC_URL}", + getDashboardLink(solutionInstructions, dashboardLinkInfo.getDashboardId(), true)); + } + } + + if (template.contains("${GATEWAYS_URL}")) { + template = template.replace("${GATEWAYS_URL}", "/gateways"); + } + + // Device list and credentials + StringBuilder devList = new StringBuilder(); + devList.append("| Device name | Access token | Owner |"); + devList.append(System.lineSeparator()); + devList.append("| :--- | :--- | :--- |"); + devList.append(System.lineSeparator()); + + for (DeviceCredentialsInfo credentialsInfo : ctx.getCreatedDevices().values()) { + devList.append("|").append(credentialsInfo.getName()) + .append("|").append(credentialsInfo.getCredentials().getCredentialsId()).append("{:copy-code}") + .append("|").append(credentialsInfo.getCustomerName() != null ? credentialsInfo.getCustomerName() : "Tenant"); + devList.append(System.lineSeparator()); + + template = template.replace("${" + credentialsInfo.getName() + "ACCESS_TOKEN}", credentialsInfo.getCredentials().getCredentialsId()); + } + + template = template.replace("${device_list_and_credentials}", devList.toString()); + + // User list (without user group column) + StringBuilder userList = new StringBuilder(); + userList.append("| Name | Login | Password | Customer name |"); + userList.append(System.lineSeparator()); + userList.append("| :--- | :--- | :--- | :--- |"); + userList.append(System.lineSeparator()); + + for (UserCredentialsInfo credentialsInfo : ctx.getCreatedUsers().values()) { + userList.append("|").append(credentialsInfo.getName()) + .append("|").append(credentialsInfo.getLogin()).append("{:copy-code}") + .append("|").append(credentialsInfo.getPassword()).append("{:copy-code}") + .append("|").append(credentialsInfo.getCustomerName() != null ? credentialsInfo.getCustomerName() : ""); + userList.append(System.lineSeparator()); + } + + template = template.replace("${user_list}", userList.toString()); + + // Edge detail URLs + for (Map.Entry edgeLinkInfoEntry : ctx.getCreatedEdges().entrySet()) { + EdgeLinkInfo edgeLinkInfo = edgeLinkInfoEntry.getValue(); + StringBuilder edgeDetailsUrl = new StringBuilder(); + if (EntityType.CUSTOMER.equals(edgeLinkInfo.getOwnerId().getEntityType())) { + edgeDetailsUrl.append("/customers/").append(edgeLinkInfo.getOwnerId().getId()); + edgeDetailsUrl.append("/edgeInstances/").append(edgeLinkInfo.getEdgeId().getId()); + } else { + edgeDetailsUrl.append("/edgeManagement/instances/").append(edgeLinkInfo.getEdgeId().getId()); + } + String edgeName = edgeLinkInfoEntry.getKey(); + String edgeDetailsPlaceholder = "${" + edgeName + "EDGE_DETAILS_URL}"; + template = template.replace(edgeDetailsPlaceholder, edgeDetailsUrl.toString()); + } + + template = replaceAlarmRules(ctx, template); + template = replaceCalculatedFields(ctx, template); + template = replaceCreatedEntities(ctx, template); + + return template; + } + + private static String replaceAlarmRules(SolutionInstallContext ctx, String template) { + StringBuilder alarmRules = new StringBuilder(); + + alarmRules.append("| Entity Profile Name | Alarm Type | Severities |").append(System.lineSeparator()); + alarmRules.append("| :--- | :--- | :--- |").append(System.lineSeparator()); + + ctx.getCreatedAlarmRules().entrySet().stream() + .sorted(Map.Entry.comparingByValue(Comparator.comparing(CreatedAlarmRuleInfo::entityName, String.CASE_INSENSITIVE_ORDER) + .thenComparing(CreatedAlarmRuleInfo::alarmType, String.CASE_INSENSITIVE_ORDER))) + .forEach(entry -> { + UUID key = entry.getKey(); + var alarmRuleInfo = entry.getValue(); + + String alarmType = alarmRuleInfo.alarmType(); + String link = alarmRuleInfo.getCfPageLink(key); + + String alarmTypeWithLink = "" + alarmType + ""; + + String profileName = alarmRuleInfo.entityId() != null ? + "" + alarmRuleInfo.entityName() + "" + : alarmRuleInfo.entityName(); + + alarmRules.append("|") + .append(profileName).append("|") + .append(alarmTypeWithLink).append("|") + .append(alarmRuleInfo.severities()).append("|") + .append(System.lineSeparator()); + }); + + return template.replace("${alarm_rules}", alarmRules.toString()); + } + + private static String replaceCalculatedFields(SolutionInstallContext ctx, String template) { + StringBuilder calculatedFields = new StringBuilder(); + + calculatedFields.append("| Entity Profile Name | Field Name | Field Type |").append(System.lineSeparator()); + calculatedFields.append("| :--- | :--- | :--- |").append(System.lineSeparator()); + + ctx.getCreatedCalculatedFields().entrySet().stream() + .sorted(Map.Entry.comparingByValue( + Comparator.comparing(CreatedCalculatedFieldInfo::entityName, String.CASE_INSENSITIVE_ORDER) + .thenComparing(CreatedCalculatedFieldInfo::name, String.CASE_INSENSITIVE_ORDER) + )) + .forEach(entry -> { + UUID key = entry.getKey(); + var cfInfo = entry.getValue(); + + String cfTitle = cfInfo.name(); + String link = cfInfo.getCfPageLink(key); + + String cfTitleWithLink = "" + cfTitle + ""; + + String profileName = cfInfo.entityId() != null ? + "" + cfInfo.entityName() + "" + : cfInfo.entityName(); + + calculatedFields.append("|") + .append(profileName).append("|") + .append(cfTitleWithLink).append("|") + .append(cfInfo.type()).append("|") + .append(System.lineSeparator()); + }); + + return template.replace("${calculated_fields}", calculatedFields.toString()); + } + + private static String replaceCreatedEntities(SolutionInstallContext ctx, String template) { + StringBuilder entityList = new StringBuilder(); + + entityList.append("| Name | Type | Owner |").append(System.lineSeparator()); + entityList.append("| :--- | :--- | :--- |").append(System.lineSeparator()); + + for (Map.Entry entry : ctx.getCreatedEntities().entrySet()) { + UUID key = entry.getKey(); + var entityInfo = entry.getValue(); + String link = entityInfo.getEntityPageLink(key); + String entityName = entityInfo.getName(); + + String name = link != null ? + "" + entityName + "" + : entityName; + + entityList.append("|") + .append(name).append("|") + .append(entityInfo.getType().getNormalName()).append("|") + .append(entityInfo.getOwner()).append("|") + .append(System.lineSeparator()); + } + return template.replace("${all_entities}", entityList.toString()); + } + + private RandomNameData generateRandomName(SolutionInstallContext ctx) { + int i = 0; + while (i < 10) { + var randomName = RandomNameUtil.next(); + var user = userService.findUserByEmail(ctx.getTenantId(), randomName.getEmail()); + if (user == null) { + return randomName; + } else { + i++; + } + } + String firstName = StringUtils.randomAlphanumeric(5); + String lastName = StringUtils.randomAlphanumeric(5); + return new RandomNameData(firstName, lastName, firstName + "." + lastName + "@thingsboard.io"); + } + + private String randomize(String src, RandomNameData name) { + return randomize(src, name, null); + } + + private String randomize(String src, RandomNameData name, RandomNameData customer) { + if (src == null) { + return null; + } else { + String result = src + .replace("$randomFirstName", name.getFirstName()) + .replace("$randomLastName", name.getLastName()) + .replace("$randomEmail", name.getEmail()); + if (customer != null) { + result = result + .replace("$customerFirstName", customer.getFirstName()) + .replace("$customerLastName", customer.getLastName()) + .replace("$customerEmail", customer.getEmail()); + } + return result.replace("$random", StringUtils.randomAlphanumeric(10).toLowerCase()); + } + } + + private void saveServerSideAttributes(SolutionInstallContext ctx, EntityId entityId, JsonNode attributes) { + saveServerSideAttributes(ctx, entityId, attributes, null); + } + + private void saveServerSideAttributes(SolutionInstallContext ctx, EntityId entityId, JsonNode attributes, RandomNameData randomNameData) { + saveAttributes(ctx, entityId, attributes, randomNameData, AttributeScope.SERVER_SCOPE); + } + + private void saveSharedAttributes(SolutionInstallContext ctx, EntityId entityId, JsonNode attributes) { + if (!EntityType.DEVICE.equals(entityId.getEntityType())) { + throw new IllegalArgumentException(entityId.getEntityType() + " cannot have shared attributes."); + } + saveAttributes(ctx, entityId, attributes, null, AttributeScope.SHARED_SCOPE); + } + + private void saveAttributes(SolutionInstallContext ctx, EntityId entityId, JsonNode attributes, RandomNameData randomNameData, AttributeScope attributeScope) { + if (attributes != null && !attributes.isNull() && !attributes.isEmpty()) { + attributes = prepareAttributes(attributes); + log.info("[{}] Saving attributes: {}", entityId, attributes); + if (randomNameData != null) { + attributes = JacksonUtil.toJsonNode(randomize(JacksonUtil.toString(attributes), randomNameData, null)); + } + attributesService.save(ctx.getTenantId(), entityId, attributeScope, + new ArrayList<>(JsonConverter.convertToAttributes(JsonParser.parseString(JacksonUtil.toString(attributes)), ctx.getOldestTelemetryTs()))); + } + } + + private JsonNode prepareAttributes(JsonNode attributes) { + ObjectNode attributesObj = (ObjectNode) attributes; + attributes.fields().forEachRemaining(entry -> { + JsonNode value = entry.getValue(); + if (value.isTextual() && isTimeExpression(value.asText())) { + value = JacksonUtil.toJsonNode(parseTimeExpression(value.asText())); + } + attributesObj.set(entry.getKey(), value); + }); + return attributesObj; + } + + private boolean isTimeExpression(String text) { + return Pattern.matches("\\$\\{currentTime(?:([+-])(\\d+)([mwdh]|min))?}", text); + } + + private String parseTimeExpression(String timeExpression) { + Matcher matcher = Pattern.compile("\\$\\{currentTime(?:([+-])(\\d+)([mwdh]|min))?}").matcher(timeExpression); + + if (!matcher.matches()) { + return timeExpression; + } + + String operator = matcher.group(1); + String amountStr = matcher.group(2); + String unit = matcher.group(3); + + ZonedDateTime now = ZonedDateTime.now(); + + if (operator != null && amountStr != null && unit != null) { + int amount = Integer.parseInt(amountStr); + now = switch (unit) { + case "m" -> operator.equals("+") ? now.plusMonths(amount) : now.minusMonths(amount); + case "w" -> operator.equals("+") ? now.plusWeeks(amount) : now.minusWeeks(amount); + case "d" -> operator.equals("+") ? now.plusDays(amount) : now.minusDays(amount); + case "h" -> operator.equals("+") ? now.plusHours(amount) : now.minusHours(amount); + case "min" -> operator.equals("+") ? now.plusMinutes(amount) : now.minusMinutes(amount); + default -> now; + }; + } + + return String.valueOf(now.toInstant().toEpochMilli()); + } + + private String getDashboardLink(TenantSolutionTemplateInstructions solutionInstructions, DashboardId dashboardId, boolean isPublic) { + if (isPublic && solutionInstructions.getPublicId() != null) { + return "/dashboard/" + dashboardId.getId() + "?publicId=" + solutionInstructions.getPublicId(); + } + return "/dashboards/" + dashboardId.getId(); + } + + private void rollback(TenantId tenantId, SolutionInstallContext ctx, Throwable e) { + List createdEntities = ctx.getCreatedEntitiesList(); + Collections.reverse(createdEntities); + for (EntityId entityId : createdEntities) { + try { + deleteEntity(tenantId, entityId, ctx.getUser()); + } catch (RuntimeException re) { + log.error("[{}] Failed to delete the entity: {}", tenantId, entityId, re); + } + } + ctx.getSolutionInstructions().setDetails(e.getMessage()); + } + + private void deleteEntity(TenantId tenantId, EntityId entityId, SecurityUser user) { + try { + List alarmIds = alarmService.findAlarms(tenantId, new AlarmQuery(entityId, new TimePageLink(Integer.MAX_VALUE), null, null, null, false)) + .getData().stream().map(AlarmInfo::getId).collect(Collectors.toList()); + Set typesToRemove = new HashSet<>(); + alarmIds.forEach(alarmId -> { + var result = alarmService.delAlarm(tenantId, alarmId, false); + if (result.isSuccessful()) { + typesToRemove.add(result.getAlarm().getType()); + } + }); + alarmService.delAlarmTypes(tenantId, typesToRemove); + } catch (Exception e) { + log.error("[{}] Failed to delete alarms for entity", entityId.getId(), e); + } + switch (entityId.getEntityType()) { + case CALCULATED_FIELD: + CalculatedField cf = calculatedFieldService.findById(tenantId, new CalculatedFieldId(entityId.getId())); + if (cf != null) { + tbCalculatedFieldService.delete(cf, user); + } + break; + case RULE_CHAIN: + ruleChainService.deleteRuleChainById(tenantId, new RuleChainId(entityId.getId())); + break; + case DEVICE: + Device device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); + if (device != null) { + tbDeviceService.delete(device, user); + } + break; + case DEVICE_PROFILE: + deviceProfileService.deleteDeviceProfile(tenantId, new DeviceProfileId(entityId.getId())); + break; + case ASSET: + Asset asset = assetService.findAssetById(tenantId, new AssetId(entityId.getId())); + if (asset != null) { + tbAssetService.delete(asset, user); + } + break; + case ASSET_PROFILE: + assetProfileService.deleteAssetProfile(tenantId, new AssetProfileId(entityId.getId())); + break; + case CUSTOMER: + customerService.deleteCustomer(tenantId, new CustomerId(entityId.getId())); + break; + case USER: + User userToDelete = userService.findUserById(tenantId, new UserId(entityId.getId())); + if (userToDelete != null) { + userService.deleteUser(tenantId, userToDelete); + } + break; + case EDGE: + Edge edge = edgeService.findEdgeById(tenantId, new EdgeId(entityId.getId())); + if (edge != null) { + tbEdgeService.delete(edge, user); + } + break; + case DASHBOARD: + dashboardService.deleteDashboard(tenantId, new DashboardId(entityId.getId())); + break; + default: + log.warn("[{}] Unsupported entity type for deletion: {}", tenantId, entityId.getEntityType()); + } + } + + private JsonNode replaceIds(SolutionInstallContext ctx, JsonNode json) { + String jsonStr = JacksonUtil.toString(json); + for (var e : ctx.getRealIds().entrySet()) { + jsonStr = jsonStr.replace(e.getKey(), e.getValue()); + } + return JacksonUtil.toJsonNode(jsonStr); + } + + private String readFileContent(Path path) { + try { + return Files.readString(path); + } catch (IOException e) { + log.warn("Failed to read file: {}", path, e); + return ""; + } + } + + private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { + Path filePath = tempDir.resolve("entities").resolve(fileName); + if (Files.exists(filePath)) { + return JacksonUtil.readValue(filePath.toFile(), clazz); + } else { + return null; + } + } + + private List loadListOfEntitiesIfFileExists(Path tempDir, String fileName, TypeReference> typeReference) { + Path filePath = tempDir.resolve("entities").resolve(fileName); + if (Files.exists(filePath)) { + try { + return JacksonUtil.readValue(filePath.toFile(), typeReference); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); + } + } else { + return new ArrayList<>(); + } + } + + private List loadListOfEntitiesFromDirectory(Path tempDir, String dirName, Class clazz) { + Path dirPath = tempDir.resolve(dirName); + if (Files.exists(dirPath) && Files.isDirectory(dirPath)) { + List result = new ArrayList<>(); + try { + for (Path filePath : Files.list(dirPath).collect(Collectors.toList())) { + try { + result.add(JacksonUtil.readValue(filePath.toFile(), clazz)); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid json file " + filePath.getFileName() + " data structure", e); + } + } + } catch (IOException e) { + log.warn("Failed to read directory: {}", dirName, e); + throw new RuntimeException(e); + } + return result; + } else { + return new ArrayList<>(); + } + } + + private static void extractZip(byte[] zipData, Path destDir) throws IOException { + try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipData))) { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + Path entryPath = destDir.resolve(entry.getName()).normalize(); + if (!entryPath.startsWith(destDir)) { + throw new IOException("ZIP entry outside of target directory: " + entry.getName()); + } + if (entry.isDirectory()) { + Files.createDirectories(entryPath); + } else { + Files.createDirectories(entryPath.getParent()); + Files.write(entryPath, zis.readAllBytes()); + } + zis.closeEntry(); + } + } + } + + private static void deleteDirectory(Path dir) { + try { + Files.walkFileTree(dir, new SimpleFileVisitor<>() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path d, IOException exc) throws IOException { + Files.delete(d); + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException e) { + log.warn("Failed to clean up temp directory: {}", dir, e); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/SolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/SolutionService.java new file mode 100644 index 0000000000..312376cc7c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/SolutionService.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2016-2026 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.solutions; + +import jakarta.servlet.http.HttpServletRequest; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; + +import java.util.List; + +public interface SolutionService { + + SolutionInstallResponse installSolution(SecurityUser user, TenantId tenantId, byte[] zipData, HttpServletRequest request) throws Exception; + + void deleteSolution(TenantId tenantId, List createdEntityIds, SecurityUser user); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedAlarmRuleInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedAlarmRuleInfo.java new file mode 100644 index 0000000000..90e5fc9f66 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedAlarmRuleInfo.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import org.thingsboard.server.common.data.id.EntityId; + +import java.util.UUID; + +public record CreatedAlarmRuleInfo(EntityId entityId, String entityName, String alarmType, String severities) { + + public String getCfPageLink(UUID cfId) { + return "/alarms/alarm-rules/" + cfId; + } + + public String getEntityPageLink() { + if (entityId == null) { + return null; + } + return switch (entityId.getEntityType()) { + case DEVICE_PROFILE -> "/profiles/deviceProfiles/" + entityId.getId(); + case ASSET_PROFILE -> "/profiles/assetProfiles/" + entityId.getId(); + default -> null; + }; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedCalculatedFieldInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedCalculatedFieldInfo.java new file mode 100644 index 0000000000..9616d738af --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedCalculatedFieldInfo.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import org.thingsboard.server.common.data.id.EntityId; + +import java.util.UUID; + +public record CreatedCalculatedFieldInfo(EntityId entityId, String entityName, String type, String name) { + + public String getCfPageLink(UUID cfId) { + return "/calculatedFields/" + cfId; + } + + public String getEntityPageLink() { + if (entityId == null) { + return null; + } + return switch (entityId.getEntityType()) { + case DEVICE_PROFILE -> "/profiles/deviceProfiles/" + entityId.getId(); + case ASSET_PROFILE -> "/profiles/assetProfiles/" + entityId.getId(); + default -> null; + }; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedEntityInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedEntityInfo.java new file mode 100644 index 0000000000..53105a6e31 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/CreatedEntityInfo.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +import java.util.UUID; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class CreatedEntityInfo { + + private String name; + private EntityType type; + private String owner; + + public String getEntityPageLink(UUID id) { + return switch (type) { + case CUSTOMER -> "/customers/" + id; + case USER -> "/users/" + id; + case ASSET -> "/entities/assets/" + id; + case DEVICE -> "/entities/devices/" + id; + case DEVICE_PROFILE -> "/profiles/deviceProfiles/" + id; + case ASSET_PROFILE -> "/profiles/assetProfiles/" + id; + case DASHBOARD -> "/dashboards/" + id; + case RULE_CHAIN -> "/ruleChains/" + id; + case EDGE -> "/edgeManagement/instances/" + id; + default -> null; + }; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/DashboardLinkInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/DashboardLinkInfo.java new file mode 100644 index 0000000000..63eb0e3757 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/DashboardLinkInfo.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.Data; +import org.thingsboard.server.common.data.id.DashboardId; + +@Data +public class DashboardLinkInfo { + + private final String name; + private final DashboardId dashboardId; + private final boolean isPublic; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/DeviceCredentialsInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/DeviceCredentialsInfo.java new file mode 100644 index 0000000000..e93104729c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/DeviceCredentialsInfo.java @@ -0,0 +1,30 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.Data; +import org.thingsboard.server.common.data.security.DeviceCredentials; + +@Data +public class DeviceCredentialsInfo { + + String name; + String type; + DeviceCredentials credentials; + String customerName; + boolean gateway; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/EdgeLinkInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/EdgeLinkInfo.java new file mode 100644 index 0000000000..e5f057636d --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/EdgeLinkInfo.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.Data; +import org.thingsboard.server.common.data.id.EdgeId; +import org.thingsboard.server.common.data.id.EntityId; + +@Data +public class EdgeLinkInfo { + + private final EdgeId edgeId; + private final EntityId ownerId; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionInstallContext.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionInstallContext.java new file mode 100644 index 0000000000..6ba950571c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionInstallContext.java @@ -0,0 +1,208 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.Data; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.Dashboard; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.cf.CalculatedField; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; +import org.thingsboard.server.service.solutions.data.definition.AssetProfileDefinition; +import org.thingsboard.server.service.solutions.data.definition.CustomerDefinition; +import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; +import org.thingsboard.server.service.solutions.data.definition.DeviceDefinition; +import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntitySearchKey; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; +import org.thingsboard.server.service.solutions.data.solution.TenantSolutionTemplateInstructions; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +@Data +public class SolutionInstallContext { + + private final TenantId tenantId; + private final Path tempDir; + private final SecurityUser user; + private final TenantSolutionTemplateInstructions solutionInstructions; + private final List createdEntitiesList = new ArrayList<>(); + private final Map realIds = new HashMap<>(); + private final Map entityIdMap = new HashMap<>(); + private final Map> relationDefinitions = new LinkedHashMap<>(); + private final List dashboardLinks = new ArrayList<>(); + + // For instructions + private final Map createdDevices = new LinkedHashMap<>(); + private final Map createdUsers = new LinkedHashMap<>(); + private final Map createdEdges = new LinkedHashMap<>(); + private final Map createdEntities = new LinkedHashMap<>(); + private final Map createdAlarmRules = new LinkedHashMap<>(); + private final Map createdCalculatedFields = new LinkedHashMap<>(); + private final long installTs; + private long oldestTelemetryTs; + private Map deviceEmulators; + private Map assetEmulators; + + public SolutionInstallContext(TenantId tenantId, Path tempDir, SecurityUser user) { + this.tenantId = tenantId; + this.tempDir = tempDir; + this.user = user; + this.solutionInstructions = new TenantSolutionTemplateInstructions(); + this.installTs = System.currentTimeMillis(); + put(new EntitySearchKey(tenantId, EntityType.TENANT, null), tenantId); + } + + public void registerReferenceOnly(String referenceId, EntityId entityId) { + if (!StringUtils.isEmpty(referenceId)) { + realIds.put(referenceId, entityId.getId().toString()); + } + } + + public void register(String referenceId, EntityId entityId) { + registerReferenceOnly(referenceId, entityId); + register(entityId); + } + + public void register(EntityId entityId) { + createdEntitiesList.add(entityId); + } + + public void register(String referenceId, RuleChain ruleChain) { + register(referenceId, ruleChain.getId()); + createdEntities.put(ruleChain.getUuidId(), new CreatedEntityInfo(ruleChain.getName(), EntityType.RULE_CHAIN, "Tenant")); + } + + public void register(DeviceProfileDefinition definition, DeviceProfile deviceProfile) { + register(definition.getJsonId(), deviceProfile.getId()); + createdEntities.put(deviceProfile.getUuidId(), new CreatedEntityInfo(deviceProfile.getName(), EntityType.DEVICE_PROFILE, "Tenant")); + } + + public void register(AssetProfileDefinition definition, AssetProfile assetProfile) { + register(definition.getJsonId(), assetProfile.getId()); + createdEntities.put(assetProfile.getUuidId(), new CreatedEntityInfo(assetProfile.getName(), EntityType.ASSET_PROFILE, "Tenant")); + } + + public void register(AssetDefinition definition, Asset asset) { + register(definition.getJsonId(), asset.getId()); + createdEntities.put(asset.getUuidId(), new CreatedEntityInfo(asset.getName(), EntityType.ASSET, + StringUtils.isEmpty(definition.getCustomer()) ? "Tenant" : definition.getCustomer())); + } + + public void register(DeviceDefinition definition, Device device) { + register(definition.getJsonId(), device.getId()); + createdEntities.put(device.getUuidId(), new CreatedEntityInfo(device.getName(), EntityType.DEVICE, + StringUtils.isEmpty(definition.getCustomer()) ? "Tenant" : definition.getCustomer())); + } + + public void register(CustomerDefinition definition, Customer customer) { + register(definition.getJsonId(), customer.getId()); + createdEntities.put(customer.getUuidId(), new CreatedEntityInfo(customer.getName(), EntityType.CUSTOMER, "Tenant")); + } + + public void register(CustomerDefinition customerDef, User user) { + register((String) null, user.getId()); + createdEntities.put(user.getUuidId(), new CreatedEntityInfo(user.getName(), EntityType.USER, + StringUtils.isEmpty(customerDef.getName()) ? "Tenant" : customerDef.getName())); + } + + public void register(EdgeDefinition definition, Edge edge) { + register(definition.getJsonId(), edge.getId()); + createdEntities.put(edge.getUuidId(), new CreatedEntityInfo(edge.getName(), EntityType.EDGE, + StringUtils.isEmpty(definition.getCustomer()) ? "Tenant" : definition.getCustomer())); + } + + public void register(DashboardDefinition definition, Dashboard dashboard) { + register(definition.getJsonId(), dashboard.getId()); + createdEntities.put(dashboard.getUuidId(), new CreatedEntityInfo(dashboard.getTitle(), EntityType.DASHBOARD, + StringUtils.isEmpty(definition.getCustomer()) ? "Tenant" : definition.getCustomer())); + } + + public void register(CalculatedField calculatedField) { + register(calculatedField.getId()); + EntityId entityId = calculatedField.getEntityId(); + CreatedEntityInfo entityInfo = createdEntities.get(entityId.getId()); + boolean alarmRule = false; // TODO: CE doesn't have ALARM calculated field type yet + if (entityInfo == null) { + String target = alarmRule ? "Alarm rule" : "Calculated field"; + throw new IllegalStateException("Failed to register " + target + " with name: " + + calculatedField.getName() + " for non-existing entity with id: " + entityId); + } + if (alarmRule) { + createdAlarmRules.put(calculatedField.getUuidId(), new CreatedAlarmRuleInfo(entityId, entityInfo.getName(), calculatedField.getName(), null)); + return; + } + createdCalculatedFields.put(calculatedField.getUuidId(), new CreatedCalculatedFieldInfo(entityId, entityInfo.getName(), calculatedField.getType().name(), calculatedField.getName())); + } + + public void putIdToMap(EntityDefinition entityDefinition, EntityId entityId) { + putIdToMap(entityDefinition.getEntityType(), entityDefinition.getName(), entityId); + } + + public void putIdToMap(EntityType entityType, String entityName, EntityId entityId) { + putIdToMap(tenantId, entityType, entityName, entityId); + } + + public void putIdToMap(EntityId ownerId, EntityType entityType, String entityName, EntityId entityId) { + put(new EntitySearchKey(ownerId, entityType, entityName), entityId); + } + + public void put(EntitySearchKey entitySearchKey, EntityId entityId) { + entityIdMap.put(entitySearchKey, entityId); + } + + @SuppressWarnings("unchecked") + public T getIdFromMap(EntityType entityType, String entityName) { + return (T) entityIdMap.get(new EntitySearchKey(tenantId, entityType, entityName)); + } + + public void put(EntityId entityId, List relations) { + relationDefinitions.put(entityId, relations); + } + + public void addDeviceCredentials(DeviceCredentialsInfo deviceCredentialsInfo) { + createdDevices.put(deviceCredentialsInfo.getName(), deviceCredentialsInfo); + } + + public void addUserCredentials(UserCredentialsInfo userCredentialsInfo) { + createdUsers.put(userCredentialsInfo.getName(), userCredentialsInfo); + } + + public void addEdgeLinkInfo(String edgeName, EdgeLinkInfo edgeLinkInfo) { + createdEdges.put(edgeName, edgeLinkInfo); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/UserCredentialsInfo.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/UserCredentialsInfo.java new file mode 100644 index 0000000000..d35900c5b4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/UserCredentialsInfo.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data; + +import lombok.Data; + +@Data +public class UserCredentialsInfo { + + String name; + String login; + String password; + String customerName; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetDefinition.java new file mode 100644 index 0000000000..2554dbafb0 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetDefinition.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@AllArgsConstructor +public class AssetDefinition extends CustomerEntityDefinition { + + private String type; + private String label; + private String emulator; + + @Override + public EntityType getEntityType() { + return EntityType.ASSET; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetProfileDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetProfileDefinition.java new file mode 100644 index 0000000000..9f95294fa7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/AssetProfileDefinition.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.thingsboard.server.common.data.asset.AssetProfile; + +@Data +@EqualsAndHashCode(callSuper = true) +public class AssetProfileDefinition extends AssetProfile { + + private String jsonId; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/BaseEntityDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/BaseEntityDefinition.java new file mode 100644 index 0000000000..84ec880380 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/BaseEntityDefinition.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Collections; +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public abstract class BaseEntityDefinition implements EntityDefinition { + + @JsonProperty("name") + private String name; + @JsonProperty("attributes") + private JsonNode attributes; + @JsonProperty("sharedAttributes") + private JsonNode sharedAttributes; + @JsonProperty("relations") + private List relations = Collections.emptyList(); + @JsonProperty("jsonId") + private String jsonId; + + public void setRelations(List relations) { + if (relations != null) { + this.relations = relations; + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CalculatedFieldDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CalculatedFieldDefinition.java new file mode 100644 index 0000000000..1dcc7a6bbd --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CalculatedFieldDefinition.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.thingsboard.server.common.data.cf.CalculatedField; + +@Data +@EqualsAndHashCode(callSuper = true) +public class CalculatedFieldDefinition extends CalculatedField { + + private Integer reprocessingOrder; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerDefinition.java new file mode 100644 index 0000000000..3cc40c658c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerDefinition.java @@ -0,0 +1,55 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.service.solutions.data.names.RandomNameData; + +import java.util.Collections; +import java.util.List; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +public class CustomerDefinition extends BaseEntityDefinition { + + private String email; + private String country; + private String city; + private String state; + private String zip; + private String address; + private List users = Collections.emptyList(); + + @JsonIgnore + private RandomNameData randomNameData; + + @Override + public EntityType getEntityType() { + return EntityType.CUSTOMER; + } + + public void setUsers(List users) { + if (users != null) { + this.users = users; + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerEntityDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerEntityDefinition.java new file mode 100644 index 0000000000..d2da2f266c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/CustomerEntityDefinition.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +public abstract class CustomerEntityDefinition extends BaseEntityDefinition { + + private String customer; + private boolean makePublic; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardDefinition.java new file mode 100644 index 0000000000..a5a9e9c22b --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardDefinition.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@AllArgsConstructor +public class DashboardDefinition extends CustomerEntityDefinition { + + private String file; + private boolean main; + + @Override + public EntityType getEntityType() { + return EntityType.DASHBOARD; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardUserDetailsDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardUserDetailsDefinition.java new file mode 100644 index 0000000000..2ec4701829 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DashboardUserDetailsDefinition.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; + +@Data +public class DashboardUserDetailsDefinition { + + private String name; + private boolean fullScreen; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceDefinition.java new file mode 100644 index 0000000000..81239c46dd --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceDefinition.java @@ -0,0 +1,41 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@AllArgsConstructor +public class DeviceDefinition extends CustomerEntityDefinition { + + private String type; + private String label; + private String emulator; + private JsonNode additionalInfo; + + @Override + public EntityType getEntityType() { + return EntityType.DEVICE; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceProfileDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceProfileDefinition.java new file mode 100644 index 0000000000..3dee5c179a --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/DeviceProfileDefinition.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.thingsboard.server.common.data.DeviceProfile; + +@Data +@EqualsAndHashCode(callSuper = true) +public class DeviceProfileDefinition extends DeviceProfile { + + private String jsonId; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EdgeDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EdgeDefinition.java new file mode 100644 index 0000000000..33034c93e9 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EdgeDefinition.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +import java.util.Collections; +import java.util.List; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@AllArgsConstructor +public class EdgeDefinition extends CustomerEntityDefinition { + + private String type; + private String label; + private String rootRuleChainId; + private List ruleChainIds = Collections.emptyList(); + private List deviceIds = Collections.emptyList(); + private List assetIds = Collections.emptyList(); + + @Override + public EntityType getEntityType() { + return EntityType.EDGE; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EmulatorDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EmulatorDefinition.java new file mode 100644 index 0000000000..37c726e091 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EmulatorDefinition.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import org.thingsboard.server.common.data.StringUtils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Data +public class EmulatorDefinition { + private String name; + private String extendz; + private String clazz; + private int publishPeriodInDays; + private int publishFrequencyInSeconds; + private int publishPauseInMillis; + private long activityPeriodInMillis; + private List telemetryProfiles = Collections.emptyList(); + + public void enrich(EmulatorDefinition parent) { + if (StringUtils.isEmpty(clazz)) { + clazz = parent.getClazz(); + } + if (publishPeriodInDays == 0) { + publishPeriodInDays = parent.getPublishPeriodInDays(); + } + if (publishFrequencyInSeconds == 0) { + publishFrequencyInSeconds = parent.getPublishFrequencyInSeconds(); + } + if (publishPauseInMillis == 0) { + publishPauseInMillis = parent.getPublishPauseInMillis(); + } + if (activityPeriodInMillis == 0L) { + activityPeriodInMillis = parent.getActivityPeriodInMillis(); + } + var profilesMap = telemetryProfiles.stream().collect(Collectors.toMap(TelemetryProfile::getKey, Function.identity())); + parent.getTelemetryProfiles().forEach(tp -> profilesMap.putIfAbsent(tp.getKey(), tp)); + telemetryProfiles = new ArrayList<>(profilesMap.values()); + } + + public long getOldestTs(long startTs) { + return startTs - TimeUnit.DAYS.toMillis(publishPeriodInDays) - publishFrequencyInSeconds; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntityDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntityDefinition.java new file mode 100644 index 0000000000..c76d183bda --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntityDefinition.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import org.thingsboard.server.common.data.EntityType; + +public interface EntityDefinition { + + String getName(); + + EntityType getEntityType(); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntitySearchKey.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntitySearchKey.java new file mode 100644 index 0000000000..f880e909b0 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/EntitySearchKey.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.id.EntityId; + +@Data +@AllArgsConstructor +public class EntitySearchKey { + + private final EntityId ownerId; + private final EntityType entityType; + private final String entityName; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/ReferenceableEntityDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/ReferenceableEntityDefinition.java new file mode 100644 index 0000000000..13dabb08cc --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/ReferenceableEntityDefinition.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class ReferenceableEntityDefinition { + + private String name; + private String file; + private String update; + private String jsonId; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/RelationDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/RelationDefinition.java new file mode 100644 index 0000000000..670d3f1ab4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/RelationDefinition.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.relation.EntitySearchDirection; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class RelationDefinition { + + private EntityType entityType; + private String entityName; + private EntitySearchDirection direction; + private String type; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TelemetryProfile.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TelemetryProfile.java new file mode 100644 index 0000000000..259744a2f0 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TelemetryProfile.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.thingsboard.server.service.solutions.data.values.ValueStrategyDefinition; + +@Data +@AllArgsConstructor +public class TelemetryProfile { + + private String key; + private ValueStrategyDefinition valueStrategy; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TenantDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TenantDefinition.java new file mode 100644 index 0000000000..957547cff6 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/TenantDefinition.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.Data; +import org.thingsboard.server.common.data.EntityType; + +@Data +public class TenantDefinition extends BaseEntityDefinition { + + @Override + public EntityType getEntityType() { + return EntityType.TENANT; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/UserDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/UserDefinition.java new file mode 100644 index 0000000000..1815cc6e57 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/definition/UserDefinition.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2026 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.solutions.data.definition; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.EntityType; + +@Data +@EqualsAndHashCode(callSuper = true) +@NoArgsConstructor +@AllArgsConstructor +public class UserDefinition extends BaseEntityDefinition { + + private String firstname; + private String lastname; + private String password; + private DashboardUserDetailsDefinition dashboard; + + @Override + public EntityType getEntityType() { + return EntityType.USER; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AbstractEmulatorLauncher.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AbstractEmulatorLauncher.java new file mode 100644 index 0000000000..abed74af3e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AbstractEmulatorLauncher.java @@ -0,0 +1,195 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.util.Pair; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.HasTenantId; +import org.thingsboard.server.common.data.StringUtils; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.HasId; +import org.thingsboard.server.common.data.msg.TbMsgType; +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.TbQueueCallback; +import org.thingsboard.server.queue.TbQueueMsgMetadata; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.queue.provider.TbQueueProducerProvider; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Data +public abstract class AbstractEmulatorLauncher & HasTenantId & HasName> { + + protected static final TbQueueCallback EMPTY_CALLBACK = new TbQueueCallback() { + @Override + public void onSuccess(TbQueueMsgMetadata metadata) { + + } + + @Override + public void onFailure(Throwable t) { + + } + }; + protected final T entity; + protected final EmulatorDefinition emulatorDefinition; + protected final ExecutorService oldTelemetryExecutor; + protected final TbClusterService tbClusterService; + protected final PartitionService partitionService; + protected final TbQueueProducerProvider tbQueueProducerProvider; + protected final TbServiceInfoProvider serviceInfoProvider; + protected final TelemetrySubscriptionService tsSubService; + protected final long publishFrequency; + + private final Emulator emulator; + private ScheduledFuture scheduledFuture; + + public AbstractEmulatorLauncher(T entity, + EmulatorDefinition emulatorDefinition, + ExecutorService oldTelemetryExecutor, + TbClusterService tbClusterService, + PartitionService partitionService, + TbQueueProducerProvider tbQueueProducerProvider, + TbServiceInfoProvider serviceInfoProvider, + TelemetrySubscriptionService tsSubService) throws Exception { + this.entity = entity; + this.emulatorDefinition = emulatorDefinition; + this.oldTelemetryExecutor = oldTelemetryExecutor; + this.tbClusterService = tbClusterService; + this.partitionService = partitionService; + this.tbQueueProducerProvider = tbQueueProducerProvider; + this.serviceInfoProvider = serviceInfoProvider; + this.tsSubService = tsSubService; + this.publishFrequency = TimeUnit.SECONDS.toMillis(Math.max(emulatorDefinition.getPublishFrequencyInSeconds(), 1)); + if (StringUtils.isEmpty(emulatorDefinition.getClazz())) { + emulator = new BasicEmulator(); + } else { + emulator = (Emulator) Class.forName(emulatorDefinition.getClazz()).getDeclaredConstructor().newInstance(); + } + emulator.init(emulatorDefinition); + } + + public CompletableFuture launch() { + final long oldestTs = emulatorDefinition.getOldestTs(System.currentTimeMillis()); + CompletableFuture future = new CompletableFuture<>(); + oldTelemetryExecutor.submit(() -> { + AtomicInteger pending = new AtomicInteger(1); + try { + if (emulator instanceof SimpleEmulator) { + if (oldestTs < (System.currentTimeMillis() - publishFrequency)) { + pushOldTelemetry(oldestTs, pending, future); + } + } else if (emulator instanceof CustomEmulator customEmulator) { + Pair telemetry = customEmulator.getNextValue(); + while (telemetry != null) { + pending.incrementAndGet(); + publishTelemetry(telemetry.getFirst(), telemetry.getSecond(), pending, future); + telemetry = customEmulator.getNextValue(); + } + } + } catch (Exception e) { + log.warn("Telemetry upload failed for {}", entity.getName(), e); + future.completeExceptionally(e); + } finally { + if (pending.decrementAndGet() == 0 && !future.isDone()) { + log.trace("[{}] Telemetry emulation finished. Producer and all callbacks completed successfully", entity.getName()); + future.complete(null); + } + } + + future.whenComplete((v, t) -> { + try { + postProcessEntity(entity); + } catch (Exception e) { + log.warn("Post-processing failed for {}", entity.getName(), e); + } + }); + + }); + return future; + } + + protected void postProcessEntity(T entity) { + } + + private void pushOldTelemetry(long oldestTs, AtomicInteger pending, CompletableFuture future) throws InterruptedException { + for (long ts = oldestTs; ts < System.currentTimeMillis(); ts += publishFrequency) { + pending.incrementAndGet(); + publishTelemetry(ts, pending, future); + } + } + + private void publishTelemetry(long ts, AtomicInteger pending, CompletableFuture future) throws InterruptedException { + ObjectNode values = ((SimpleEmulator) emulator).getValue(ts); + publishTelemetry(ts, values, pending, future); + Thread.sleep(emulatorDefinition.getPublishPauseInMillis()); + } + + public void stop() { + scheduledFuture.cancel(true); + } + + private void publishTelemetry(long ts, ObjectNode value, AtomicInteger pending, CompletableFuture future) { + String msgData = JacksonUtil.toString(value); + log.debug("[{}] Publishing telemetry: {}", entity.getName(), msgData); + TbMsgMetaData md = new TbMsgMetaData(); + md.putValue("ts", Long.toString(ts)); + TbMsg tbMsg = TbMsg.newMsg() + .type(TbMsgType.POST_TELEMETRY_REQUEST) + .originator(entity.getId()) + .copyMetaData(md) + .dataType(TbMsgDataType.JSON) + .data(msgData) + .build(); + + TbQueueCallback callback = new TbQueueCallback() { + + @Override + public void onSuccess(TbQueueMsgMetadata metadata) { + log.debug("[{}] Successfully pushed message to Rule Engine for ts {}", entity.getName(), ts); + if (pending.decrementAndGet() == 0 && !future.isDone()) { + log.trace("[{}] Completing emulation future from callback for msg with ts: {}", entity.getName(), ts); + future.complete(null); + } + } + + @Override + public void onFailure(Throwable t) { + log.warn("[{}] Telemetry upload failed for ts {}", entity.getName(), ts, t); + if (pending.decrementAndGet() == 0 && !future.isDone()) { + future.completeExceptionally(t); + } + } + }; + + tbClusterService.pushMsgToRuleEngine(entity.getTenantId(), entity.getId(), tbMsg, callback); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AssetEmulatorLauncher.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AssetEmulatorLauncher.java new file mode 100644 index 0000000000..1f2d144b99 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/AssetEmulatorLauncher.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import lombok.Builder; +import lombok.extern.slf4j.Slf4j; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.queue.provider.TbQueueProducerProvider; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.concurrent.ExecutorService; + +@Slf4j +public class AssetEmulatorLauncher extends AbstractEmulatorLauncher { + + @Builder + public AssetEmulatorLauncher(Asset entity, EmulatorDefinition emulatorDefinition, ExecutorService oldTelemetryExecutor, TbClusterService tbClusterService, + PartitionService partitionService, + TbQueueProducerProvider tbQueueProducerProvider, + TbServiceInfoProvider serviceInfoProvider, + TelemetrySubscriptionService tsSubService) throws Exception { + super(entity, emulatorDefinition, oldTelemetryExecutor, tbClusterService, partitionService, tbQueueProducerProvider, serviceInfoProvider, tsSubService); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/BasicEmulator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/BasicEmulator.java new file mode 100644 index 0000000000..c81aed3c02 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/BasicEmulator.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.solutions.data.values.TelemetryGenerator; +import org.thingsboard.server.service.solutions.data.values.TelemetryGeneratorFactory; + +import java.util.HashMap; +import java.util.Map; + +public class BasicEmulator implements SimpleEmulator { + + private final Map tsGenerators = new HashMap<>(); + + @Override + public void init(EmulatorDefinition emulatorDefinition) { + emulatorDefinition.getTelemetryProfiles().forEach(tp -> tsGenerators.put(tp.getKey(), TelemetryGeneratorFactory.create(tp))); + } + + @Override + public ObjectNode getValue(long ts) { + ObjectNode values = JacksonUtil.newObjectNode(); + tsGenerators.values().forEach(gen -> gen.addValue(ts, values)); + return values; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/CustomEmulator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/CustomEmulator.java new file mode 100644 index 0000000000..627fe4e94d --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/CustomEmulator.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.data.util.Pair; + +public interface CustomEmulator extends Emulator { + + Pair getNextValue(); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/DeviceEmulatorLauncher.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/DeviceEmulatorLauncher.java new file mode 100644 index 0000000000..62fe03aa31 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/DeviceEmulatorLauncher.java @@ -0,0 +1,98 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.google.common.util.concurrent.FutureCallback; +import lombok.Builder; +import lombok.extern.slf4j.Slf4j; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.thingsboard.rule.engine.api.AttributesSaveRequest; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.kv.LongDataEntry; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.queue.common.TbProtoQueueMsg; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; +import org.thingsboard.server.queue.provider.TbQueueProducerProvider; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; +import org.thingsboard.server.service.state.DefaultDeviceStateService; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.UUID; +import java.util.concurrent.ExecutorService; + +@Slf4j +public class DeviceEmulatorLauncher extends AbstractEmulatorLauncher { + + @Builder + public DeviceEmulatorLauncher(Device entity, + EmulatorDefinition emulatorDefinition, + ExecutorService oldTelemetryExecutor, + TbClusterService tbClusterService, + PartitionService partitionService, + TbQueueProducerProvider tbQueueProducerProvider, + TbServiceInfoProvider serviceInfoProvider, + TelemetrySubscriptionService tsSubService) throws Exception { + super(entity, emulatorDefinition, oldTelemetryExecutor, tbClusterService, partitionService, tbQueueProducerProvider, serviceInfoProvider, tsSubService); + } + + @Override + protected void postProcessEntity(Device entity) { + if (this.emulatorDefinition.getActivityPeriodInMillis() > 0) { + tsSubService.saveAttributes(AttributesSaveRequest.builder() + .tenantId(entity.getTenantId()) + .entityId(entity.getId()) + .scope(AttributeScope.SERVER_SCOPE) + .entry(new LongDataEntry(DefaultDeviceStateService.INACTIVITY_TIMEOUT, this.emulatorDefinition.getActivityPeriodInMillis())) + .callback(new FutureCallback<>() { + @Override + public void onSuccess(@Nullable Void unused) { + TopicPartitionInfo tpi = partitionService.resolve(ServiceType.TB_CORE, entity.getTenantId(), entity.getId()); + UUID sessionId = UUID.randomUUID(); + TransportProtos.TransportToDeviceActorMsg msg = TransportProtos.TransportToDeviceActorMsg.newBuilder() + .setSessionInfo(TransportProtos.SessionInfoProto.newBuilder() + .setSessionIdMSB(sessionId.getMostSignificantBits()) + .setSessionIdLSB(sessionId.getLeastSignificantBits()) + .setDeviceIdMSB(entity.getId().getId().getMostSignificantBits()) + .setDeviceIdLSB(entity.getId().getId().getLeastSignificantBits()) + .setDeviceProfileIdMSB(entity.getId().getId().getMostSignificantBits()) + .setDeviceProfileIdLSB(entity.getId().getId().getLeastSignificantBits()) + .setDeviceName(entity.getName()) + .setDeviceType(entity.getType()) + .setTenantIdMSB(entity.getTenantId().getId().getMostSignificantBits()) + .setTenantIdLSB(entity.getTenantId().getId().getLeastSignificantBits()) + .setNodeId(serviceInfoProvider.getServiceId()) + .build()) + .setSubscriptionInfo(TransportProtos.SubscriptionInfoProto.newBuilder().setLastActivityTime(System.currentTimeMillis()).build()) + .build(); + tbQueueProducerProvider.getTbCoreMsgProducer().send(tpi, + new TbProtoQueueMsg<>(entity.getUuidId(), + TransportProtos.ToCoreMsg.newBuilder().setToDeviceActorMsg(msg).build()), EMPTY_CALLBACK + ); + } + + @Override + public void onFailure(Throwable throwable) { + } + }) + .build()); + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/Emulator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/Emulator.java new file mode 100644 index 0000000000..45a9a029b8 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/Emulator.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; + +public interface Emulator { + + void init(EmulatorDefinition emulatorDefinition); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/FieldIrrigationStateEmulator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/FieldIrrigationStateEmulator.java new file mode 100644 index 0000000000..44c9eb550f --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/FieldIrrigationStateEmulator.java @@ -0,0 +1,108 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.data.util.Pair; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.service.solutions.data.definition.EmulatorDefinition; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.TimeZone; + +public class FieldIrrigationStateEmulator implements CustomEmulator { + + private static final int START_HOUR = 6; + private int idx; + private List> data = new ArrayList<>(); + + @Override + public void init(EmulatorDefinition emulatorDefinition) { + idx = 0; + var tz = TimeZone.getTimeZone("America/New_York"); + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(System.currentTimeMillis()); + c.setTimeZone(tz); + int curHour = c.get(Calendar.HOUR_OF_DAY); + c.add(Calendar.DAY_OF_MONTH, curHour < START_HOUR ? -7 : -6); + c.set(Calendar.HOUR_OF_DAY, START_HOUR); + c.set(Calendar.MINUTE, 0); + + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("durationThreshold", 30 * 60000) + .put("consumption", 423) + .put("duration", 30 * 60000) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("durationThreshold", 30 * 60000) + .put("consumption", 407) + .put("duration", 30 * 60000) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("consumptionThreshold", 1000) + .put("consumption", 1000) + .put("duration", 63 * 60000) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("consumptionThreshold", 500) + .put("consumption", 500) + .put("duration", 36 * 60000) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("consumptionThreshold", 1000) + .put("consumption", 1000) + .put("duration", 63 * 60000) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("durationThreshold", 30 * 60000) + .put("duration", 30 * 60000) + .put("consumption", 452) + ); + add(c, JacksonUtil.newObjectNode() + .put("startTs", c.getTimeInMillis()) + .put("durationThreshold", 30 * 60000) + .put("duration", 30 * 60000) + .put("consumption", 447) + ); + } + + private void add(Calendar c, ObjectNode objectNode) { + ObjectNode startIrrigationMsg = JacksonUtil.newObjectNode(); + startIrrigationMsg.put("irrigationState", "DONE"); + startIrrigationMsg.set("irrigationTask", objectNode); + data.add(Pair.of(c.getTimeInMillis(), startIrrigationMsg)); + c.add(Calendar.DAY_OF_MONTH, 1); + } + + @Override + public Pair getNextValue() { + if (idx < data.size()) { + var result = data.get(idx); + idx++; + return result; + } else { + return null; + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/SimpleEmulator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/SimpleEmulator.java new file mode 100644 index 0000000000..144a5f7f26 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/emulator/SimpleEmulator.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2016-2026 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.solutions.data.emulator; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +public interface SimpleEmulator extends Emulator { + + ObjectNode getValue(long ts); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameData.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameData.java new file mode 100644 index 0000000000..ca66c37199 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameData.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2016-2026 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.solutions.data.names; + +import lombok.Data; + +@Data +public class RandomNameData { + + private final String firstName; + private final String lastName; + private final String email; +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameUtil.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameUtil.java new file mode 100644 index 0000000000..50bc3b9dc5 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/names/RandomNameUtil.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2016-2026 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.solutions.data.names; + +import org.thingsboard.server.common.data.StringUtils; + +import java.util.Random; + +public class RandomNameUtil { + + private static final Random RANDOM = new Random(System.currentTimeMillis()); + + private static String[] FIRST_NAMES = new String[]{ + "Nadia", "Lynne", "Lera", "Holly", "Zina", "Mandi", "Kasie", "Josef", "Liane", "Man", + "Karan", "Nga", "Tesha", "Elva", "Bree", "Ida", "Mimi", "Altha", "Omar", "Ollie", + "Nicol", "Ned", "Teri", "Sabra", "Kari", "Eva", "Penni", "Simon", "Kaci", "Jess", + "Bea", "Ron", "Melba", "Vella", "Nada", "Cyndi", "Audry", "Helga", "Chana", "Lola", + "Terry", "Tami", "Dedra", "Erwin", "Anne", "Zoila", "Nelia", "Hyman", "Deane", "Erica", + "Amos", "Maura", "Gwenn", "Evan", "Lelia", "Grant", "Abe", "Fanny", "Cindi", "Pilar", + "Darcy", "Len", "Casie", "Jose", "Kylie", "Cami", "Casey", "Kerri", "Bruno", "Theda", + "Ardis", "Carin", "Belia", "Jeff", "Yetta", "Ola", "Lyla", "Megan", "Zita", "Rocky", + "Darci", "Dale", "Mirta", "Tanja", "Stacy", "Julie", "Aisha", "Avis", "Hugh", "Anh", + "Bud", "Earle", "Ossie", "Odell", "Dovie", "Afton", "Joel", "Aida", "Vina", "Emiko", + "Tori", "Keena", "Addie", "Nancy", "Tonda", "Josue", "Dina", "Mitch", "Thea", "Cole", + "Lyman", "Donna", "Roma", "Deena", "Lue", "Bette", "Ilene", "Vera", "Kirby", "Lenna", + "Pat", "Grace", "Gus", "Frank", "Lena", "Adele", "Kerry", "Santo", "Wade", "Trudi", + "Bruce", "Raul", "Katy", "Heidi", "Marna", "Faith", "Ronna", "Kylee", "Emma", "Luna", + "Ilda", "Mose", "Juan", "Cori", "Gayla", "Otha", "Jung", "Bambi", "Joi", "Sibyl", + "Reid", "Bonny", "Roni", "Joy", "Farah", "Jeane", "Jill", "Tisha", "Leon", "Leigh", + "Inge", "Zella", "Rubin", "Carri", "Nana", "Sofia", "Lucio", "Eboni", "Adam", "Lino", + "Elvis", "Marci", "Adina", "Nanci", "Joyce", "James", "Louis", "Aurea", "Chi", "Kathy", + "Nina", "Lise", "Reda", "Candi", "Ralph", "Velva", "Mari", "Mavis", "Kory", "Tammi", + "Lucy", "Lavon", "Ana", "Lin", "Alena", "Haley", "Myra", "Amy", "Marlo", "Ami" + }; + + private static String[] LAST_NAMES = new String[]{ + "Vinson", "Rogers", "Burkett", "Gamboa", "Gross", "Toledo", "Kiser", "Harman", "Pierce", "Lovett", + "Sexton", "Coates", "Seymour", "Holland", "Finley", "Hagen", "Schmitt", "Beach", "Rea", "Peck", + "Noel", "Archer", "Zamora", "Wood", "Rivera", "Lentz", "Alonso", "Rider", "Story", "Schwab", + "Mercado", "Caruso", "Bynum", "Spears", "Bingham", "Tyler", "Ponce", "Skaggs", "Matos", "Stinson", + "Burgos", "Coles", "Helton", "Joyce", "Galvan", "Grant", "Stahl", "Daigle", "Hayden", "Quiroz", + "Horne", "Shaw", "Addison", "Harvey", "Watkins", "Romano", "Ahmed", "Lind", "Swenson", "Kemp", + "Barnes", "Horton", "Dugan", "Farr", "Swanson", "Hale", "Hidalgo", "Schulte", "Ervin", "Osorio", + "Lincoln", "Zhang", "Oakes", "Stiles", "Lu", "Culver", "Singer", "Knott", "Bullard", "Butts", + "Coley", "Roth", "Cobb", "Darnell", "Vaughan", "Conrad", "Austin", "Rico", "Hobson", "Brunner", + "Mccray", "Mattson", "Barber", "Clement", "Ly", "Dejesus", "Painter", "Macias", "Healy", "Duncan", + "Forrest", "Hurley", "Torres", "Blue", "Rucker", "Ferrell", "Maddox", "Osborne", "Holt", "Briggs", + "Irvin", "Bassett", "Urban", "Overton", "Sloan", "Guzman", "Estrada", "Redding", "Gold", "Paz", + "Lucero", "Reyes", "Conner", "Keith", "Hays", "Hutton", "Moore", "Tuttle", "Powers", "William", + "Reeder", "Castro", "Vela", "Baca", "Frazier", "Kline", "Huggins", "Zepeda", "Pate", "Marion", + "Hollis", "Ybarra", "Cuellar", "Gallo", "Gomes", "Louis", "Bolden", "Liu", "Hayes", "Simpson", + "Otero", "Conway", "Peoples", "Mohr", "Loomis", "Engel", "Hughes", "Chapman", "Bower", "Schmidt", + "Mcmahon", "Booth", "Ward", "Drake", "Cutler", "Gordon", "Black", "Clifton", "Curran", "Pierre", + "Workman", "Tilley", "Moody", "Kuhn", "Eastman", "Scott", "Vang", "Tillman", "Cleary", "Yi", + "Griffin", "Mendoza", "Mason", "Pittman", "Landis", "Gay", "Rowland", "Jordan", "Lo", "Kumar", + "Vernon", "Boyd", "Rocha", "Mcqueen", "Cornett", "Deaton", "Borden", "Lacey", "Gaston", "Miles" + }; + + public static String nextFirstName() { + return randomElement(FIRST_NAMES); + } + + public static String nextLastName() { + return randomElement(LAST_NAMES); + } + + private static String toEmail(String firstName, String lastName) { + return firstName.toLowerCase() + "." + lastName.toLowerCase() + "@thingsboard.io"; + } + + public static RandomNameData next() { + var firstName = nextFirstName(); + var lastName = nextLastName(); + return new RandomNameData(firstName, lastName, toEmail(firstName, lastName)); + } + + public static RandomNameData nextSuperRandom() { + var firstName = nextFirstName() + StringUtils.randomAlphanumeric(10).toLowerCase(); + var lastName = nextLastName() + StringUtils.randomAlphanumeric(10).toLowerCase(); + return new RandomNameData(firstName, lastName, toEmail(firstName, lastName)); + } + + private static String randomElement(String[] array) { + return array[RANDOM.nextInt(array.length)]; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/SolutionInstallResponse.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/SolutionInstallResponse.java new file mode 100644 index 0000000000..e625a6bfce --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/SolutionInstallResponse.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2016-2026 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.solutions.data.solution; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import org.thingsboard.server.common.data.id.EntityId; + +import java.util.List; + +@Schema +@Data +public class SolutionInstallResponse extends TenantSolutionTemplateInstructions { + + @Schema(description = "Indicates that template was installed successfully") + private boolean success; + @Schema(description = "List of entity IDs created during solution installation") + private List createdEntityIds; + + public SolutionInstallResponse(TenantSolutionTemplateInstructions instructions, boolean success, List createdEntityIds) { + super(instructions); + this.success = success; + this.createdEntityIds = createdEntityIds; + } + + public SolutionInstallResponse() { + super(); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/TenantSolutionTemplateInstructions.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/TenantSolutionTemplateInstructions.java new file mode 100644 index 0000000000..fabd89d072 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/solution/TenantSolutionTemplateInstructions.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2016-2026 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.solutions.data.solution; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.DashboardId; + +@Schema +@Data +@AllArgsConstructor +@NoArgsConstructor +public class TenantSolutionTemplateInstructions { + + @Schema(description = "Id of the main dashboard of the solution") + private DashboardId dashboardId; + @Schema(description = "Id of the public customer if solution has public entities") + private CustomerId publicId; + @Schema(description = "Is the main dashboard public") + private boolean mainDashboardPublic; + @Schema(description = "Markdown with solution usage instructions") + private String details; + + public TenantSolutionTemplateInstructions(TenantSolutionTemplateInstructions instructions) { + this.dashboardId = instructions.getDashboardId(); + this.publicId = instructions.getPublicId(); + this.mainDashboardPublic = instructions.isMainDashboardPublic(); + this.details = instructions.getDetails(); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyDefinition.java new file mode 100644 index 0000000000..ba803faf87 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyDefinition.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class CompositeValueStrategyDefinition implements ValueStrategyDefinition { + + private ValueStrategyDefinition defaultHours; + private ValueStrategyDefinition workHours; + private ValueStrategyDefinition nightHours; + private ValueStrategyDefinition holidayHours; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.COMPOSITE; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyGenerator.java new file mode 100644 index 0000000000..6cbfaf550e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CompositeValueStrategyGenerator.java @@ -0,0 +1,55 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +public class CompositeValueStrategyGenerator extends TelemetryGenerator { + + TelemetryGenerator defaultGenerator; + TelemetryGenerator whGenerator; + TelemetryGenerator nhGenerator; + TelemetryGenerator hhGenerator; + + public CompositeValueStrategyGenerator(TelemetryProfile tp) { + super(tp); + var def = (CompositeValueStrategyDefinition) tp.getValueStrategy(); + defaultGenerator = TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), def.getDefaultHours())); + if (def.getWorkHours() != null) { + whGenerator = TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), def.getWorkHours())); + } + if (def.getNightHours() != null) { + nhGenerator = TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), def.getNightHours())); + } + if (def.getHolidayHours() != null) { + hhGenerator = TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), def.getHolidayHours())); + } + } + + @Override + public void addValue(long ts, ObjectNode values) { + if (hhGenerator != null && GeneratorTools.isHoliday(ts)) { + hhGenerator.addValue(ts, values); + } else if (nhGenerator != null && GeneratorTools.isNightHour(ts)) { + nhGenerator.addValue(ts, values); + } else if (whGenerator != null && GeneratorTools.isWorkHour(ts)) { + whGenerator.addValue(ts, values); + } else { + defaultGenerator.addValue(ts, values); + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantTelemetryGenerator.java new file mode 100644 index 0000000000..59ca319f67 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantTelemetryGenerator.java @@ -0,0 +1,51 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +public class ConstantTelemetryGenerator extends TelemetryGenerator { + + private final ConstantValueStrategyDefinition strategy; + private JsonNode value; + + public ConstantTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (ConstantValueStrategyDefinition) telemetryProfile.getValueStrategy(); + this.value = strategy.getValue(); + } + + @Override + public void addValue(long ts, ObjectNode values) { + values.set(key, value); + } + + @Override + public double getValue() { + if (value != null && value.isNumber()) { + return value.doubleValue(); + } else { + return super.getValue(); + } + } + + @Override + public void setValue(double value) { + // do nothing; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantValueStrategyDefinition.java new file mode 100644 index 0000000000..ef18ef2c9b --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ConstantValueStrategyDefinition.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class ConstantValueStrategyDefinition implements ValueStrategyDefinition { + private JsonNode value; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.CONSTANT; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterTelemetryGenerator.java new file mode 100644 index 0000000000..544d143893 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterTelemetryGenerator.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Getter; +import lombok.Setter; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.getMultiplier; +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomDouble; + +public class CounterTelemetryGenerator extends TelemetryGenerator { + + private final CounterValueStrategyDefinition strategy; + @Getter @Setter + private double value; + + public CounterTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (CounterValueStrategyDefinition) telemetryProfile.getValueStrategy(); + this.value = getRandomStartValue(); + } + + @Override + public void addValue(long ts, ObjectNode values) { + double step = randomDouble(strategy.getMinIncrement(), strategy.getMaxIncrement()); + double multiplier = getMultiplier(ts, strategy.getHolidayMultiplier(), strategy.getWorkHoursMultiplier(), strategy.getNightHoursMultiplier()); + value += step * multiplier; + if (value > getRandomEndValue()) { + value = getRandomStartValue(); + } + put(values, value); + } + + private void put(ObjectNode values, double value) { + if (strategy.getPrecision() == 0) { + values.put(key, (int) value); + } else { + values.put(key, BigDecimal.valueOf(value) + .setScale(strategy.getPrecision(), RoundingMode.HALF_UP) + .doubleValue()); + } + } + + public double getRandomStartValue() { + return randomDouble(strategy.getMinStartValue(), strategy.getMaxStartValue()); + } + + public double getRandomEndValue() { + return randomDouble(strategy.getMinEndValue(), strategy.getMaxEndValue()); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterValueStrategyDefinition.java new file mode 100644 index 0000000000..9010af51bd --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/CounterValueStrategyDefinition.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class CounterValueStrategyDefinition implements ValueStrategyDefinition { + + private int precision; + private double minStartValue; + private double maxStartValue; + private double minEndValue; + private double maxEndValue; + private double minIncrement; + private double maxIncrement; + private double holidayMultiplier; + private double workHoursMultiplier; + private double nightHoursMultiplier; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.COUNTER; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementTelemetryGenerator.java new file mode 100644 index 0000000000..bbcb6cedf7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementTelemetryGenerator.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomDouble; + +public class DecrementTelemetryGenerator extends IncDecTelemetryGenerator { + + public DecrementTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + } + + @Override + public void addValue(long ts, ObjectNode values) { + double step = randomDouble(strategy.getMinDecrement(), strategy.getMaxDecrement()); + double newValue = value - step; + value = Math.max(newValue, endValue); + put(values, value); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementValueStrategyDefinition.java new file mode 100644 index 0000000000..b5f254e2e5 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/DecrementValueStrategyDefinition.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class DecrementValueStrategyDefinition extends IncDecValueStrategyDefinition { + + private double minDecrement; + private double maxDecrement; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.DECREMENT; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventTelemetryGenerator.java new file mode 100644 index 0000000000..82555f7ed4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventTelemetryGenerator.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomLong; + + +public class EventTelemetryGenerator extends TelemetryGenerator { + + private final EventValueStrategyDefinition strategy; + private final long currentAnomaly; + private Object value; + + public EventTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (EventValueStrategyDefinition) telemetryProfile.getValueStrategy(); + currentAnomaly = randomLong(0, strategy.getAnomalyChance()); + } + + @Override + public void addValue(long ts, ObjectNode values) { + boolean anomaly = false; + if (randomLong(0, strategy.getAnomalyChance()) == currentAnomaly) { + anomaly = true; + } + this.value = anomaly ? strategy.getAnomalyValue() : strategy.getNormalValue(); + if (value instanceof Boolean) { + values.put(key, (Boolean) value); + } else if (value instanceof Double) { + values.put(key, ((Double) value)); + } else if (value instanceof Integer) { + values.put(key, ((Integer) value)); + } else { + throw new RuntimeException("Not supported value for event telemetry generator: " + value); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventValueStrategyDefinition.java new file mode 100644 index 0000000000..855004da02 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/EventValueStrategyDefinition.java @@ -0,0 +1,33 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class EventValueStrategyDefinition implements ValueStrategyDefinition { + private Object normalValue; + private Object anomalyValue; + private double anomalyChance; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.EVENT; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/GeneratorTools.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/GeneratorTools.java new file mode 100644 index 0000000000..918379faa6 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/GeneratorTools.java @@ -0,0 +1,96 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import java.util.Calendar; +import java.util.Date; +import java.util.Random; +import java.util.TimeZone; + +public class GeneratorTools { + + private static final Random random = new Random(); + + public static long randomLong(double min, double max) { + return (long) randomDouble(min, max); + } + + public static double randomDouble(double min, double max) { + return min + random.nextDouble() * Math.abs(max - min); + } + + public static double getMultiplier(long ts, double holidayMultiplier, double workHoursMultiplier, double nightHoursMultiplier) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTime(date); + int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); + int hour = c.get(Calendar.HOUR_OF_DAY); + double multiplier = 1.0; + if (dayOfWeek == 1 || dayOfWeek == 7) { + multiplier *= holidayMultiplier; + } + + if (hour > 8 && hour < 18) { + multiplier *= workHoursMultiplier; + } else if (hour < 6 || hour > 22) { + multiplier *= nightHoursMultiplier; + } + return multiplier; + } + + public static int getHour(TimeZone tz, long ts) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTimeZone(tz); + c.setTime(date); + return c.get(Calendar.HOUR_OF_DAY); + } + + public static int getMinute(TimeZone tz, long ts) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTimeZone(tz); + c.setTime(date); + return c.get(Calendar.MINUTE); + } + + public static boolean isHoliday(long ts) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTime(date); + int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); + return dayOfWeek == 1 || dayOfWeek == 7; + } + + public static boolean isWorkHour(long ts) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTime(date); + int hour = c.get(Calendar.HOUR_OF_DAY); + + return hour > 8 && hour < 18; + } + + public static boolean isNightHour(long ts) { + Date date = new Date(ts); + Calendar c = Calendar.getInstance(); + c.setTime(date); + int hour = c.get(Calendar.HOUR_OF_DAY); + + return hour < 6 || hour >= 22; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecTelemetryGenerator.java new file mode 100644 index 0000000000..09d7e2dce2 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecTelemetryGenerator.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Getter; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomDouble; + +public abstract class IncDecTelemetryGenerator extends TelemetryGenerator { + + protected final T strategy; + @Getter + protected double value; + protected double endValue; + + @SuppressWarnings("unchecked") + public IncDecTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (T) telemetryProfile.getValueStrategy(); + this.value = getRandomStartValue(); + this.endValue = getRandomEndValue(); + } + + public void setValue(double value) { + this.value = value; + this.endValue = getRandomEndValue(); + } + + protected void put(ObjectNode values, double value) { + if (strategy.getPrecision() == 0) { + values.put(key, (int) value); + } else { + values.put(key, BigDecimal.valueOf(value) + .setScale(strategy.getPrecision(), RoundingMode.HALF_UP) + .doubleValue()); + } + } + + public double getRandomStartValue() { + return randomDouble(strategy.getMinStartValue(), strategy.getMaxStartValue()); + } + + public double getRandomEndValue() { + return randomDouble(strategy.getMinEndValue(), strategy.getMaxEndValue()); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecValueStrategyDefinition.java new file mode 100644 index 0000000000..adc3100dab --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncDecValueStrategyDefinition.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public abstract class IncDecValueStrategyDefinition implements ValueStrategyDefinition { + + private int precision; + private double minStartValue; + private double maxStartValue; + private double minEndValue; + private double maxEndValue; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementTelemetryGenerator.java new file mode 100644 index 0000000000..d18f36017f --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementTelemetryGenerator.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomDouble; + +public class IncrementTelemetryGenerator extends IncDecTelemetryGenerator { + + public IncrementTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + } + + @Override + public void addValue(long ts, ObjectNode values) { + double step = randomDouble(strategy.getMinIncrement(), strategy.getMaxIncrement()); + double newValue = value + step; + value = Math.min(newValue, endValue); + put(values, value); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementValueStrategyDefinition.java new file mode 100644 index 0000000000..64d7bc0b4c --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/IncrementValueStrategyDefinition.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class IncrementValueStrategyDefinition extends IncDecValueStrategyDefinition { + + private double minIncrement; + private double maxIncrement; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.INCREMENT; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalTelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalTelemetryGenerator.java new file mode 100644 index 0000000000..927eb5a76f --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalTelemetryGenerator.java @@ -0,0 +1,94 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Getter; +import lombok.Setter; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.getMultiplier; +import static org.thingsboard.server.service.solutions.data.values.GeneratorTools.randomDouble; + +public class NaturalTelemetryGenerator extends TelemetryGenerator { + + private final NaturalValueStrategyDefinition strategy; + @Getter @Setter + private double value; + private boolean isIncrement; + private double lowValue; + private double highValue; + + public NaturalTelemetryGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (NaturalValueStrategyDefinition) telemetryProfile.getValueStrategy(); + this.value = getRandomStartValue(); + this.lowValue = getRandomLowValue(); + this.highValue = getRandomHighValue(); + isIncrement = !strategy.isDecrementOnStart(); + } + + @Override + public void addValue(long ts, ObjectNode values) { + + double multiplier = getMultiplier(ts, strategy.getHolidayMultiplier(), strategy.getWorkHoursMultiplier(), strategy.getNightHoursMultiplier()); + + if (isIncrement) { + double step = randomDouble(strategy.getMinIncrement(), strategy.getMaxIncrement()); + value += step * multiplier; + if (value > highValue) { + value = highValue; + highValue = getRandomHighValue(); + isIncrement = false; + } + } else { + double step = randomDouble(strategy.getMinDecrement(), strategy.getMaxDecrement()); + value -= step * multiplier; + if (value < lowValue) { + value = lowValue; + lowValue = getRandomLowValue(); + isIncrement = true; + } + } + + put(values, value); + } + + private void put(ObjectNode values, double value) { + if (strategy.getPrecision() == 0) { + values.put(key, (int) value); + } else { + values.put(key, BigDecimal.valueOf(value) + .setScale(strategy.getPrecision(), RoundingMode.HALF_UP) + .doubleValue()); + } + } + + public double getRandomStartValue() { + return randomDouble(strategy.getMinStartValue(), strategy.getMaxStartValue()); + } + + public double getRandomLowValue() { + return randomDouble(strategy.getMinLowValue(), strategy.getMaxLowValue()); + } + + public double getRandomHighValue() { + return randomDouble(strategy.getMinHighValue(), strategy.getMaxHighValue()); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalValueStrategyDefinition.java new file mode 100644 index 0000000000..3141baa47a --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/NaturalValueStrategyDefinition.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class NaturalValueStrategyDefinition implements ValueStrategyDefinition { + private int precision; + private double minStartValue; + private double maxStartValue; + private double minLowValue; + private double maxLowValue; + private double minHighValue; + private double maxHighValue; + private double minIncrement; + private double maxIncrement; + private double minDecrement; + private double maxDecrement; + private double holidayMultiplier; + private double workHoursMultiplier; + private double nightHoursMultiplier; + private boolean decrementOnStart; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.NATURAL; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyDefinition.java new file mode 100644 index 0000000000..4804863bd3 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyDefinition.java @@ -0,0 +1,35 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Data; + +import java.util.List; + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class ScheduleValueStrategyDefinition implements ValueStrategyDefinition { + + private List schedule; + private String timeZone; + private ValueStrategyDefinition defaultDefinition; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.SCHEDULE; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyGenerator.java new file mode 100644 index 0000000000..1d067a3044 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ScheduleValueStrategyGenerator.java @@ -0,0 +1,70 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.TimeZone; + +public class ScheduleValueStrategyGenerator extends TelemetryGenerator { + + private TelemetryGenerator defaultGenerator; + private TimeZone timeZone; + private Map scheduleGenerators; + private TelemetryGenerator prevGenerator; + + public ScheduleValueStrategyGenerator(TelemetryProfile tp) { + super(tp); + var def = (ScheduleValueStrategyDefinition) tp.getValueStrategy(); + timeZone = TimeZone.getTimeZone(def.getTimeZone()); + defaultGenerator = TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), def.getDefaultDefinition())); + scheduleGenerators = new LinkedHashMap<>(); + for (ValueStrategySchedule scheduleItem : def.getSchedule()) { + scheduleGenerators.put(scheduleItem, TelemetryGeneratorFactory.create(new TelemetryProfile(tp.getKey(), scheduleItem.getDefinition()))); + } + } + + @Override + public void addValue(long ts, ObjectNode values) { + int hour = GeneratorTools.getHour(timeZone, ts); + int minute = GeneratorTools.getMinute(timeZone, ts); + TelemetryGenerator generator = scheduleGenerators.entrySet().stream().filter(pair -> { + var schedule = pair.getKey(); + if (hour == schedule.getStartHour() && hour == schedule.getEndHour()) { + return schedule.getStartMinute() <= minute && minute <= schedule.getEndMinute(); + } else if (hour == schedule.getStartHour() && hour < schedule.getEndHour()) { + return schedule.getStartMinute() <= minute; + } else if (hour > schedule.getStartHour() && hour < schedule.getEndHour()) { + return true; + } else if (hour > schedule.getStartHour() && hour == schedule.getEndHour()) { + return minute <= schedule.getEndHour(); + } else { + return false; + } + }).map(Map.Entry::getValue).findFirst().orElse(defaultGenerator); + + if (prevGenerator != null && !prevGenerator.equals(generator)) { + generator.setValue(prevGenerator.getValue()); + } + + generator.addValue(ts, values); + + prevGenerator = generator; + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyDefinition.java new file mode 100644 index 0000000000..d523715d67 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyDefinition.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Data; + + +@Data +@JsonIgnoreProperties(ignoreUnknown = true) +public class SequenceValueStrategyDefinition implements ValueStrategyDefinition { + private boolean random; + private ObjectNode telemetry; + + @Override + public ValueStrategyDefinitionType getStrategyType() { + return ValueStrategyDefinitionType.SEQUENCE; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyGenerator.java new file mode 100644 index 0000000000..d7c75025f4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/SequenceValueStrategyGenerator.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +import java.util.Random; + +public class SequenceValueStrategyGenerator extends TelemetryGenerator { + + private final SequenceValueStrategyDefinition strategy; + private int max; + private int index; + + public SequenceValueStrategyGenerator(TelemetryProfile telemetryProfile) { + super(telemetryProfile); + this.strategy = (SequenceValueStrategyDefinition) telemetryProfile.getValueStrategy(); + max = strategy.getTelemetry().fields().next().getValue().size() - 1; + index = strategy.isRandom() ? new Random().nextInt(max + 1) : 0; + + } + + @Override + public void addValue(long ts, ObjectNode values) { + strategy.getTelemetry().fields().forEachRemaining(entry -> { + String key = entry.getKey(); + values.set(key, entry.getValue().get(index)); + }); + index++; + if (index > max) { + index = 0; + } + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGenerator.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGenerator.java new file mode 100644 index 0000000000..5024f4e590 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGenerator.java @@ -0,0 +1,41 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Data; +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +@Data +public abstract class TelemetryGenerator { + protected final TelemetryProfile profile; + protected final String key; + + public TelemetryGenerator(TelemetryProfile telemetryProfile) { + this.profile = telemetryProfile; + this.key = telemetryProfile.getKey(); + } + + public double getValue() { + throw new RuntimeException("Not supported"); + } + + public void setValue(double value) { + throw new RuntimeException("Not supported"); + } + + public abstract void addValue(long ts, ObjectNode values); +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGeneratorFactory.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGeneratorFactory.java new file mode 100644 index 0000000000..17d29ce3e1 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/TelemetryGeneratorFactory.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + + +import org.thingsboard.server.service.solutions.data.definition.TelemetryProfile; + +public class TelemetryGeneratorFactory { + + public static TelemetryGenerator create(TelemetryProfile tp) { + switch (tp.getValueStrategy().getStrategyType()) { + case COUNTER: + return new CounterTelemetryGenerator(tp); + case NATURAL: + return new NaturalTelemetryGenerator(tp); + case EVENT: + return new EventTelemetryGenerator(tp); + case CONSTANT: + return new ConstantTelemetryGenerator(tp); + case SEQUENCE: + return new SequenceValueStrategyGenerator(tp); + case COMPOSITE: + return new CompositeValueStrategyGenerator(tp); + case SCHEDULE: + return new ScheduleValueStrategyGenerator(tp); + case INCREMENT: + return new IncrementTelemetryGenerator(tp); + case DECREMENT: + return new DecrementTelemetryGenerator(tp); + default: + throw new RuntimeException("Not supported!"); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinition.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinition.java new file mode 100644 index 0000000000..34d5f9b5e7 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinition.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.PROPERTY, + property = "type") +@JsonSubTypes({ + @JsonSubTypes.Type(value = CounterValueStrategyDefinition.class, name = "counter"), + @JsonSubTypes.Type(value = NaturalValueStrategyDefinition.class, name = "natural"), + @JsonSubTypes.Type(value = EventValueStrategyDefinition.class, name = "event"), + @JsonSubTypes.Type(value = SequenceValueStrategyDefinition.class, name = "sequence"), + @JsonSubTypes.Type(value = ConstantValueStrategyDefinition.class, name = "constant"), + @JsonSubTypes.Type(value = CompositeValueStrategyDefinition.class, name = "composite"), + @JsonSubTypes.Type(value = ScheduleValueStrategyDefinition.class, name = "schedule"), + @JsonSubTypes.Type(value = IncrementValueStrategyDefinition.class, name = "inc"), + @JsonSubTypes.Type(value = DecrementValueStrategyDefinition.class, name = "dec")}) +public interface ValueStrategyDefinition { + + ValueStrategyDefinitionType getStrategyType(); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinitionType.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinitionType.java new file mode 100644 index 0000000000..a561d6469e --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategyDefinitionType.java @@ -0,0 +1,22 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +public enum ValueStrategyDefinitionType { + + COUNTER, NATURAL, EVENT, SEQUENCE, CONSTANT, COMPOSITE, SCHEDULE, INCREMENT, DECREMENT; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategySchedule.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategySchedule.java new file mode 100644 index 0000000000..0bb2ccf8fa --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/values/ValueStrategySchedule.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2016-2026 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.solutions.data.values; + +import lombok.Data; + +@Data +public class ValueStrategySchedule { + + private int startHour; + private int startMinute; + + private int endHour; + private int endMinute; + + private ValueStrategyDefinition definition; + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/DeviceProfile.java b/common/data/src/main/java/org/thingsboard/server/common/data/DeviceProfile.java index a4317b8aa6..8d0c44800c 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/DeviceProfile.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/DeviceProfile.java @@ -114,6 +114,9 @@ public class DeviceProfile extends BaseData implements HasName, this.description = deviceProfile.getDescription(); this.image = deviceProfile.getImage(); this.isDefault = deviceProfile.isDefault(); + this.type = deviceProfile.getType(); + this.transportType = deviceProfile.getTransportType(); + this.provisionType = deviceProfile.getProvisionType(); this.defaultRuleChainId = deviceProfile.getDefaultRuleChainId(); this.defaultDashboardId = deviceProfile.getDefaultDashboardId(); this.defaultQueueName = deviceProfile.getDefaultQueueName(); diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java index e08b686515..544f44cbc2 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/IotHubInstalledItemDescriptor.java @@ -31,7 +31,8 @@ import java.io.Serializable; @Type(name = "DASHBOARD", value = DashboardInstalledItemDescriptor.class), @Type(name = "CALCULATED_FIELD", value = CalculatedFieldInstalledItemDescriptor.class), @Type(name = "RULE_CHAIN", value = RuleChainInstalledItemDescriptor.class), - @Type(name = "DEVICE", value = DeviceInstalledItemDescriptor.class) + @Type(name = "DEVICE", value = DeviceInstalledItemDescriptor.class), + @Type(name = "SOLUTION_TEMPLATE", value = SolutionTemplateInstalledItemDescriptor.class) }) public interface IotHubInstalledItemDescriptor extends Serializable { diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/SolutionTemplateInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/SolutionTemplateInstalledItemDescriptor.java new file mode 100644 index 0000000000..51a34576aa --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/SolutionTemplateInstalledItemDescriptor.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2016-2026 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.common.data.iot_hub; + +import lombok.Data; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.DashboardId; +import org.thingsboard.server.common.data.id.EntityId; + +import java.util.List; + +@Data +public class SolutionTemplateInstalledItemDescriptor implements IotHubInstalledItemDescriptor { + + private List createdEntityIds; + private DashboardId dashboardId; + private CustomerId publicId; + private boolean mainDashboardPublic; + private String details; + +} diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index 00c0d3e5e1..361062149c 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -207,6 +207,7 @@ import { CheckConnectivityDialogComponent } from '@home/components/ai-model/chec import { AIModelDialogComponent } from '@home/components/ai-model/ai-model-dialog.component'; import { ResourcesDialogComponent } from "@home/components/resources/resources-dialog.component"; import { ResourcesLibraryComponent } from "@home/components/resources/resources-library.component"; +import { SolutionInstallDialogComponent } from '@home/components/solution/solution-install-dialog.component'; @NgModule({ declarations: @@ -362,6 +363,7 @@ import { ResourcesLibraryComponent } from "@home/components/resources/resources- AIModelDialogComponent, ResourcesDialogComponent, ResourcesLibraryComponent, + SolutionInstallDialogComponent, ], imports: [ CommonModule, @@ -511,6 +513,7 @@ import { ResourcesLibraryComponent } from "@home/components/resources/resources- AIModelDialogComponent, ResourcesDialogComponent, ResourcesLibraryComponent, + SolutionInstallDialogComponent, ], providers: [ WidgetComponentService, diff --git a/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.html new file mode 100644 index 0000000000..e5736bf4f3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.html @@ -0,0 +1,44 @@ + +
+ +

@if (instructions) {info_outline}{{ (instructions ? 'iot-hub.solution-instructions' : 'iot-hub.solution-install-title') | translate }}

+ + +
+
+ +
+
+ + @if (dashboardId) { + + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.scss b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.scss new file mode 100644 index 0000000000..9b95152b86 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.scss @@ -0,0 +1,50 @@ +/** + * Copyright © 2016-2026 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. + */ + +:host { + h2 { + .mat-icon { + padding-right: 8px; + box-sizing: initial; + vertical-align: sub; + } + } +} + +:host ::ng-deep { + .mat-mdc-dialog-content { + tb-markdown { + .tb-markdown-view { + .table-wrapper { + overflow-y: auto; + margin: 30px 32px; + border: 1px solid rgba(42, 125, 236, .2); + border-radius: 4px; + padding: 0; + width: calc(100% - 64px); + table { + width: 100%; + table-layout: auto; + white-space: nowrap; + margin: 0; + border: 0; + border-radius: 0; + } + } + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.ts new file mode 100644 index 0000000000..5ef74c4879 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/solution/solution-install-dialog.component.ts @@ -0,0 +1,59 @@ +/// +/// Copyright © 2016-2026 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. +/// + +import { Component, Inject } from '@angular/core'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { Router } from '@angular/router'; +import { SolutionTemplateInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; + +export interface SolutionInstallDialogData { + descriptor: SolutionTemplateInstalledItemDescriptor; + instructions?: boolean; +} + +@Component({ + selector: 'tb-solution-install-dialog', + templateUrl: './solution-install-dialog.component.html', + styleUrls: ['./solution-install-dialog.component.scss'], + standalone: false +}) +export class SolutionInstallDialogComponent { + + details: string; + dashboardId: string | null; + instructions: boolean; + + constructor( + @Inject(MAT_DIALOG_DATA) public data: SolutionInstallDialogData, + private dialogRef: MatDialogRef, + private router: Router + ) { + this.details = data.descriptor.details || ''; + this.dashboardId = data.descriptor.dashboardId?.id || null; + this.instructions = !!data.instructions; + } + + gotoMainDashboard(): void { + if (this.dashboardId) { + this.dialogRef.close(); + this.router.navigateByUrl(`/dashboards/${this.dashboardId}`); + } + } + + close(): void { + this.dialogRef.close(); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.html index 3894da7685..b352a5293b 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.html @@ -42,6 +42,11 @@ (click)="onTypeTabChange(ItemType.DASHBOARD)"> {{ 'item.type-dashboard' | translate }}s + + {{ 'item.type-solution-template' | translate }}s + diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.ts index a9b7243898..5ca56d4a55 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-browse.component.ts @@ -42,6 +42,7 @@ interface SortOption { const TYPE_TABS: ItemType[] = [ ItemType.WIDGET, ItemType.DASHBOARD, + ItemType.SOLUTION_TEMPLATE, ItemType.CALCULATED_FIELD, ItemType.RULE_CHAIN, ItemType.DEVICE @@ -296,6 +297,7 @@ export class TbIotHubBrowseComponent implements OnInit, OnDestroy { switch (this.activeType) { case ItemType.WIDGET: return 'iot-hub.title-widgets'; case ItemType.DASHBOARD: return 'iot-hub.title-dashboards'; + case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.title-solution-templates'; case ItemType.CALCULATED_FIELD: return 'iot-hub.title-calculated-fields'; case ItemType.RULE_CHAIN: return 'iot-hub.title-rule-chains'; case ItemType.DEVICE: return 'iot-hub.title-devices'; @@ -306,6 +308,7 @@ export class TbIotHubBrowseComponent implements OnInit, OnDestroy { switch (this.activeType) { case ItemType.WIDGET: return 'iot-hub.subtitle-widgets'; case ItemType.DASHBOARD: return 'iot-hub.subtitle-dashboards'; + case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.subtitle-solution-templates'; case ItemType.CALCULATED_FIELD: return 'iot-hub.subtitle-calculated-fields'; case ItemType.RULE_CHAIN: return 'iot-hub.subtitle-rule-chains'; case ItemType.DEVICE: return 'iot-hub.subtitle-devices'; @@ -316,6 +319,7 @@ export class TbIotHubBrowseComponent implements OnInit, OnDestroy { switch (this.activeType) { case ItemType.WIDGET: return 'iot-hub.search-widgets'; case ItemType.DASHBOARD: return 'iot-hub.search-dashboards'; + case ItemType.SOLUTION_TEMPLATE: return 'iot-hub.search-solution-templates'; case ItemType.CALCULATED_FIELD: return 'iot-hub.search-calculated-fields'; case ItemType.RULE_CHAIN: return 'iot-hub.search-rule-chains'; case ItemType.DEVICE: return 'iot-hub.search-devices'; diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-install-dialog.component.ts index fd48b0f999..ecb623103d 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-install-dialog.component.ts @@ -15,16 +15,20 @@ /// import { Component, Inject } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog'; import { Router } from '@angular/router'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; -import { IotHubInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { + IotHubInstalledItemDescriptor, + SolutionTemplateInstalledItemDescriptor +} from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { TranslateService } from '@ngx-translate/core'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityId } from '@shared/models/id/entity-id'; import { getEntityDetailsPageURL } from '@core/utils'; +import { SolutionInstallDialogComponent } from '@home/components/solution/solution-install-dialog.component'; export interface IotHubInstallDialogData { item: MpItemVersionView; @@ -173,6 +177,7 @@ export class TbIotHubInstallDialogComponent { constructor( @Inject(MAT_DIALOG_DATA) public data: IotHubInstallDialogData, private dialogRef: MatDialogRef, + private dialog: MatDialog, private router: Router, private translate: TranslateService ) { @@ -199,8 +204,17 @@ export class TbIotHubInstallDialogComponent { this.data.iotHubApiService.installItemVersion(versionId, { ignoreLoading: true }, data).subscribe({ next: (result) => { if (result.success) { - this.state = 'success'; - this.entityDetailsUrl = this.resolveEntityDetailsUrl(result.descriptor); + if (result.descriptor?.type === 'SOLUTION_TEMPLATE') { + this.dialogRef.close('installed'); + this.dialog.open(SolutionInstallDialogComponent, { + disableClose: true, + panelClass: 'tb-solution-install-dialog-panel', + data: { descriptor: result.descriptor as SolutionTemplateInstalledItemDescriptor } + }); + } else { + this.state = 'success'; + this.entityDetailsUrl = this.resolveEntityDetailsUrl(result.descriptor); + } } else { this.state = 'error'; this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss index d066356922..2897f9416a 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.scss @@ -187,9 +187,9 @@ } .mat-column-itemType { - width: 150px; - min-width: 150px; - max-width: 150px; + width: 170px; + min-width: 170px; + max-width: 170px; } .mat-column-version { @@ -231,6 +231,7 @@ &.tb-type-calc-field { background: #fff3e0; color: #e65100; } &.tb-type-rule-chain { background: #f3e5f5; color: #7b1fa2; } &.tb-type-device { background: #eceff1; color: #455a64; } + &.tb-type-solution-template { background: #e0f7fa; color: #00695c; } } .tb-iot-hub-up-to-date { diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts index 317ba59816..31d00f041f 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-installed-items.component.ts @@ -145,6 +145,7 @@ export class TbIotHubInstalledItemsComponent implements OnInit, AfterViewInit { case 'CALCULATED_FIELD': return 'tb-type-calc-field'; case 'RULE_CHAIN': return 'tb-type-rule-chain'; case 'DEVICE': return 'tb-type-device'; + case 'SOLUTION_TEMPLATE': return 'tb-type-solution-template'; default: return ''; } } @@ -169,6 +170,7 @@ export class TbIotHubInstalledItemsComponent implements OnInit, AfterViewInit { case 'DASHBOARD': return descriptor.dashboardId?.id; case 'CALCULATED_FIELD': return descriptor.entityId?.id; case 'RULE_CHAIN': return descriptor.ruleChainId?.id; + case 'SOLUTION_TEMPLATE': return descriptor.dashboardId?.id; default: return null; } } @@ -180,6 +182,7 @@ export class TbIotHubInstalledItemsComponent implements OnInit, AfterViewInit { case 'DASHBOARD': return EntityType.DASHBOARD; case 'CALCULATED_FIELD': return descriptor.entityId?.entityType as EntityType; case 'RULE_CHAIN': return EntityType.RULE_CHAIN; + case 'SOLUTION_TEMPLATE': return EntityType.DASHBOARD; default: return null; } } diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-card.component.ts b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-card.component.ts index 87f5502696..995aefa065 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-card.component.ts +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-card.component.ts @@ -66,6 +66,7 @@ export class TbIotHubItemCardComponent { case ItemType.CALCULATED_FIELD: return 'preview-calculated-field'; case ItemType.RULE_CHAIN: return 'preview-rule-chain'; case ItemType.DEVICE: return 'preview-device'; + case ItemType.SOLUTION_TEMPLATE: return 'preview-dashboard'; default: return ''; } } @@ -74,6 +75,7 @@ export class TbIotHubItemCardComponent { switch (this.item.type) { case ItemType.WIDGET: return 'widgets'; case ItemType.DASHBOARD: return 'dashboard'; + case ItemType.SOLUTION_TEMPLATE: return 'integration_instructions'; case ItemType.CALCULATED_FIELD: return this.item.icon || cfTypeIcons.get(this.item.dataDescriptor?.cfType) || 'functions'; case ItemType.RULE_CHAIN: diff --git a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-detail-dialog.component.html b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-detail-dialog.component.html index 770a6bdf15..dc12d92b31 100644 --- a/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-detail-dialog.component.html +++ b/ui-ngx/src/app/modules/home/pages/iot-hub/iot-hub-item-detail-dialog.component.html @@ -69,15 +69,15 @@ } - - @if (item.type === ItemType.DASHBOARD) { + + @if (item.type === ItemType.DASHBOARD || item.type === ItemType.SOLUTION_TEMPLATE) {
@if (getPreviewUrl(); as url) { } @else {
- dashboard + {{ getTypeIcon() }}
}
@@ -116,7 +116,7 @@ } - @if (item.description && item.type !== ItemType.WIDGET && item.type !== ItemType.DASHBOARD) { + @if (item.description && item.type !== ItemType.WIDGET && item.type !== ItemType.DASHBOARD && item.type !== ItemType.SOLUTION_TEMPLATE) {
{{ item.description }}
} @@ -175,10 +175,21 @@