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 43828a4891..b480afae0e 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 @@ -184,7 +184,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; @@ -323,7 +325,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)); @@ -340,8 +342,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); @@ -353,7 +358,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) { @@ -363,7 +368,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) { @@ -374,14 +379,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()); } } @@ -389,7 +394,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) { @@ -428,13 +433,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 3198d8ff28..62865a2455 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 @@ -314,7 +314,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); @@ -344,12 +344,11 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; if (failedDependency) { @@ -361,8 +360,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;