From 1a15b5c94f729e0a7b09b13ca2e4a70b5c73e061 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 01/12] report every conflicting entity before installing a solution template Only rule chains, profiles and dashboards were checked upfront, so a template with a clashing customer, asset, device or edge died mid install on a DB constraint and had to be rolled back. All of them are validated now, and every conflict is named and reported at once instead of repeating the same sentence per entity type. Rule chains are looked up by exact name and dashboards by exact title, since the paged text search matches with 'contains' and could report a different entity as the conflict. The install dialog also stopped repeating "Failed to install " inside the error details, since it is already shown right above them. --- .../service/iot_hub/DefaultIotHubService.java | 5 +- .../solutions/DefaultSolutionService.java | 147 +++++++++++------- .../iot_hub/DefaultIotHubServiceTest.java | 35 +++++ .../solutions/DefaultSolutionServiceTest.java | 133 ++++++++++++++++ 4 files changed, 262 insertions(+), 58 deletions(-) create mode 100644 application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java 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 f7cc08391a..cd90af6f26 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 @@ -952,7 +952,10 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + // The dialog already says "Failed to install ''" above the details, so only a + // failing dependency is worth naming here - for the root entry that would just repeat itself. + result.setErrorMessage(entry.isRoot() ? e.getMessage() + : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; 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 index 34e56275e2..d84e681be6 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -32,7 +32,6 @@ 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.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -42,7 +41,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -151,12 +149,15 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -177,6 +178,11 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -291,71 +297,102 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - + SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { //TODO: check other entities. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, + title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, + title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, + name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, + name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, + name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return null; + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); + solutionInstallResponse.setSuccess(false); + solutionInstallResponse.setDetails(details.toString()); + return solutionInstallResponse; + } + + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (StringUtils.isEmpty(name)) { + continue; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, so those are looked up as is - skipping them + * here would let the install die on a DB constraint again. + */ + private static boolean isRandomizedAtInstall(String name) { + return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. + */ + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + if (conflictDescriptions.isEmpty()) { + return; } + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + private static T firstOrNull(Collection data) { + return data == null || data.isEmpty() ? null : data.iterator().next(); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { @@ -1450,10 +1487,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1467,7 +1500,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c252b58103..bfe0db5750 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -344,6 +344,41 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the install dialog already shows "Failed to install ''" right above these details + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // a failing dependency is not the item the dialog names, so it has to be named here + assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..a8c5697a42 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,133 @@ +/** + * 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 org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + Device device = new Device(); + device.setName("Existing device"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getDetails()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} From 56866d30c8522842a7d12b2c50e11108debe919c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 02/12] compose the failed dependency sentence in the dialog, not in the service The service was pre-composing "Failed to install dependency '':", which can never be translated and made the backend depend on the dialog already printing the root item above the details. It now reports the failure itself, and the dialog prefixes a localized sentence when the entry that failed is not the root. --- .../service/iot_hub/DefaultIotHubService.java | 5 +---- .../service/iot_hub/DefaultIotHubServiceTest.java | 15 ++++++++++----- .../iot-hub/iot-hub-install-dialog.component.ts | 6 ++++++ .../src/assets/locale/locale.constant-en_US.json | 1 + 4 files changed, 18 insertions(+), 9 deletions(-) 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 cd90af6f26..f7109c3bf2 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 @@ -952,10 +952,7 @@ public class DefaultIotHubService implements IotHubService { boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - // The dialog already says "Failed to install ''" above the details, so only a - // failing dependency is worth naming here - for the root entry that would just repeat itself. - result.setErrorMessage(entry.isRoot() ? e.getMessage() - : "Failed to install dependency '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(e.getMessage()); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index bfe0db5750..c48e5896a1 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -345,7 +345,7 @@ class DefaultIotHubServiceTest { } @Test - void installPlan_rootFails_errorMessageIsNotPrefixedWithTheItemName() throws Exception { + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String rootVersionId = UUID.randomUUID().toString(); @@ -356,12 +356,12 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); - // the install dialog already shows "Failed to install ''" right above these details + // the sentence around the failure belongs to the dialog, which localizes it assertThat(result.getErrorMessage()).isEqualTo("install failed"); } @Test - void installPlan_dependencyFails_errorMessageNamesTheDependency() throws Exception { + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { mockTenant(); HttpServletRequest request = mock(HttpServletRequest.class); String depVersionId = UUID.randomUUID().toString(); @@ -374,8 +374,13 @@ class DefaultIotHubServiceTest { InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); - // a failing dependency is not the item the dialog names, so it has to be named here - assertThat(result.getErrorMessage()).isEqualTo("Failed to install dependency 'Dep': install failed"); + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index e4816d19ad..c55d708bcb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -339,6 +339,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 98f59ec8a9..aefce04e88 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,6 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}':", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From 0d275e0d2cf75dca4f50506fe9107e80e3911829 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:11:49 +0300 Subject: [PATCH 03/12] address review comments on the install validation - rule chains are looked up under the name from the rule chain file, the same source the install uses, instead of the name in rule_chains.json - the details end with a blank line, so the partial rollback warning the dialog appends does not land inside the last list item - an exception without a message falls back to its type, so the failing entry is still named - the dependency prefix is only added when the server sent an error message, since the fallback sentence names the root item --- .../service/iot_hub/DefaultIotHubService.java | 8 +++-- .../solutions/DefaultSolutionService.java | 22 ++++++++++++- .../iot_hub/DefaultIotHubServiceTest.java | 18 ++++++++++ .../solutions/DefaultSolutionServiceTest.java | 33 ++++++++++++++++++- .../iot-hub-install-dialog.component.ts | 10 +++--- 5 files changed, 83 insertions(+), 8 deletions(-) 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 f7109c3bf2..1e41211cb2 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 @@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -947,12 +948,15 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + // an exception without a message would leave both the entry and the result blank, + // and the dialog would have nothing to name the failing entry by + String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); + resultEntry.setErrorMessage(failure); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(e.getMessage()); + result.setErrorMessage(failure); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; 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 index d84e681be6..216960f4fe 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -321,7 +321,7 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, ReferenceableEntityDefinition::getName, + collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -345,6 +345,9 @@ public class DefaultSolutionService implements SolutionService { conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); + // the dialog appends its own sentences to these details, so the list has to end with a blank line + details.append(System.lineSeparator()); + SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); solutionInstallResponse.setDetails(details.toString()); @@ -391,6 +394,23 @@ public class DefaultSolutionService implements SolutionService { return "'" + value + "'"; } + /** + * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, + * so the conflict has to be looked up under the name the install will actually create. + */ + private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { + if (StringUtils.isEmpty(definition.getFile())) { + return null; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + return null; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; + } + private static T firstOrNull(Collection data) { return data == null || data.isEmpty() ? null : data.iterator().next(); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index c48e5896a1..e34fd92d3c 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -384,6 +384,24 @@ class DefaultIotHubServiceTest { verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); } + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index a8c5697a42..04096c3cc3 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,15 +25,19 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; import java.util.UUID; @@ -57,6 +61,8 @@ class DefaultSolutionServiceTest { private AssetService assetService; @Mock private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; @InjectMocks private DefaultSolutionService service; @@ -89,6 +95,8 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); + // the dialog appends its own sentences, so the details have to end with a blank line + assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -111,6 +119,23 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -122,7 +147,13 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); } private void writeEntitiesFile(String fileName, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index c55d708bcb..54a8409063 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -338,10 +338,12 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage); + const serverError = result.errorMessage; + let message = serverError || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + // The title already names the item being installed, so only a failing dependency has to be named + // here - and only when the server reported the failure, since the fallback above names the root. + const failedDependency = serverError + ? (result.entries ?? []).find(entry => !entry.root && entry.errorMessage) : undefined; if (failedDependency) { message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; } From 6fe4852f9b953e9d73ac009de56031550f4b650a Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 7 Sep 2026 15:56:03 +0300 Subject: [PATCH 04/12] address the second review pass on the install validation - the dialog no longer mistakes a MISSING plan entry for the failing one: such entries carry an error message of their own with no name, so the lookup now also requires the WILL_INSTALL status - the whole dependency sentence lives in the locale bundle as one key with a name and an error parameter, instead of a fragment glued to the server message, and the partial rollback warning is appended as its own paragraph by the dialog rather than relying on the details ending with a blank line - a rule chain is validated under the type from the rule chain file too, so an EDGE chain is no longer looked up among the CORE ones - names are deduplicated before the lookup rather than when formatting, so a template repeating a name queries once - the entity type and the name come from the definition itself for the five lists that carry both, which removes the pairing hazard - ExceptionUtil.getMessage replaces the hand-rolled fallback, and the single-use firstOrNull helper is inlined - the dashboard check moved after the device one to match the provision order the comment claims, and the unreachable empty-list guard is gone - tests cover both profile types, edges, the rule chain type and its two unresolvable-name branches, the deduplicated lookup and a json file holding null --- .../service/iot_hub/DefaultIotHubService.java | 10 +- .../solutions/DefaultSolutionService.java | 130 ++++++++++-------- .../solutions/DefaultSolutionServiceTest.java | 88 +++++++++++- .../iot-hub-install-dialog.component.ts | 14 +- .../assets/locale/locale.constant-en_US.json | 2 +- 5 files changed, 173 insertions(+), 71 deletions(-) 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 1e41211cb2..f7f5fae4a5 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 @@ -20,8 +20,8 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DeviceProfile; @@ -948,15 +948,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - // an exception without a message would leave both the entry and the result blank, - // and the dialog would have nothing to name the failing entry by - String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage(); - resultEntry.setErrorMessage(failure); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage(failure); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; 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 index 216960f4fe..cdeb9c06af 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -124,6 +124,7 @@ 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.EntityDefinition; 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; @@ -181,7 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; - private static final String RANDOM_NAME_PLACEHOLDER_PREFIX = "$random"; + private static final String RANDOM_PLACEHOLDER = "$random"; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,32 +322,23 @@ public class DefaultSolutionService implements SolutionService { // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. Map> conflicts = new LinkedHashMap<>(); - collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition), - name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name))); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, name -> assetProfileService.findAssetProfileByName(tenantId, name)); - collectConflicts(conflicts, EntityType.CUSTOMER, customers, CustomerDefinition::getName, - title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); - collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName, - title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); - collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName, - name -> assetService.findAssetByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName, - name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); - collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName, - name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList())); - - // the dialog appends its own sentences to these details, so the list has to end with a blank line - details.append(System.lineSeparator()); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -354,65 +346,91 @@ public class DefaultSolutionService implements SolutionService { return solutionInstallResponse; } + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); + } + } + } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); for (T definition : definitions) { String name = nameExtractor.apply(definition); - if (StringUtils.isEmpty(name)) { + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); + } + } + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate continue; } - HasName existing = lookup.apply(name); - if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } /** * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of - * every other entity are used as written, placeholder included, so those are looked up as is - skipping them - * here would let the install die on a DB constraint again. + * every other entity are used as written, placeholder included, and must be looked up as is. */ - private static boolean isRandomizedAtInstall(String name) { - return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX); + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); } /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { - if (conflictDescriptions.isEmpty()) { - return; - } + private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator()); - } - - private static String quoted(String value) { - return "'" + value + "'"; - } - - /** - * The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json, - * so the conflict has to be looked up under the name the install will actually create. - */ - private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) { - if (StringUtils.isEmpty(definition.getFile())) { - return null; - } - Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); - if (!Files.exists(ruleChainPath)) { - // provisionRuleChains logs and skips such a definition, so there is nothing to validate - return null; - } - JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); - return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null; - } - - private static T firstOrNull(Collection data) { - return data == null || data.isEmpty() ? null : data.iterator().next(); + .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) + .append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 04096c3cc3..d89012057b 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -24,13 +24,19 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; import org.thingsboard.server.dao.asset.AssetService; import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; +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.rule.RuleChainService; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; @@ -42,6 +48,8 @@ import java.util.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -63,6 +71,12 @@ class DefaultSolutionServiceTest { private DashboardService dashboardService; @Mock private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; @InjectMocks private DefaultSolutionService service; @@ -95,8 +109,6 @@ class DefaultSolutionServiceTest { CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Device**: 'Existing device'"); - // the dialog appends its own sentences, so the details have to end with a blank line - assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator()); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) .doesNotContain("Customer $random") @@ -136,6 +148,78 @@ class DefaultSolutionServiceTest { .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result).isNotNull(); + assertThat(result.getDetails().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + Device device = new Device(); + device.setName("Sensor"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + verifyNoInteractions(deviceService); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 54a8409063..f777a4da31 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -340,19 +340,21 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage) : undefined; + // The title already names the item being installed, so only a failing dependency has to be named here, and + // only when the server reported the failure - the fallback above names the root. A missing entry carries an + // error message of its own, so the failing one is the entry the cascade actually tried to install. + const failedDependency = serverError ? (result.entries ?? []).find( + entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { - message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message; + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index aefce04e88..b5f51fd6d4 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3850,7 +3850,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", - "install-dependency-error": "Failed to install the dependency '{{name}}':", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.", From f97bc57694821c4ef8d8ca05222e9319cd44c9d7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Tue, 8 Sep 2026 13:36:49 +0300 Subject: [PATCH 05/12] address the PE review notes on the install report - drop the java.util.Collection import that stayed behind when firstOrNull was inlined - cap each report section at ten names plus "and N more": a template can hold hundreds of devices, and the dialog renders these details without the height cap the plain-text branch has - leave the details empty when the server reported no message of its own, since the description above them already names the item that failed - cover the asset conflict, the capped report and the remaining mocks in the validation test --- .../solutions/DefaultSolutionService.java | 14 ++++++--- .../solutions/DefaultSolutionServiceTest.java | 31 +++++++++++++++++-- .../iot-hub-install-dialog.component.html | 14 +++++---- .../iot-hub-install-dialog.component.ts | 18 ++++++----- 4 files changed, 56 insertions(+), 21 deletions(-) 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 index cdeb9c06af..352d4d4e17 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -150,7 +150,6 @@ import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -183,6 +182,7 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_REPORTED_CONFLICTS = 10; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -338,7 +338,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities)); + conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, + entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -427,10 +428,13 @@ public class DefaultSolutionService implements SolutionService { * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List entities) { + private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", "))) - .append(System.lineSeparator()); + .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { + details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + } + details.append(System.lineSeparator()); } private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d89012057b..d28955e742 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.id.TenantId; @@ -46,6 +47,8 @@ import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; @@ -88,7 +91,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionNamesEveryConflictingEntity() throws IOException { writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); - writeEntitiesFile("assets.json", "[{\"name\": \"New asset\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); Customer customer = new Customer(); customer.setTitle("Existing customer"); @@ -96,6 +99,9 @@ class DefaultSolutionServiceTest { device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); @@ -108,6 +114,7 @@ class DefaultSolutionServiceTest { .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported assertThat(result.getDetails()) @@ -220,6 +227,25 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } + @Test + void testValidateSolutionCapsTheNamesItLists() throws IOException { + String definitions = IntStream.rangeClosed(1, 12) + .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") + .collect(Collectors.joining(",")); + writeEntitiesFile("devices.json", "[" + definitions + "]"); + for (int i = 1; i <= 12; i++) { + Device device = new Device(); + device.setName("Sensor " + i); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + } + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getDetails().lines().toList()) + .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " + + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + } + @Test void testValidateSolutionWithoutConflicts() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); @@ -231,7 +257,8 @@ class DefaultSolutionServiceTest { @Test void testValidateSolutionWithoutEntityFiles() { assertThat(service.validateSolution(tenantId, tempDir)).isNull(); - verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); } private void writeFile(String relativePath, String content) throws IOException { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index 25c5ca2089..d267ccf57e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -141,12 +141,14 @@ @case ('error') {

{{ 'iot-hub.install-error-title' | translate }}

{{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

- @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
- {{ errorMessage }} -
+ @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
+ {{ errorMessage }} +
+ } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index f777a4da31..5fe6879e5e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage ?? ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -331,18 +331,19 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -354,7 +355,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - message += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial'); + const warning = this.translate.instant('iot-hub.install-rollback-partial'); + message = message ? message + '\n\n' + warning : warning; } this.errorMessage = message; return; From 79e1a9ff77dca592fb12085dbd313285137cef53 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 12:54:04 +0300 Subject: [PATCH 06/12] address the second PE review pass on the install report - rename the cap to MAX_LISTED_NAMES_PER_TYPE: it shortens the printed list, it does not limit what is validated - say how many conflicts a type has in total, and add a note when names were left out, so the "rename or delete them" instruction stays true - keep only the names in the conflict map, the entities were never read for anything else - one way of saying "there are no details" in the dialog, and one comment instead of two that open the same way - cover the whole branch of the cap (10, 11 and 12 names) and the profile name that comes from both the json file and the directory --- .../solutions/DefaultSolutionService.java | 36 ++++++---- .../solutions/DefaultSolutionServiceTest.java | 71 ++++++++++++++----- .../iot-hub-install-dialog.component.ts | 17 +++-- 3 files changed, 82 insertions(+), 42 deletions(-) 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 index 352d4d4e17..d8ec610c58 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -182,7 +182,9 @@ public class DefaultSolutionService implements SolutionService { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; private static final String RANDOM_PLACEHOLDER = "$random"; - private static final int MAX_REPORTED_CONFLICTS = 10; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -321,7 +323,7 @@ public class DefaultSolutionService implements SolutionService { }); // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. - Map> conflicts = new LinkedHashMap<>(); + Map> conflicts = new LinkedHashMap<>(); collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); @@ -338,8 +340,11 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, - entities.stream().map(entity -> "'" + entity.getName() + "'").toList())); + conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, + names.stream().map(name -> "'" + name + "'").toList())); + if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); solutionInstallResponse.setSuccess(false); @@ -351,7 +356,7 @@ public class DefaultSolutionService implements SolutionService { * The entity type and the name both come from the definition, so a list can not end up checked against the * wrong type by mistake. */ - private void collectConflicts(Map> conflicts, List definitions, + private void collectConflicts(Map> conflicts, List definitions, Function lookup) { Set checked = new HashSet<>(); for (EntityDefinition definition : definitions) { @@ -361,7 +366,7 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, Function nameExtractor, Function lookup) { Set checked = new HashSet<>(); for (T definition : definitions) { @@ -372,14 +377,14 @@ public class DefaultSolutionService implements SolutionService { } } - private void collectConflict(Map> conflicts, EntityType entityType, String name, + private void collectConflict(Map> conflicts, EntityType entityType, String name, Function lookup) { if (StringUtils.isEmpty(name)) { return; } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); } } @@ -387,7 +392,7 @@ public class DefaultSolutionService implements SolutionService { * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. */ - private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, List definitions) { Set checked = new HashSet<>(); for (ReferenceableEntityDefinition definition : definitions) { @@ -426,13 +431,16 @@ public class DefaultSolutionService implements SolutionService { /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, - * instead of the same sentence repeated for every type. + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. */ - private void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { details.append("- **").append(entityType.getNormalName()).append("**: ") - .append(conflictDescriptions.stream().limit(MAX_REPORTED_CONFLICTS).collect(Collectors.joining(", "))); - if (conflictDescriptions.size() > MAX_REPORTED_CONFLICTS) { - details.append(" and ").append(conflictDescriptions.size() - MAX_REPORTED_CONFLICTS).append(" more"); + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); } details.append(System.lineSeparator()); } diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d28955e742..b1b5f1726a 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -18,6 +18,8 @@ package org.thingsboard.server.service.solutions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -61,6 +63,10 @@ class DefaultSolutionServiceTest { private static final String CONFLICTS_INTRO = "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); @@ -95,15 +101,14 @@ class DefaultSolutionServiceTest { Customer customer = new Customer(); customer.setTitle("Existing customer"); - Device device = new Device(); - device.setName("Existing device"); when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); Asset asset = new Asset(); asset.setName("Existing asset"); when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -184,9 +189,7 @@ class DefaultSolutionServiceTest { void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); - Device device = new Device(); - device.setName("Sensor"); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); @@ -227,23 +230,47 @@ class DefaultSolutionServiceTest { verifyNoInteractions(deviceService); } - @Test - void testValidateSolutionCapsTheNamesItLists() throws IOException { - String definitions = IntStream.rangeClosed(1, 12) - .mapToObj(i -> "{\"name\": \"Sensor " + i + "\"}") - .collect(Collectors.joining(",")); - writeEntitiesFile("devices.json", "[" + definitions + "]"); - for (int i = 1; i <= 12; i++) { - Device device = new Device(); - device.setName("Sensor " + i); - when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor " + i)).thenReturn(device); + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()) - .contains("- **Device**: 'Sensor 1', 'Sensor 2', 'Sensor 3', 'Sensor 4', 'Sensor 5', 'Sensor 6', " - + "'Sensor 7', 'Sensor 8', 'Sensor 9', 'Sensor 10' and 2 more"); + assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @Test @@ -261,6 +288,12 @@ class DefaultSolutionServiceTest { deviceProfileService, assetProfileService, edgeService); } + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + private void writeFile(String relativePath, String content) throws IOException { Path file = tempDir.resolve(relativePath); Files.createDirectories(file.getParent()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 5fe6879e5e..552120b83f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -308,7 +308,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage ?? ''; + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -338,12 +338,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -355,8 +354,8 @@ export class TbIotHubInstallDialogComponent extends DialogComponent 0) { - const warning = this.translate.instant('iot-hub.install-rollback-partial'); - message = message ? message + '\n\n' + warning : warning; + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; From 27f83a1102a31e4538a092f82f6c720c1f8eead9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 13:56:22 +0300 Subject: [PATCH 07/12] name what the install still does not pre-validate The TODO predates the report and most of it is done now - customers, assets, devices, edges, dashboards, rule chains and both profile types are all checked before anything is created. What is left is the entities that still only fail at provision time. --- .../server/service/solutions/DefaultSolutionService.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index d8ec610c58..ecdb313639 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -301,7 +301,8 @@ public class DefaultSolutionService implements SolutionService { } SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - //TODO: check other entities. + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); From 99465e283cf8ee97ae722d590e191125f5b00078 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 9 Sep 2026 15:27:34 +0300 Subject: [PATCH 08/12] quote the names where the conflict is collected The map then holds what the report prints, which leaves appendConflicts a plain pass-through and matches PE, where the entity group descriptions arrive already formatted. --- .../service/solutions/DefaultSolutionService.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) 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 index ecdb313639..b279d693ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -341,9 +341,8 @@ public class DefaultSolutionService implements SolutionService { return null; } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); - conflicts.forEach((entityType, names) -> appendConflicts(details, entityType, - names.stream().map(name -> "'" + name + "'").toList())); - if (conflicts.values().stream().anyMatch(names -> names.size() > MAX_LISTED_NAMES_PER_TYPE)) { + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } @@ -385,7 +384,7 @@ public class DefaultSolutionService implements SolutionService { } HasName existing = lookup.apply(name); if (existing != null) { - conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing.getName()); + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); } } @@ -430,6 +429,10 @@ public class DefaultSolutionService implements SolutionService { return title.contains(RANDOM_PLACEHOLDER); } + private static String quoted(String value) { + return "'" + value + "'"; + } + /** * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} From bd25bee271ecd9ba540022a4b840db1e0f3f059d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:42:54 +0300 Subject: [PATCH 09/12] give the validation a result type of its own validateSolution borrowed SolutionInstallResponse and used null to say that nothing conflicts, so the call site had to test two different ways of saying "go ahead". It returns a SolutionValidationResult now, built through passed() or conflictsFound(report) - the private constructor keeps the two states honest - and the install response is assembled where the install actually answers. --- .../solutions/DefaultSolutionService.java | 23 +++++--- .../data/SolutionValidationResult.java | 43 ++++++++++++++ .../solutions/DefaultSolutionServiceTest.java | 57 +++++++++---------- 3 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java 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 index b279d693ef..ad8c6a224b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -111,6 +111,7 @@ 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.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -257,9 +258,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -300,7 +301,7 @@ public class DefaultSolutionService implements SolutionService { } } - SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { //TODO: pre-validate what still only fails at provision time: customer users (unique by email), // alarm rules and calculated fields. @@ -338,7 +339,7 @@ public class DefaultSolutionService implements SolutionService { collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); if (conflicts.isEmpty()) { - return null; + return SolutionValidationResult.passed(); } StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); @@ -346,10 +347,14 @@ public class DefaultSolutionService implements SolutionService { details.append(System.lineSeparator()).append(TRUNCATION_NOTE); } - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(details.toString()); - return solutionInstallResponse; + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; } /** diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..407290e487 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,43 @@ +/** + * 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.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index b1b5f1726a..860a6d3a0c 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -41,7 +41,7 @@ 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.rule.RuleChainService; -import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import java.io.IOException; import java.nio.file.Files; @@ -111,18 +111,17 @@ class DefaultSolutionServiceTest { .thenReturn(existingDevice("Existing device")); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.isSuccess()).isFalse(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence( CONFLICTS_INTRO, "- **Customer**: 'Existing customer'", "- **Asset**: 'Existing asset'", "- **Device**: 'Existing device'"); // the randomized customer title and the entities that do not exist yet are not reported - assertThat(result.getDetails()) + assertThat(result.getConflictReport()) .doesNotContain("Customer $random") .doesNotContain("New device") .doesNotContain("New asset"); @@ -136,10 +135,10 @@ class DefaultSolutionServiceTest { dashboard.setTitle("Overview"); when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); } @@ -153,10 +152,10 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()) + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); } @@ -176,10 +175,10 @@ class DefaultSolutionServiceTest { when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result).isNotNull(); - assertThat(result.getDetails().lines().toList()).containsSubsequence( + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( "- **Device profile**: 'thermostat'", "- **Asset profile**: 'building'", "- **Edge**: 'Main edge'"); @@ -191,9 +190,9 @@ class DefaultSolutionServiceTest { when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: 'Sensor'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); } @@ -203,7 +202,7 @@ class DefaultSolutionServiceTest { "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(ruleChainService); } @@ -217,16 +216,16 @@ class DefaultSolutionServiceTest { when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) .thenReturn(List.of(ruleChain)); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); } @Test void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { writeEntitiesFile("devices.json", "null"); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(deviceService); } @@ -240,17 +239,17 @@ class DefaultSolutionServiceTest { names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) .thenReturn(existingDevice(name))); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); int hidden = conflictCount - LISTED_NAMES_PER_TYPE; String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); - assertThat(result.getDetails().lines().toList()).contains("- **Device**: " + listed + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); if (hidden > 0) { - assertThat(result.getDetails()).contains(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); } else { - assertThat(result.getDetails()).doesNotContain(TRUNCATION_NOTE); + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); } } @@ -267,9 +266,9 @@ class DefaultSolutionServiceTest { profile.setName("Sensor profile"); when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); - SolutionInstallResponse result = service.validateSolution(tenantId, tempDir); + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); - assertThat(result.getDetails().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); } @@ -278,12 +277,12 @@ class DefaultSolutionServiceTest { writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); } @Test void testValidateSolutionWithoutEntityFiles() { - assertThat(service.validateSolution(tenantId, tempDir)).isNull(); + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, deviceProfileService, assetProfileService, edgeService); } From 63387b45b0f61a2b49a91582c44e0ac51ef12f51 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 10:54:57 +0300 Subject: [PATCH 10/12] use the SPDX license header on the new file The base branch switched every header to the SPDX form while this branch was open, so the one file this branch adds was the only one left with the old block comment. --- .../data/SolutionValidationResult.java | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java index 407290e487..4b6b07c54b 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -1,18 +1,5 @@ -/** - * 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. - */ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.solutions.data; import lombok.AccessLevel; From 04feee5c87f0bfd9e032e20fe2fa21113f5876bb Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:07:24 +0300 Subject: [PATCH 11/12] use the SPDX license header on the new test class The base switched every header to the SPDX form yesterday, so the files this branch adds were the only ones left with the old block comment and license:check failed on them once the base was merged in. --- .../server/service/solutions/DefaultSolutionServiceTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index 860a6d3a0c..d34798fe14 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,3 +1,5 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 /** * Copyright © 2016-2026 The Thingsboard Authors * From 5887f01bb362c104db086c5983a3ad5e72141b87 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 11 Sep 2026 11:12:39 +0300 Subject: [PATCH 12/12] drop the old license block left under the SPDX header license:format prepends the header it expects without recognising the block comment the files were created with, so both new files carried the license twice. They now have only the two SPDX lines, the same as every other file that this repository shares with CE. --- .../solutions/DefaultSolutionServiceTest.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java index d34798fe14..d65868a7fb 100644 --- a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -1,20 +1,5 @@ // SPDX-FileCopyrightText: Copyright The Thingsboard Authors // SPDX-License-Identifier: Apache-2.0 -/** - * 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 org.junit.jupiter.api.Test;