Browse Source

Merge remote-tracking branch 'origin/hotfix-4.4' into internal-hotfix-4.4

pull/16844/head
Viacheslav Klimov 3 weeks ago
parent
commit
bf2b5e2e82
Failed to extract signature
  1. 42
      .github/workflows/check-license-headers.yml
  2. 16
      application/pom.xml
  3. 2
      application/src/main/data/json/system/widget_types/basic_gpio_control.json
  4. 2
      application/src/main/data/json/system/widget_types/raspberry_pi_gpio_control.json
  5. 10
      application/src/main/java/org/thingsboard/server/controller/AiResourceController.java
  6. 13
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  7. 7
      application/src/main/java/org/thingsboard/server/controller/BlobEntityController.java
  8. 7
      application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
  9. 8
      application/src/main/java/org/thingsboard/server/controller/ImageController.java
  10. 4
      application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java
  11. 9
      application/src/main/java/org/thingsboard/server/controller/ReportController.java
  12. 10
      application/src/main/java/org/thingsboard/server/controller/TbResourceController.java
  13. 7
      application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
  14. 28
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  15. 11
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  16. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
  17. 4
      application/src/main/java/org/thingsboard/server/service/queue/DefaultTbEdgeConsumerService.java
  18. 42
      application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
  19. 50
      application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java
  20. 17
      application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
  21. 130
      application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java
  22. 97
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  23. 32
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  24. 7
      check-license-headers.sh
  25. 2
      common/cluster-api/pom.xml
  26. 11
      common/dao-api/pom.xml
  27. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaMultiPageResultSet.java
  28. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaSession.java
  29. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaSessionBuilder.java
  30. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/nosql/TbResultSet.java
  31. 4
      common/data/pom.xml
  32. 4
      common/edge-api/pom.xml
  33. 3
      common/integration/aws-integrations/src/main/java/org/thingsboard/integration/aws/kinesis/KinesisPollingConfig.java
  34. 4
      common/proto/pom.xml
  35. 2
      common/queue/src/main/java/org/thingsboard/server/queue/settings/TbQueueIntegrationExecutorSettings.java
  36. 9
      common/transport/http/src/main/java/org/thingsboard/server/transport/http/DeviceApiController.java
  37. 35
      common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java
  38. 4
      dao/pom.xml
  39. 4
      dao/src/main/java/org/thingsboard/server/dao/subscription/BasicLicenseActivationService.java
  40. 32
      pom.xml
  41. 4
      rule-engine/rule-engine-api/pom.xml
  42. 2
      rule-engine/rule-engine-components/pom.xml
  43. 2
      rule-engine/rule-engine-components/src/main/resources/public/static/rulenode/twilio-config.js
  44. 41
      tools/src/main/python/license-headers/README.md
  45. 555
      tools/src/main/python/license-headers/check_license_headers.py
  46. 6
      tools/src/main/python/license-headers/curations.json
  47. 682
      tools/src/main/python/license-headers/test_check_license_headers.py
  48. 1
      ui-ngx/package.json
  49. 2
      ui-ngx/src/app/core/core.state.ts
  50. 63
      ui-ngx/src/app/core/guards/auth.guard.ts
  51. 9
      ui-ngx/src/app/core/services/menu.service.ts
  52. 4
      ui-ngx/src/app/core/utils.ts
  53. 3
      ui-ngx/src/app/modules/home/components/converter/converter-dialog.component.html
  54. 2
      ui-ngx/src/app/modules/home/components/converter/converter-dialog.component.ts
  55. 21
      ui-ngx/src/app/modules/home/components/converter/converter.component.ts
  56. 14
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-image-dialog.component.html
  57. 5
      ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-image-dialog.component.scss
  58. 14
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  59. 33
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  60. 180
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  61. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  62. 30
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html
  63. 32
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss
  64. 9
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts
  65. 1
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  66. 9
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  67. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  68. 12
      ui-ngx/src/app/modules/home/components/notification/notification-bell.component.html
  69. 33
      ui-ngx/src/app/modules/home/components/notification/notification-bell.component.ts
  70. 2
      ui-ngx/src/app/modules/home/components/router-tabs.component.html
  71. 28
      ui-ngx/src/app/modules/home/components/router-tabs.component.ts
  72. 2
      ui-ngx/src/app/modules/home/components/rule-node/action/gps-geo-action-config.component.html
  73. 4
      ui-ngx/src/app/modules/home/pages/notification/notification-routing.module.ts
  74. 16
      ui-ngx/src/app/modules/home/pages/notification/rule/rule-notification-dialog.component.ts
  75. 40
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-setting-form.component.html
  76. 4
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-setting-form.component.ts
  77. 2
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings-routing.modules.ts
  78. 54
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.html
  79. 36
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.scss
  80. 99
      ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts
  81. 21
      ui-ngx/src/app/modules/home/pages/notification/template/template-notification-dialog.component.ts
  82. 2
      ui-ngx/src/app/shared/components/dashboard-select-panel.component.html
  83. 2
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  84. 6
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  85. 46
      ui-ngx/src/app/shared/models/notification.models.ts
  86. 11003
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  87. 15600
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  88. 21
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  89. 4
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  90. 12
      ui-ngx/yarn.lock

42
.github/workflows/check-license-headers.yml

@ -48,10 +48,50 @@ jobs:
java-version: 21
cache: maven
# Header-free CE contents from earlier runs. A pull request reads the cache of its base branch, then of master.
# What keeps a pull request from feeding the cache that other runs trust is GitHub's cache scoping, not the `if:`
# on the save step: a pull request runs its own copy of this workflow, and whatever it saved would be restorable
# only by that pull request. The `if:` keeps pull requests from spending the repository's cache storage.
- name: Restore normalized CE contents
id: restore-cache
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: target/license-headers-cache
key: license-headers-ce-v1-${{ github.ref_name }}-${{ github.run_id }}
restore-keys: |
license-headers-ce-v1-${{ github.base_ref || github.ref_name }}-
license-headers-ce-v1-
# What the restore brought, to save the cache below only when this run changed it. A run that only reads the
# cache leaves its bytes as they were; the check needs no marker for this.
- name: Fingerprint restored CE contents
id: cache-fingerprint
if: github.event_name != 'pull_request'
run: echo "hash=${{ hashFiles('target/license-headers-cache/*.sqlite') }}" >> "$GITHUB_OUTPUT"
- name: Check license headers
env:
# Pull requests check only the files they change; pushes and manual runs check every file.
SINCE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || '' }}
run: |
mkdir -p target/license-provenance
./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log
# The runner does nothing else: use every CPU, not all but one as on a workstation.
LICENSE_HEADERS_JOBS="$(nproc)"
export LICENSE_HEADERS_JOBS
# A run uses the cache of one signature; older ones would only make every save and restore larger.
export LICENSE_HEADERS_CACHE_SIGNATURES=1
./check-license-headers.sh ${SINCE:+--since "$SINCE"} 2>&1 | tee target/license-provenance/console.log
# Saved even when the check finds problems, but only when the run changed the cache: it normalized something
# the cache lacked, or it pruned the databases of other signatures.
- name: Save normalized CE contents
if: >-
always() && github.event_name != 'pull_request'
&& hashFiles('target/license-headers-cache/*.sqlite') != steps.cache-fingerprint.outputs.hash
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: target/license-headers-cache
key: ${{ steps.restore-cache.outputs.cache-primary-key }}
- name: Add findings to the job summary
if: failure() && hashFiles('target/license-provenance/console.log') != ''

16
application/pom.xml

@ -463,35 +463,35 @@
<artifactId>rocksdbjni</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-azure-open-ai</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-google-genai</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-mistral-ai</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-anthropic</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bedrock</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-official</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-ollama</artifactId>
</dependency>
<dependency>

2
application/src/main/data/json/system/widget_types/basic_gpio_control.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/raspberry_pi_gpio_control.json

File diff suppressed because one or more lines are too long

10
application/src/main/java/org/thingsboard/server/controller/AiResourceController.java

@ -5,7 +5,6 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@ -27,7 +26,6 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.resource.AiResourceService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.UUID;
@ -64,18 +62,12 @@ class AiResourceController extends BaseController {
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(content.mediaType()))
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name()))
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(content.name()))
.header("X-Content-Type-Options", "nosniff")
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate())
.body(content.data());
}
private static String disposition(String name) {
ContentDisposition.Builder builder = ContentDisposition.attachment();
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name);
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString();
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@DeleteMapping("/{resourceId}")
@ResponseStatus(HttpStatus.NO_CONTENT)

13
application/src/main/java/org/thingsboard/server/controller/BaseController.java

@ -15,6 +15,7 @@ import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@ -27,6 +28,7 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
import org.thingsboard.common.util.DonAsynchron;
import org.thingsboard.common.util.JacksonUtil;
@ -1760,4 +1762,15 @@ public abstract class BaseController {
return oAuth2ClientIds;
}
protected static String toContentDisposition(String fileName) {
ContentDisposition.Builder builder = ContentDisposition.attachment();
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(fileName);
return (ascii ? builder.filename(fileName) : builder.filename(fileName, StandardCharsets.UTF_8)).build().toString();
}
protected static String getFileName(MultipartFile file) {
String fileName = file.getOriginalFilename();
return fileName != null ? fileName.replace("%22", "\"") : null;
}
}

7
application/src/main/java/org/thingsboard/server/controller/BlobEntityController.java

@ -8,7 +8,6 @@ import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -37,7 +36,6 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.blob.TbBlobService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -103,11 +101,8 @@ public class BlobEntityController extends BaseController {
BlobEntityId blobEntityId = new BlobEntityId(toUUID(strBlobEntityId));
BlobEntity blobEntity = checkBlobEntityId(blobEntityId, Operation.READ);
ByteArrayResource resource = new ByteArrayResource(blobEntity.getData().array());
ContentDisposition cd = ContentDisposition.attachment()
.filename(blobEntity.getName(), StandardCharsets.UTF_8)
.build();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(blobEntity.getName()))
.header("x-filename", blobEntity.getName())
.contentLength(resource.contentLength())
.contentType(parseMediaType(blobEntity.getContentType()))

7
application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java

@ -9,7 +9,6 @@ import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@ -41,7 +40,6 @@ import org.thingsboard.server.service.security.model.token.AccessJwtToken;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.utils.MiscUtils;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;
@ -153,11 +151,8 @@ public class DashboardReportController extends BaseController {
private Consumer<DashboardReportData> onSuccess(DeferredResult<ResponseEntity<Resource>> result) {
return reportData -> {
ByteArrayResource resource = new ByteArrayResource(reportData.getData());
ContentDisposition cd = ContentDisposition.attachment()
.filename(reportData.getName(), StandardCharsets.UTF_8)
.build();
ResponseEntity<Resource> response = ResponseEntity.ok().
header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(reportData.getName()))
.header("x-filename", reportData.getName())
.contentLength(resource.contentLength())
.contentType(parseMediaType(reportData.getContentType()))

8
application/src/main/java/org/thingsboard/server/controller/ImageController.java

@ -98,11 +98,11 @@ public class ImageController extends BaseController {
image.setCustomerId(user.getCustomerId());
resourceValidator.validateResourceSize(user.getTenantId(), null, file.getSize());
image.setFileName(file.getOriginalFilename());
image.setFileName(getFileName(file));
if (StringUtils.isNotEmpty(title)) {
image.setTitle(title);
} else {
image.setTitle(file.getOriginalFilename());
image.setTitle(getFileName(file));
}
ResourceSubType subType = ResourceSubType.IMAGE;
@ -132,7 +132,7 @@ public class ImageController extends BaseController {
TbResource image = new TbResource(imageInfo);
image.setData(file.getBytes());
image.setFileName(file.getOriginalFilename());
image.setFileName(getFileName(file));
image.updateDescriptor(ImageDescriptor.class, descriptor -> {
descriptor.setMediaType(file.getContentType());
return descriptor;
@ -333,7 +333,7 @@ public class ImageController extends BaseController {
.eTag(descriptor.getEtag());
if (!cacheKey.isPublic()) {
result
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(fileName))
.header("x-filename", fileName);
}
if (systemImagesBrowserTtlInMinutes > 0 && imageInfo.getTenantId().isSysTenantId()) {

4
application/src/main/java/org/thingsboard/server/controller/OtaPackageController.java

@ -82,7 +82,7 @@ public class OtaPackageController extends BaseController {
ByteArrayResource resource = new ByteArrayResource(otaPackage.getData().array());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + otaPackage.getFileName())
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(otaPackage.getFileName()))
.header("x-filename", otaPackage.getFileName())
.contentLength(resource.contentLength())
.contentType(parseMediaType(otaPackage.getContentType()))
@ -149,7 +149,7 @@ public class OtaPackageController extends BaseController {
ChecksumAlgorithm checksumAlgorithm = ChecksumAlgorithm.valueOf(checksumAlgorithmStr.toUpperCase());
byte[] data = file.getBytes();
return tbOtaPackageService.saveOtaPackageData(otaPackageInfo, checksum, checksumAlgorithm,
data, file.getOriginalFilename(), file.getContentType(), getCurrentUser());
data, getFileName(file), file.getContentType(), getCurrentUser());
}
@ApiOperation(value = "Get OTA Package Infos (getOtaPackages)",

9
application/src/main/java/org/thingsboard/server/controller/ReportController.java

@ -10,7 +10,6 @@ import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.EntityType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@ -57,7 +56,6 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.AccessJwtToken;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@ -277,7 +275,7 @@ public class ReportController extends BaseController {
ReportData reportData = future.get(timeoutMs, TimeUnit.MILLISECONDS);
ByteArrayResource resource = new ByteArrayResource(reportData.getData());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + reportData.getName() + "\"")
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(reportData.getName()))
.header("x-filename", reportData.getName())
.contentLength(resource.contentLength())
.contentType(MediaType.parseMediaType(reportData.getContentType()))
@ -342,11 +340,8 @@ public class ReportController extends BaseController {
private ResponseEntity<ByteArrayResource> buildDownloadResponse(byte[] data, String name, String contentType) {
ByteArrayResource resource = new ByteArrayResource(data);
ContentDisposition cd = ContentDisposition.attachment()
.filename(name, StandardCharsets.UTF_8)
.build();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(name))
.header("x-filename", name)
.contentLength(resource.contentLength())
.header("Content-Type", contentType)

10
application/src/main/java/org/thingsboard/server/controller/TbResourceController.java

@ -101,7 +101,7 @@ public class TbResourceController extends BaseController {
ByteArrayResource resource = new ByteArrayResource(tbResource.getData());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + tbResource.getFileName())
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(tbResource.getFileName()))
.header("x-filename", tbResource.getFileName())
.contentLength(resource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
@ -237,7 +237,7 @@ public class TbResourceController extends BaseController {
@RequestPart MultipartFile file) throws Exception {
TbResource resource = new TbResource();
resource.setTenantId(getTenantId());
resource.setTitle(StringUtils.isNotEmpty(title) ? title : file.getOriginalFilename());
resource.setTitle(StringUtils.isNotEmpty(title) ? title : getFileName(file));
ResourceType resourceType = ResourceType.valueOf(resourceTypeStr);
resource.setResourceType(resourceType);
@ -251,7 +251,7 @@ public class TbResourceController extends BaseController {
if (StringUtils.isNotEmpty(resourceSubTypeStr)) {
resource.setResourceSubType(ResourceSubType.valueOf(resourceSubTypeStr));
}
resource.setFileName(file.getOriginalFilename());
resource.setFileName(getFileName(file));
resource.setData(file.getBytes());
checkEntity(resource.getId(), resource, Resource.TB_RESOURCE);
@ -266,7 +266,7 @@ public class TbResourceController extends BaseController {
@RequestPart MultipartFile file) throws Exception {
TbResourceId tbResourceId = new TbResourceId(id);
TbResource resource = checkResourceId(tbResourceId, Operation.WRITE);
resource.setFileName(file.getOriginalFilename());
resource.setFileName(getFileName(file));
resource.setData(file.getBytes());
return tbResourceService.save(resource, getCurrentUser());
}
@ -452,7 +452,7 @@ public class TbResourceController extends BaseController {
byte[] data = resourceService.getResourceData(resourceInfo.getTenantId(), resourceInfo.getId());
ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + resourceInfo.getFileName())
.header(HttpHeaders.CONTENT_DISPOSITION, toContentDisposition(resourceInfo.getFileName()))
.header("x-filename", resourceInfo.getFileName())
.contentLength(resource.contentLength())
.header("Content-Type", resourceInfo.getResourceType().getMediaType())

7
application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java

@ -72,10 +72,10 @@ public class AlarmRuleState {
public AlarmEvalResult reeval(long ts, CalculatedFieldCtx ctx) { // on scheduled duration check or periodic re-eval for rules with schedule
boolean active = isActive(ts);
boolean activeChanged = this.active == null || active != this.active;
this.active = active;
switch (condition.getType()) {
case SIMPLE, REPEATING -> {
boolean activeChanged = this.active == null || active != this.active;
this.active = active;
if (!active) {
return AlarmEvalResult.EMPTY;
}
@ -94,6 +94,9 @@ public class AlarmRuleState {
if (!active) {
return AlarmEvalResult.FALSE;
}
if (firstEventTs <= 0 && condition.hasSchedule() && activeChanged) {
return doEval(false, ctx);
}
long requiredDuration = getRequiredDurationInMs();
if (requiredDuration > 0 && firstEventTs > 0 && ts > firstEventTs) {
duration = ts - firstEventTs;

28
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

@ -177,8 +177,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
validateIntegrations(tenantId, request);
applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo));
} catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName);
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey);
} catch (RestClientException e) {
log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e);
return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null);
@ -209,14 +209,14 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
throw new IllegalArgumentException("The update has no steps");
}
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor());
Set<String> stateKeys = new HashSet<>();
// A form's values are saved under its key too, so an entity step may not share it
Set<String> stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>();
for (DeviceUpdateRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
throw new IllegalArgumentException("Invalid update step: " + step.getName());
}
// The key of the step's install state
if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) {
throw new IllegalArgumentException("Duplicate update step: " + step.getName());
if (!stateKeys.add(step.stateKey())) {
throw new IllegalArgumentException("Duplicate update step: " + step.stateKey());
}
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
switch (step.getAction()) {
@ -267,9 +267,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} catch (ExecutionException e) {
// What the integration reports, e.g. wrong credentials, is what the user has to fix
Throwable cause = e.getCause() != null ? e.getCause() : e;
throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause));
throw new StepFailure(step.stateKey(), new IllegalArgumentException(cause.getMessage(), cause));
} catch (TimeoutException e) {
throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration"));
throw new StepFailure(step.stateKey(), new IllegalStateException("Timeout to validate the integration configuration"));
}
}
}
@ -308,7 +308,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
StepResult result = applyStep(tenantId, step, entity);
ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.getName(), output);
outputs.put(step.stateKey(), output);
ObjectNode state = JacksonUtil.newObjectNode();
state.set("entityOutput", output);
// The package's own entity stays the package's, whatever the request says, so later versions update it
@ -328,7 +328,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if (metadata != null) {
state.set("metadata", metadata);
}
installState.put(step.getId() != null ? step.getId() : step.getName(), state);
installState.put(step.stateKey(), state);
// As at install, an entity used as it was is listed too, so a delete removes the metadata entries the
// package added to it; usedExistingEntityIds keeps it the user's
if (!stepEntityIds.contains(result.entityId())) {
@ -350,7 +350,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} catch (StepFailure e) {
throw e;
} catch (Exception e) {
throw new StepFailure(step.getName(), e);
throw new StepFailure(step.stateKey(), e);
}
}
@ -989,11 +989,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */
private static class StepFailure extends RuntimeException {
private final String stepName;
private final String stepKey;
StepFailure(String stepName, Throwable cause) {
StepFailure(String stepKey, Throwable cause) {
super(cause.getMessage(), cause);
this.stepName = stepName;
this.stepKey = stepKey;
}
}

11
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -38,7 +38,8 @@ public class DeviceUpdateRequest {
@Data
public static class Step {
private String name;
// The package step's id, which keys its install state; the name when not set
// The package step's stable id, so that a next version can rename the step. It is also the step's install state
// key when set, which the default converter update relies on to write the state back under the stored key
private String id;
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
@ -66,6 +67,14 @@ public class DeviceUpdateRequest {
private JsonNode metadata;
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
private boolean defaultConverter;
/**
* The key of the step's install state: its id, or else its type and name, so that two steps of an install
* method never share it. The install wizard keys the steps of an install the same way.
*/
public String stateKey() {
return id != null ? id : type + ":" + name;
}
}
}

4
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java

@ -12,7 +12,7 @@ import java.util.Map;
/**
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep
* names the step that failed, if one did.
* is the install state key of the step that failed, if one did.
*/
@Data
@NoArgsConstructor
@ -23,7 +23,7 @@ public class DeviceUpdateResult {
private String errorMessage;
private String failedStep;
private DeviceInstalledItemDescriptor descriptor;
// By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
// By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {

4
application/src/main/java/org/thingsboard/server/service/queue/DefaultTbEdgeConsumerService.java

@ -7,6 +7,8 @@ import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
@ -43,8 +45,6 @@ import org.thingsboard.server.service.edge.rpc.EdgeRpcService;
import org.thingsboard.server.service.queue.processing.AbstractConsumerService;
import org.thingsboard.server.service.queue.processing.IdMsgPair;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

42
application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java

@ -905,6 +905,48 @@ public class AlarmRulesTest extends AbstractControllerTest {
});
}
@Test
public void testCreateAlarm_durationCondition_scheduleStarted() throws Exception {
Argument motionDetectedArgument = new Argument();
motionDetectedArgument.setRefEntityKey(new ReferencedEntityKey("motionDetected", ArgumentType.TS_LATEST, null));
motionDetectedArgument.setDefaultValue("false");
Map<String, Argument> arguments = Map.of(
"motionDetected", motionDetectedArgument
);
SpecificTimeSchedule schedule = new SpecificTimeSchedule();
schedule.setTimezone(ZoneId.systemDefault().getId());
schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7));
long startsOn = Duration.between(LocalDate.now().atStartOfDay(), LocalDateTime.now())
.plus(15, ChronoUnit.SECONDS).toMillis();
schedule.setStartsOn(startsOn);
Map<AlarmSeverity, Condition> createRules = Map.of(
AlarmSeverity.CRITICAL, new Condition("return motionDetected == true;", null, null,
new AlarmConditionValue<>(1000L, null),
new AlarmConditionValue<>(schedule, null))
);
AlarmRuleDefinition alarmRule = createAlarmRule(deviceId, "Motion detected alarm",
arguments, createRules, null);
postTelemetry(deviceId, "{\"motionDetected\":true}");
Thread.sleep(10000);
assertThat(getLatestAlarmResult(alarmRule.getId())).isNull();
// no new telemetry after the schedule window opens, so the stored value must be used
await().atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> {
CalculatedFieldDebugEvent debugEvent = getDebugEvents(alarmRule.getId(), 5).stream()
.filter(event -> event.getResult() != null)
.findFirst().orElse(null);
assertThat(debugEvent).isNotNull();
TbAlarmResult alarmResult = JacksonUtil.fromString(debugEvent.getResult(), TbAlarmResult.class);
assertThat(alarmResult.isCreated()).isTrue();
assertThat(alarmResult.getAlarm().getSeverity()).isEqualTo(AlarmSeverity.CRITICAL);
assertThat(alarmResult.getAlarm().getStatus()).isEqualTo(AlarmStatus.ACTIVE_UNACK);
});
}
@Test
public void testManualClearAlarm() throws Exception {
Argument temperatureArgument = new Argument();

50
application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java

@ -9,8 +9,11 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.ImageDescriptor;
@ -26,10 +29,13 @@ import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.sql.resource.TbResourceRepository;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
@ -296,6 +302,38 @@ public class ImageControllerTest extends AbstractControllerTest {
assertThat(downloadPublicImage(imageInfo.getPublicResourceKey())).containsExactly(PNG_IMAGE);
}
@Test
public void testDownloadImageWithSpecialCharactersInFileName() throws Exception {
Map<String, String> expectedHeaders = Map.of(
"Baker Street, 221B.png", "attachment; filename=\"Baker Street, 221B.png\"",
"\"Baker Street\", 221B.png", "attachment; filename=\"\\\"Baker Street\\\", 221B.png\"",
"Хрещатик, 22.png", "attachment; filename=\"=?UTF-8?Q?=D0=A5=D1=80=D0=B5=D1=89=D0=B0=D1=82=D0=B8=D0=BA,_22.png?=\"; " +
"filename*=UTF-8''%D0%A5%D1%80%D0%B5%D1%89%D0%B0%D1%82%D0%B8%D0%BA%2C%2022.png"
);
for (Map.Entry<String, String> entry : expectedHeaders.entrySet()) {
TbResourceInfo imageInfo = uploadImage(HttpMethod.POST, "/api/image", entry.getKey(), "image/png", PNG_IMAGE);
for (String url : List.of("/api/images/tenant/{key}", "/api/images/tenant/{key}/preview")) {
String contentDisposition = downloadImageContentDisposition(url, imageInfo.getResourceKey());
assertThat(contentDisposition).as(entry.getKey()).isEqualTo(entry.getValue());
}
}
}
@Test
public void testUploadImageWithEncodedQuotesInFileName() throws Exception {
TbResourceInfo imageInfo = uploadImage(HttpMethod.POST, "/api/image", "%22Baker Street%22, 221B.png", "image/png", PNG_IMAGE);
assertThat(imageInfo.getFileName()).isEqualTo("\"Baker Street\", 221B.png");
assertThat(imageInfo.getTitle()).isEqualTo("\"Baker Street\", 221B.png");
assertThat(imageInfo.getResourceKey()).isEqualTo("\"Baker Street\", 221B.png");
doGet("/api/images/tenant/{key}", imageInfo.getResourceKey()).andExpect(status().isOk());
doGet("/api/images/tenant/{key}/preview", imageInfo.getResourceKey()).andExpect(status().isOk());
}
@Test
public void testMakeImagePublic() throws Exception {
String filename = "my_public_image.png";
@ -425,4 +463,16 @@ public class ImageControllerTest extends AbstractControllerTest {
.andReturn().getResponse().getContentAsByteArray();
}
private String downloadImageContentDisposition(String urlTemplate, String key) throws Exception {
MockHttpServletRequestBuilder request = get(urlTemplate, key).characterEncoding(StandardCharsets.UTF_8);
setJwtToken(request);
MockHttpServletResponse response = mockMvc.perform(request)
.andExpect(status().isOk())
.andReturn().getResponse();
assertThat(response.getContentAsByteArray()).isNotEmpty();
List<String> headers = response.getHeaders(HttpHeaders.CONTENT_DISPOSITION);
assertThat(headers).hasSize(1);
return headers.get(0);
}
}

17
application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java

@ -44,6 +44,7 @@ import org.thingsboard.server.common.data.widget.WidgetTypeDetails;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.exception.DataValidationException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
@ -1209,6 +1210,22 @@ public class TbResourceControllerTest extends AbstractControllerTest {
return new TbResourceInfo(save(resource));
}
@Test
public void testUploadResourceWithEncodedQuotesInFileName() throws Exception {
TbResource resource = new TbResource();
resource.setResourceType(ResourceType.JS_MODULE);
resource.setFileName("%22Baker Street%22, 221B.js");
resource.setData("export const value = 1;".getBytes(StandardCharsets.UTF_8));
TbResourceInfo savedResource = save(resource);
assertThat(savedResource.getFileName()).isEqualTo("\"Baker Street\", 221B.js");
assertThat(savedResource.getTitle()).isEqualTo("\"Baker Street\", 221B.js");
assertThat(savedResource.getResourceKey()).isEqualTo("\"Baker Street\", 221B.js");
doGet("/api/resource/js_module/tenant/{key}/info", savedResource.getResourceKey()).andExpect(status().isOk());
}
private TbResourceInfo save(TbResource tbResource) throws Exception {
byte[] data = tbResource.getData() != null ? tbResource.getData() : tbResource.getEncodedData() != null ? Base64.getDecoder().decode(tbResource.getEncodedData()) : null;
List<MockPart> parts = new ArrayList<>();

130
application/src/test/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleStateTest.java

@ -0,0 +1,130 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.cf.ctx.state.alarm;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.alarm.rule.AlarmRule;
import org.thingsboard.server.common.data.alarm.rule.condition.AlarmConditionValue;
import org.thingsboard.server.common.data.alarm.rule.condition.DurationAlarmCondition;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.AlarmConditionFilter;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.SimpleAlarmConditionExpression;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate;
import org.thingsboard.server.common.data.alarm.rule.condition.expression.predicate.NumericFilterPredicate.NumericOperation;
import org.thingsboard.server.common.data.alarm.rule.condition.schedule.SpecificTimeSchedule;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.kv.DoubleDataEntry;
import org.thingsboard.server.common.data.query.EntityKeyValueType;
import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx;
import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AlarmRuleStateTest {
private static final DeviceId DEVICE_ID = new DeviceId(UUID.fromString("5512071d-5abc-411d-a907-4cdb6539c2eb"));
// Schedule window: every day from 10:00 to 24:00 UTC
private static final long DAY_START_TS = Instant.parse("2024-01-15T00:00:00Z").toEpochMilli();
private static final long WINDOW_STARTS_ON_MS = TimeUnit.HOURS.toMillis(10);
private static final long TELEMETRY_TS = DAY_START_TS + TimeUnit.HOURS.toMillis(8);
private static final long WINDOW_OPENED_TS = DAY_START_TS + WINDOW_STARTS_ON_MS + TimeUnit.SECONDS.toMillis(1);
private static final long SHORT_DURATION_MS = TimeUnit.MINUTES.toMillis(1);
// AlarmRuleState.evalDuration() measures the duration against the wall clock, so to have a duration
// that has not elapsed yet for a telemetry ts fixed in the past, it has to be far longer than the time since then.
private static final long LONG_DURATION_MS = TimeUnit.DAYS.toMillis(365 * 1000);
private final CalculatedFieldCtx ctx = mock(CalculatedFieldCtx.class);
private AlarmCalculatedFieldState state;
@BeforeEach
void setUp() {
AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration();
configuration.setCreateRules(Map.of());
CalculatedField calculatedField = new CalculatedField();
calculatedField.setName("Test alarm");
calculatedField.setConfiguration(configuration);
when(ctx.getCalculatedField()).thenReturn(calculatedField);
when(ctx.getArgNames()).thenReturn(List.of("temperature"));
state = new AlarmCalculatedFieldState(DEVICE_ID);
state.setCtx(ctx, null);
// stored telemetry that satisfies the condition, received while the schedule window was closed
state.update(Map.of("temperature", new SingleValueArgumentEntry(TELEMETRY_TS, new DoubleDataEntry("temperature", 30.0), 1L)), ctx);
}
@Test
void testReevalDurationWithoutSchedule_doesNotStartTimerFromStoredValue() {
// re-evaluated without a new event because another rule of the same calculated field has a schedule
AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, false);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isNull();
assertThat(ruleState.getFirstEventTs()).isZero();
}
@Test
void testReevalDurationWithSchedule_whenWindowOpensAndDurationElapsed_thenTrue() {
AlarmRuleState ruleState = createRuleState(SHORT_DURATION_MS, true);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.TRUE);
assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS);
}
@Test
void testReevalDurationWithSchedule_whenWindowOpensAndDurationNotElapsed_thenTimerStarted() {
// leftDuration of the result is what AlarmCalculatedFieldState uses to schedule the next duration check
AlarmRuleState ruleState = createRuleState(LONG_DURATION_MS, true);
AlarmEvalResult result = ruleState.reeval(WINDOW_OPENED_TS, ctx);
assertThat(result.getStatus()).isEqualTo(AlarmEvalResult.Status.NOT_YET_TRUE);
assertThat(result.getLeftDuration()).isPositive();
assertThat(ruleState.getFirstEventTs()).isEqualTo(TELEMETRY_TS);
}
private AlarmRuleState createRuleState(long durationMs, boolean withSchedule) {
DurationAlarmCondition condition = new DurationAlarmCondition();
condition.setExpression(createTemperatureGreaterThanExpression(25.0));
condition.setUnit(TimeUnit.MILLISECONDS);
condition.setValue(new AlarmConditionValue<>(durationMs, null));
if (withSchedule) {
SpecificTimeSchedule schedule = new SpecificTimeSchedule();
schedule.setTimezone("UTC");
schedule.setDaysOfWeek(Set.of(1, 2, 3, 4, 5, 6, 7));
schedule.setStartsOn(WINDOW_STARTS_ON_MS);
condition.setSchedule(new AlarmConditionValue<>(schedule, null));
}
AlarmRule rule = new AlarmRule();
rule.setCondition(condition);
return new AlarmRuleState(AlarmSeverity.CRITICAL, rule, state);
}
private SimpleAlarmConditionExpression createTemperatureGreaterThanExpression(double threshold) {
AlarmConditionFilter filter = new AlarmConditionFilter();
filter.setArgument("temperature");
filter.setValueType(EntityKeyValueType.NUMERIC);
filter.setPredicates(List.of(new NumericFilterPredicate(NumericOperation.GREATER, new AlarmConditionValue<>(threshold, null))));
SimpleAlarmConditionExpression expression = new SimpleAlarmConditionExpression();
expression.setFilters(List.of(filter));
return expression;
}
}

97
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -206,7 +206,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText())
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText())
.isEqualTo(EntityChecksum.of(savedDashboard.getValue()));
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId);
}
@ -225,7 +225,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@ -245,7 +245,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview");
assertThat(descriptor.getInstallState()).containsOnlyKeys("main-dashboard");
}
@Test
@ -260,7 +260,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse();
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").has("checksum")).isFalse();
}
@Test
@ -273,7 +273,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getInstallState().get("DASHBOARD:Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId);
}
@ -289,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("use-existing");
}
@Test
@ -334,7 +334,7 @@ class DefaultDevicePackageUpdateServiceTest {
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getInstallState().get("DASHBOARD:Dashboard").get("resolution").asText()).isEqualTo("created");
}
@Test
@ -395,7 +395,7 @@ class DefaultDevicePackageUpdateServiceTest {
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
assertThat(saved.getValue()).isNotSameAs(current);
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN");
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("INTEGRATION:TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
// The entries the step added, which a delete of the package removes; not the one it removed
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
@ -450,7 +450,7 @@ class DefaultDevicePackageUpdateServiceTest {
// entries from it (DefaultIotHubServiceTest#deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas)
assertThat(descriptor.getCreatedEntityIds()).containsOnlyOnce(tenantsIntegrationId);
assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(tenantsIntegrationId);
JsonNode state = descriptor.getInstallState().get("TTN");
JsonNode state = descriptor.getInstallState().get("INTEGRATION:TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
}
@ -487,6 +487,75 @@ class DefaultDevicePackageUpdateServiceTest {
verify(installedItemService, never()).save(any(), any());
}
@Test
void twoStepsOfOneTypeAndName_areRejected() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepWithTheKeyOfAForm_isRejected() {
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setId("Settings");
DeviceUpdateRequest request = request(step);
request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10))));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepsOfOneNameAndAnotherType_eachKeepTheirOwnState() {
// Installed when the state was keyed by name: the integration's state replaced the converter's
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter converter = new Converter(converterId);
converter.setTenantId(tenantId);
converter.setName("TTN my-app");
when(converterService.findConverterById(tenantId, converterId)).thenReturn(converter);
Integration integration = new Integration(integrationId);
integration.setTenantId(tenantId);
integration.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
integration.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration);
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setCreatedEntityIds(List.of(profileId, deviceId, converterId, integrationId));
ObjectNode legacy = stateOf(integrationId, "created").put("checksum", "installed");
legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app"))));
DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
uplink.setDefaultConverter(true);
DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceUpdateRequest request = request(uplink, ttn);
request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration")));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
// The state under the name is gone: each step's is under its own key now
assertThat(state).containsOnlyKeys("Configuration", "UPLINK_CONVERTER:${integrationName}", "INTEGRATION:${integrationName}");
JsonNode converterState = state.get("UPLINK_CONVERTER:${integrationName}");
assertThat(converterState.get("entityOutput").get("id").asText()).isEqualTo(converterId.getId().toString());
assertThat(converterState.get("defaultConverter").asBoolean()).isTrue();
JsonNode integrationState = state.get("INTEGRATION:${integrationName}");
assertThat(integrationState.get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString());
assertThat(integrationState.get("checksum").asText()).isEqualTo("installed");
assertThat(integrationState.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
assertThat(result.getOutputs().get("UPLINK_CONVERTER:${integrationName}").get("id").asText()).isEqualTo(converterId.getId().toString());
assertThat(result.getOutputs().get("INTEGRATION:${integrationName}").get("id").asText()).isEqualTo(integrationId.getId().toString());
}
@Test
void failedStep_rollsBackAndReportsTheStep() {
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308"));
@ -499,7 +568,7 @@ class DefaultDevicePackageUpdateServiceTest {
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
assertThat(rolledBack).hasSize(1);
verify(installedItemService, never()).save(any(), any());
@ -515,7 +584,7 @@ class DefaultDevicePackageUpdateServiceTest {
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@ -550,7 +619,7 @@ class DefaultDevicePackageUpdateServiceTest {
// The devices keep sending to the same endpoint
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key");
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app");
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key");
assertThat(result.getOutputs().get("INTEGRATION:TTN").get("routingKey").asText()).isEqualTo("routing-key");
}
@Test
@ -579,7 +648,7 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink");
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink");
assertThat(state.get("defaultConverter").asBoolean()).isTrue();
// The other packages keep what they recorded: check() takes the checksum of any installed package
assertThat(created.get("checksum").asText()).isEqualTo("before");
@ -631,7 +700,7 @@ class DefaultDevicePackageUpdateServiceTest {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard");
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard");
}
@Test

32
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -775,6 +775,38 @@ class DefaultIotHubServiceTest {
verify(integrationService, never()).deleteIntegration(any(), any());
}
@Test
void deleteInstalledItem_devicePackageInstalledWithStateByName_deletesTheConverterWhoseStateWasReplaced() throws Exception {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
IotHubInstalledItem deleted = devicePackage(converter.getId(), integrationId);
// The converter and the integration steps shared the name: the integration's state replaced the converter's
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", "use-existing");
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", integrationId.getId().toString()));
state.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) deleted.getDescriptor();
descriptor.setInstallState(Map.of("${integrationName}", state));
descriptor.setUsedExistingEntityIds(List.of(integrationId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(integrationService.findIntegrationById(tenantId, integrationId))
.thenReturn(integration(integrationId, Map.of("profile.milesight-iot-am308", "AM308", "profile.added-by-user", "Mine")));
service.deleteInstalledItem(user, deleted.getId());
// Found by createdEntityIds, not by the install state
verify(tbConverterService).delete(converter, user);
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
verify(integrationService, never()).deleteIntegration(any(), any());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
assertThat(metadata.get("profile.added-by-user").asText()).isEqualTo("Mine");
}
@Test
void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());

7
check-license-headers.sh

@ -8,9 +8,14 @@ set -euo pipefail
usage() {
echo "Checks SPDX license headers against CE provenance."
echo "usage: $0 [--fix] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...]"
echo "usage: $0 [--fix] [--since <ref>] [--ce-ref <ref>] [--ce-remote <url>] [--output target/...] [--no-cache] [--cache <dir>]"
echo " --fix restamp files whose expected header the check determined"
echo " and remove redundant or orphaned curations"
echo " --since check only files changed since the merge base of <ref> and HEAD,"
echo " uncommitted and untracked files included, e.g. --since origin/lts-4.4;"
echo " runs the full check when CE commits, Mycila settings or the check itself changed"
echo " --no-cache normalize every CE file again instead of reusing target/license-headers-cache"
echo " --cache keep the cache in <dir> instead of target/license-headers-cache"
echo " --ce-ref CE branch, tag or commit that this branch integrates, fetched on every run;"
echo " without it, CE is the history that does not contain the relicensing commit"
echo " --ce-remote CE repository to fetch --ce-ref from (default: https://github.com/thingsboard/thingsboard.git)"

2
common/cluster-api/pom.xml

@ -76,7 +76,7 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
<scope>provided</scope>
</dependency>

11
common/dao-api/pom.xml

@ -42,6 +42,10 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
@ -76,10 +80,15 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.stephenc.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-jmx</artifactId>

2
common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaMultiPageResultSet.java

@ -10,7 +10,7 @@ import com.datastax.oss.driver.api.core.cql.Row;
import com.datastax.oss.driver.api.core.cql.Statement;
import com.datastax.oss.driver.internal.core.util.CountingIterator;
import com.datastax.oss.driver.internal.core.util.concurrent.BlockingOperation;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jspecify.annotations.NonNull;
import java.nio.ByteBuffer;
import java.util.ArrayList;

2
common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaSession.java

@ -13,7 +13,7 @@ import com.datastax.oss.driver.api.core.type.reflect.GenericType;
import com.datastax.oss.driver.internal.core.cql.DefaultPrepareRequest;
import com.datastax.oss.driver.internal.core.cql.SinglePageResultSet;
import com.google.common.util.concurrent.ListenableFuture;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jspecify.annotations.NonNull;
import java.util.concurrent.ExecutionException;

2
common/dao-api/src/main/java/org/thingsboard/server/dao/cassandra/guava/GuavaSessionBuilder.java

@ -7,7 +7,7 @@ import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
import com.datastax.oss.driver.api.core.context.DriverContext;
import com.datastax.oss.driver.api.core.session.ProgrammaticArguments;
import com.datastax.oss.driver.api.core.session.SessionBuilder;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jspecify.annotations.NonNull;
public class GuavaSessionBuilder extends SessionBuilder<GuavaSessionBuilder, GuavaSession> {

2
common/dao-api/src/main/java/org/thingsboard/server/dao/nosql/TbResultSet.java

@ -13,8 +13,8 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.jspecify.annotations.NonNull;
import java.nio.ByteBuffer;
import java.util.ArrayList;

4
common/data/pom.xml

@ -71,7 +71,7 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
<scope>test</scope>
</dependency>
@ -112,7 +112,7 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-core</artifactId>
</dependency>
</dependencies>

4
common/edge-api/pom.xml

@ -26,10 +26,6 @@
</properties>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.common</groupId>
<artifactId>data</artifactId>

3
common/integration/aws-integrations/src/main/java/org/thingsboard/integration/aws/kinesis/KinesisPollingConfig.java

@ -7,6 +7,7 @@ import software.amazon.awssdk.services.kinesis.KinesisAsyncClient;
import software.amazon.kinesis.retrieval.RecordsFetcherFactory;
import software.amazon.kinesis.retrieval.RetrievalFactory;
import software.amazon.kinesis.retrieval.RetrievalSpecificConfig;
import software.amazon.kinesis.retrieval.polling.KinesisSleepTimeController;
import software.amazon.kinesis.retrieval.polling.SimpleRecordsFetcherFactory;
import software.amazon.kinesis.retrieval.polling.SynchronousBlockingRetrievalFactory;
@ -27,6 +28,6 @@ public class KinesisPollingConfig implements RetrievalSpecificConfig {
@Override
public RetrievalFactory retrievalFactory() {
return new SynchronousBlockingRetrievalFactory(streamName, kinesisClient, recordsFetcherFactory, maxRecords, kinesisRequestTimeout, null);
return new SynchronousBlockingRetrievalFactory(streamName, kinesisClient, recordsFetcherFactory, maxRecords, kinesisRequestTimeout, null, new KinesisSleepTimeController());
}
}

4
common/proto/pom.xml

@ -26,10 +26,6 @@
</properties>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.common</groupId>
<artifactId>data</artifactId>

2
common/queue/src/main/java/org/thingsboard/server/queue/settings/TbQueueIntegrationExecutorSettings.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.queue.settings;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
@ -9,7 +10,6 @@ import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.queue.util.PropertyUtils;
import javax.annotation.PostConstruct;
import java.util.Map;
@Lazy

9
common/transport/http/src/main/java/org/thingsboard/server/transport/http/DeviceApiController.java

@ -17,6 +17,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
@ -60,6 +61,7 @@ import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcRequestMs
import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg;
import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceTokenRequestMsg;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@ -498,9 +500,12 @@ public class DeviceApiController implements TbTransportService {
} else if (title.equals(otaPackageResponseMsg.getTitle()) && version.equals(otaPackageResponseMsg.getVersion())) {
String otaPackageId = new UUID(otaPackageResponseMsg.getOtaPackageIdMSB(), otaPackageResponseMsg.getOtaPackageIdLSB()).toString();
ByteArrayResource resource = new ByteArrayResource(transportContext.getOtaPackageDataCache().get(otaPackageId, chunkSize, chunk));
String fileName = otaPackageResponseMsg.getFileName();
ContentDisposition.Builder contentDisposition = ContentDisposition.attachment();
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(fileName);
ResponseEntity<ByteArrayResource> response = ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + otaPackageResponseMsg.getFileName())
.header("x-filename", otaPackageResponseMsg.getFileName())
.header(HttpHeaders.CONTENT_DISPOSITION, (ascii ? contentDisposition.filename(fileName) : contentDisposition.filename(fileName, StandardCharsets.UTF_8)).build().toString())
.header("x-filename", fileName)
.contentLength(resource.contentLength())
.contentType(parseMediaType(otaPackageResponseMsg.getContentType()))
.body(resource);

35
common/transport/http/src/test/java/org/thingsboard/server/transport/http/DeviceApiControllerTest.java

@ -1,20 +1,27 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.transport.http;
import com.google.gson.JsonParseException;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.context.request.async.DeferredResult;
import org.thingsboard.server.cache.ota.OtaPackageDataCache;
import org.thingsboard.server.common.transport.TransportContext;
import org.thingsboard.server.gen.transport.TransportProtos;
import java.io.IOException;
import java.util.UUID;
import java.util.function.Consumer;
import static org.assertj.core.api.Assertions.assertThat;
class DeviceApiControllerTest {
@Test
@ -67,4 +74,30 @@ class DeviceApiControllerTest {
callback.onError(new RuntimeException("oops it is run time error"));
}
@Test
void getOtaPackageCallbackWithCommaInFileName() {
UUID otaPackageId = UUID.randomUUID();
OtaPackageDataCache otaPackageDataCache = Mockito.mock(OtaPackageDataCache.class);
Mockito.when(otaPackageDataCache.get(otaPackageId.toString(), 0, 0)).thenReturn(new byte[]{1, 2, 3});
TransportContext transportContext = Mockito.mock(TransportContext.class);
Mockito.when(transportContext.getOtaPackageDataCache()).thenReturn(otaPackageDataCache);
DeferredResult<ResponseEntity> responseWriter = Mockito.mock(DeferredResult.class);
var callback = new DeviceApiController.GetOtaPackageCallback(transportContext, responseWriter, "Title", "1.0", 0, 0);
callback.onSuccess(TransportProtos.GetOtaPackageResponseMsg.newBuilder()
.setResponseStatus(TransportProtos.ResponseStatus.SUCCESS)
.setOtaPackageIdMSB(otaPackageId.getMostSignificantBits())
.setOtaPackageIdLSB(otaPackageId.getLeastSignificantBits())
.setTitle("Title")
.setVersion("1.0")
.setContentType("application/octet-stream")
.setFileName("Baker Street, 221B.bin")
.build());
ArgumentCaptor<ResponseEntity> response = ArgumentCaptor.forClass(ResponseEntity.class);
Mockito.verify(responseWriter).setResult(response.capture());
assertThat(response.getValue().getHeaders().get(HttpHeaders.CONTENT_DISPOSITION))
.containsExactly("attachment; filename=\"Baker Street, 221B.bin\"");
}
}

4
dao/pom.xml

@ -144,11 +144,11 @@
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-query-builder</artifactId>
</dependency>
<dependency> <!--need for datastax-->

4
dao/src/main/java/org/thingsboard/server/dao/subscription/BasicLicenseActivationService.java

@ -2,6 +2,8 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.subscription;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
@ -31,8 +33,6 @@ import org.thingsboard.server.dao.asset.AssetService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.subscription.LicenseCapacity.CappedEntity;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;

32
pom.xml

@ -100,14 +100,14 @@
<httpclient5.version>5.6.4</httpclient5.version> <!-- to fix CVE-2026-71290. Pinned via the httpclient5 overrides below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<zstd-jni.version>1.5.7-14</zstd-jni.version> <!-- to fix CVE-2026-87795, CVE-2026-87823, CVE-2026-87824, CVE-2026-87825, CVE-2026-87877, CVE-2026-90560 and CVE-2026-90852. Transitive dependency of kafka-clients 3.9.2; not managed by any BOM, so the override below is the sole source of the version. TODO: remove once kafka-clients pulls zstd-jni >= 1.5.7-14 -->
<freemarker.version>2.3.35</freemarker.version> <!-- to fix CVE-2026-84939. Pinned via the freemarker override below: spring-boot-dependencies is imported as a BOM, so this property alone would not win. TODO: remove when fixed in spring-boot-dependencies -->
<javax-annotation.version>1.3.2</javax-annotation.version> <!-- fixme Remove when generate proto will use jakarta -->
<javax.xml.bind-api.version>2.4.0-b180830.0359</javax.xml.bind-api.version>
<jjwt.version>0.12.5</jjwt.version>
<rat.version>0.10</rat.version> <!-- unused -->
<cassandra.version>4.17.0</cassandra.version>
<jcip-annotations.version>1.0-1</jcip-annotations.version>
<metrics.version>4.2.25</metrics.version>
<cassandra-all.version>5.0.7</cassandra-all.version> <!-- tools; 5.0.7 fixes CVE-2026-27314 -->
<guava.version>33.7.2-jre</guava.version> <!-- to fix CVE-2026-102554 -->
<jspecify.version>1.0.1</jspecify.version>
<commons-io.version>2.16.1</commons-io.version>
<commons-logging.version>1.3.1</commons-logging.version>
<commons-csv.version>1.10.0</commons-csv.version>
@ -159,7 +159,7 @@
<antlr.version>3.5.3</antlr.version>
<amazon-kinesis-producer>0.15.12</amazon-kinesis-producer>
<org.json.version>20250517</org.json.version> <!-- Transitive dependency by amazon-kinesis-producer 0.15.10, 0.15.12 to address CVE-2023-5072 -->
<amazon-kinesis-client>3.0.1</amazon-kinesis-client>
<amazon-kinesis-client>3.1.2</amazon-kinesis-client>
<apache-avro.version>1.11.4</apache-avro.version> <!--vulnerability fix, related to the kinesis client-->
<aws.sdk.version>1.12.701</aws.sdk.version>
<aws.sdk2.version>2.31.62</aws.sdk2.version>
@ -185,7 +185,7 @@
<antisamy.version>1.7.5</antisamy.version>
<snmp4j.version>3.8.0</snmp4j.version>
<bytebuddy.version>1.18.4</bytebuddy.version>
<langchain4j.version>1.16.1-TB1</langchain4j.version>
<langchain4j.version>1.16.1</langchain4j.version>
<error_prone_annotations.version>2.43.0</error_prone_annotations.version>
<animal-sniffer-annotations.version>1.24</animal-sniffer-annotations.version>
<auto-value-annotations.version>1.11.0</auto-value-annotations.version>
@ -1390,7 +1390,7 @@
<version>${bytebuddy.version}</version>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>${langchain4j.version}</version>
<type>pom</type>
@ -1745,11 +1745,6 @@
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax-annotation.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
@ -1839,14 +1834,10 @@
<classifier>osx-x86_64</classifier>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-core</artifactId>
<version>${cassandra.version}</version>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-query-builder</artifactId>
<version>${cassandra.version}</version>
<!-- The driver declares it provided: its classes carry these annotations, which compiling against them needs -->
<groupId>com.github.stephenc.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<version>${jcip-annotations.version}</version>
</dependency>
<dependency>
<groupId>io.dropwizard.metrics</groupId>
@ -1964,6 +1955,11 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<version>${jspecify.version}</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>

4
rule-engine/rule-engine-api/pom.xml

@ -78,7 +78,7 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<groupId>org.apache.cassandra</groupId>
<artifactId>java-driver-core</artifactId>
<scope>provided</scope>
</dependency>
@ -93,7 +93,7 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
</dependency>
<dependency>

2
rule-engine/rule-engine-components/pom.xml

@ -151,7 +151,7 @@
<artifactId>json-path</artifactId>
</dependency>
<dependency>
<groupId>org.thingsboard.langchain4j</groupId>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
</dependency>
<dependency>

2
rule-engine/rule-engine-components/src/main/resources/public/static/rulenode/twilio-config.js

File diff suppressed because one or more lines are too long

41
tools/src/main/python/license-headers/README.md

@ -36,7 +36,46 @@ packaging define the new artifact.
./check-license-headers.sh
```
The check needs the full Git history of the clone.
The check needs the full Git history of the clone. It runs Git and Mycila
subprocesses in parallel on all CPUs but one; set `LICENSE_HEADERS_JOBS` to
another number, for example `1` for a sequential run.
## Cache
The check removes the header of every CE file it compares with Mycila. CE files
never change, so their header-free contents are kept in
`target/license-headers-cache` and reused by the next run. The cache is valid
while the Mycila version and configuration in the root `pom.xml`, the templates
and the check itself stay the same; anything else starts a new cache, and the
check normalizes again instead of using the old one. Pass `--no-cache` to
normalize every CE file again, or `--cache` to keep the cache elsewhere.
The check keeps the caches of the three most recent signatures, so switching
between branches does not start over; set `LICENSE_HEADERS_CACHE_SIGNATURES`
to keep another number. If SQLite cannot use the cache, for example because
another run holds its lock, the run continues without it.
In GitHub Actions, pushes and manual runs save the cache and pull requests only
read it: a pull request takes the cache of its base branch, then of `master`.
CI keeps only the current signature, so the saved cache holds one database, and
saves it only when the run changed it.
## Check only changed files
```sh
./check-license-headers.sh --since origin/lts-4.4
```
Checks the files that differ between the merge base of the given ref and HEAD
and the working tree, untracked files included, and the files whose curation
changed. Pull requests run the check this way against their target branch;
pushes and manual runs check every file. Curations of files no longer in scope
are still reported for the whole repository.
The check falls back to every file when a change can move the verdict of an
unchanged file: new CE commits merged into the branch, a changed Mycila
configuration in the root `pom.xml`, or a change to the check itself. Other
changes to the Mycila scope, such as a module added to `<modules>`, do not
trigger it: the files they bring into scope are checked by the next push.
## Fix automatically

555
tools/src/main/python/license-headers/check_license_headers.py

@ -9,17 +9,21 @@ from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass
import hashlib
import io
import json
import os
from pathlib import Path, PurePosixPath
import re
import sqlite3
import subprocess
import sys
import tempfile
import threading
import uuid
import xml.etree.ElementTree as ET
@ -45,6 +49,7 @@ RELICENSING_COMMIT = "31936b09d24871e421f212502a8342f9d8aabb20"
CE_REMOTE = "https://github.com/thingsboard/thingsboard.git"
CURATIONS = "tools/src/main/python/license-headers/curations.json"
README = "tools/src/main/python/license-headers/README.md"
CHECKER_PATHS = ("tools/src/main/python/license-headers/", "check-license-headers.sh")
CURATION_FIELDS = {"path", "contentHash", "header", "reason"}
CONTENT_HASH = re.compile(r"sha256:[0-9a-f]{64}")
UNRECOGNIZED = "unrecognized"
@ -65,6 +70,14 @@ RESTAMP_LISTING = 40
REPEATED_HEADERS = 3
HEADER_WINDOW = 4096
XML_SPACE = "{http://www.w3.org/XML/1998/namespace}space"
JOBS_VARIABLE = "LICENSE_HEADERS_JOBS"
CACHE_SIGNATURES_VARIABLE = "LICENSE_HEADERS_CACHE_SIGNATURES"
CACHE_DIRECTORY = "target/license-headers-cache"
CACHE_FORMAT = "1"
CACHE_SIGNATURES_KEPT = 3
CACHE_FILE = re.compile(r"[0-9a-f]{32}\.sqlite")
# Git's minimum similarity for a copy, in percent: the -C threshold and the size filter in front of it.
COPY_SIMILARITY = 50
@dataclass(frozen=True)
@ -132,6 +145,30 @@ class Console:
console = Console()
def positive_setting(variable, default):
configured = os.environ.get(variable, "")
if not configured:
return default
if not configured.isdigit() or int(configured) < 1:
raise Failure(f"{variable} must be a positive number, not {configured!r}")
return int(configured)
def jobs():
"""Parallel subprocesses: LICENSE_HEADERS_JOBS when set, otherwise all CPUs but one to keep the machine responsive."""
return positive_setting(JOBS_VARIABLE, max(1, (os.cpu_count() or 1) - 1))
def parallel(function, items):
"""Results of function for every item in item order; the first failure propagates."""
items = list(items)
workers = min(len(items), jobs())
if workers <= 1:
return [function(item) for item in items]
with ThreadPoolExecutor(max_workers=workers) as pool:
return list(pool.map(function, items))
def run(argv, cwd, *, data=None, ok=(0,)):
result = subprocess.run(argv, cwd=cwd, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode not in ok:
@ -238,9 +275,12 @@ class Change:
status: str
def history(repo, revision, *options):
def history(repo, revisions, *options):
"""First-parent changes of every revision in one walk: commits shared by several revisions appear once."""
if not revisions or any(revision.startswith("-") for revision in revisions):
raise Failure("history needs revisions that do not start with '-'")
raw = git(repo, "log", "--first-parent", "--diff-merges=first-parent", "--root", "--raw", "--no-abbrev",
"--no-renames", "-z", "--format=%x1e%H", *options, revision, "--")
"--no-renames", "-z", "--format=%x1e%H", *options, *revisions, "--")
return list(parse_history(raw))
@ -400,8 +440,8 @@ def validate_curation(entry):
return name
def xml_plain(path):
root = ET.parse(path).getroot()
def xml_plain(source):
root = ET.parse(source).getroot()
for element in root.iter():
element.tag = element.tag.rsplit("}", 1)[-1]
return root
@ -418,7 +458,15 @@ class Plugin:
def read_plugin(repo):
plugins = xml_plain(repo / "pom.xml").findall("./build/pluginManagement/plugins/plugin")
return parse_plugin(xml_plain(repo / "pom.xml"))
def plugin_signature(plugin):
return plugin.version, ET.tostring(plugin.configuration)
def parse_plugin(project):
plugins = project.findall("./build/pluginManagement/plugins/plugin")
plugin = next((p for p in plugins if p.findtext("artifactId") == "license-maven-plugin"), None)
if plugin is None:
raise Failure("Root pom.xml does not manage the Mycila license plugin")
@ -451,8 +499,8 @@ class Scope:
def discover_scope(repo, plugin):
states = defaultdict(set)
modules = []
for entry in SCOPE_POMS:
for report in scope_check(repo, plugin, entry):
for reports in parallel(lambda entry: scope_check(repo, plugin, entry), SCOPE_POMS):
for report in reports:
module = report.parent.parent
modules.append({"path": str(module.relative_to(repo)), "report": str(report.relative_to(repo))})
for name, result in read_scope_report(repo, module, report):
@ -516,7 +564,6 @@ class Mycila:
def __init__(self, repo, directory, plugin):
self.root = directory
self.plugin = plugin
self.report = directory / "report.json"
self.paths = {}
self.contents = {}
self.removed = {}
@ -527,9 +574,10 @@ class Mycila:
(directory / name).parent.mkdir(parents=True, exist_ok=True)
(directory / name).write_bytes(self.templates[header])
def add(self, key, name, content):
def add(self, key, name, content, slot=None):
group = "head" if key[0] == "head" else "ce"
path = self.root / "files" / group / str(len(self.paths)) / PurePosixPath(name).name
slot = len(self.paths) if slot is None else slot
path = self.root / "files" / group / str(slot) / PurePosixPath(name).name
path.parent.mkdir(parents=True)
path.write_bytes(content)
self.paths[key] = path.relative_to(self.root).as_posix()
@ -548,8 +596,9 @@ class Mycila:
def current_headers(self, keys):
keys = list(keys)
recognized = defaultdict(list)
for header in TEMPLATES:
for key, result in self.invoke("check", header, keys).items():
checks = parallel(lambda header: self.invoke("check", header, keys), TEMPLATES)
for header, results in zip(TEMPLATES, checks):
for key, result in results.items():
if result == "PRESENT":
recognized[key].append(header)
return {key: recognized[key][0] if len(recognized[key]) == 1 else UNRECOGNIZED for key in keys}
@ -631,43 +680,46 @@ class Mycila:
rejected[key] = "more than one header, review by hand"
accepted = [key for key in keys if key not in rejected]
with self.guarded(accepted):
for header in TEMPLATES:
group = [key for key in accepted if expected[key] == header]
if group:
self.invoke("format", header, group)
groups = {header: [key for key in accepted if expected[key] == header] for header in TEMPLATES}
parallel(lambda header: self.invoke("format", header, groups[header]), TEMPLATES)
return {key: self.contents[key] for key in accepted}, rejected
def invoke(self, goal, header, keys, *, styles=()):
keys = list(keys)
if not keys:
return {}
self.write_pom(header, keys, styles)
self.report.unlink(missing_ok=True)
invocation = uuid.uuid4().hex
pom, report = self.root / f"pom-{invocation}.xml", self.root / f"report-{invocation}.json"
self.write_pom(pom, report, header, keys, styles)
try:
maven(self.root, [self.plugin.coordinates + ":" + goal])
maven(self.root, ["-f", pom.name, self.plugin.coordinates + ":" + goal])
results = self.read_results(report)
except Failure as exc:
unknown = self.unknown_inputs(keys)
unknown = self.unknown_inputs(report, keys)
if unknown:
raise Failure(f"Mycila cannot normalize these inputs: {unknown[:20]}") from exc
raise
results = self.read_results()
finally:
pom.unlink(missing_ok=True)
report.unlink(missing_ok=True)
if set(results) != {self.paths[key] for key in keys} or "UNKNOWN" in results.values():
raise Failure("Mycila comparison scope was incomplete or unknown")
return {key: results[self.paths[key]] for key in keys}
def read_results(self):
if not self.report.exists():
@staticmethod
def read_results(report):
if not report.exists():
raise Failure("Mycila did not produce its comparison report")
return {item["path"]: item["result"] for item in json.loads(self.report.read_text())["files"]}
return {item["path"]: item["result"] for item in json.loads(report.read_text())["files"]}
def unknown_inputs(self, keys):
def unknown_inputs(self, report, keys):
try:
results = self.read_results()
results = self.read_results(report)
except Failure:
return []
return [str(key) for key in keys if results.get(self.paths[key]) == "UNKNOWN"]
def write_pom(self, header, keys, styles):
def write_pom(self, pom, report, header, keys, styles):
project = ET.Element("project", xmlns="http://maven.apache.org/POM/4.0.0")
append_elements(project, [("modelVersion", "4.0.0"), ("groupId", "license.provenance"),
("artifactId", "temporary-comparison"), ("version", "1")])
@ -677,7 +729,7 @@ class Mycila:
config = ET.SubElement(plugin, "configuration")
append_elements(config, [("encoding", "UTF-8"), ("strictCheck", "true"), ("quiet", "true"),
("failIfMissing", "false"), ("failIfUnknown", "true"),
("reportFormat", "json"), ("reportLocation", str(self.report))])
("reportFormat", "json"), ("reportLocation", str(report))])
config.append(self.mapping(styles))
license_set = ET.SubElement(ET.SubElement(config, "licenseSets"), "licenseSet")
append_elements(license_set, [("header", str(self.root / TEMPLATES[header])),
@ -688,7 +740,7 @@ class Mycila:
parent = ET.SubElement(license_set, "inlineHeaderStyles")
for style in styles:
append_elements(ET.SubElement(parent, "inlineHeaderStyle"), (("name", style.name),) + style.settings)
ET.ElementTree(project).write(self.root / "pom.xml", encoding="utf-8", xml_declaration=True)
ET.ElementTree(project).write(pom, encoding="utf-8", xml_declaration=True)
def mapping(self, styles):
mapping = self.plugin.configuration.find("mapping")
@ -721,7 +773,7 @@ def normalized_copies(mycila, source_refs, names, nonempty):
before = stage(mycila, sources)
after = stage(mycila, destinations)
raw = git(mycila.root, "diff-tree", "--no-commit-id", "-r", "--raw", "--no-abbrev", "-z",
"-C50%", "--find-copies-harder", "-l0", before, after)
f"-C{COPY_SIMILARITY}%", "--find-copies-harder", "-l0", before, after)
keys = {path: key for key, path in mycila.paths.items()}
copies = defaultdict(list)
for source, destination, similarity in parse_copies(raw):
@ -733,9 +785,14 @@ def normalized_copies(mycila, source_refs, names, nonempty):
return dict(copies)
def staged(content):
"""What stage() hands to Git: the size filter in front of the copy search measures exactly this."""
return content.replace(b"\r\n", b"\n")
def stage(mycila, keys):
for key in keys:
mycila.write(key, mycila.contents[key].replace(b"\r\n", b"\n"))
mycila.write(key, staged(mycila.contents[key]))
pathspec = "".join(mycila.paths[key] + "\0" for key in sorted(keys)).encode("utf-8")
run(["git", "--literal-pathspecs", "add", "-f", "--pathspec-from-file=-", "--pathspec-file-nul"],
mycila.root, data=pathspec)
@ -822,9 +879,8 @@ class Lineage:
if git(repo, "rev-parse", "--is-shallow-repository").decode().strip() == "true":
raise Failure("this clone is shallow and the check needs full history. Run git fetch --unshallow.")
deleted = {}
for base in bases:
for change in history(repo, base, "--diff-filter=D"):
deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old})
for change in history(repo, list(bases), "--diff-filter=D"):
deleted.setdefault(change.path, {"path": change.path, "ref": change.commit + "^1", "blob": change.old})
return cls(head=head, bases=tuple(bases), trees={base: tree(repo, base) for base in bases}, deleted=deleted)
def versions(self, name):
@ -847,6 +903,7 @@ class Comparison:
copies: dict
merges: dict
ce_directories: frozenset
size_filter: bool | None = None
def classify(self, name, curation):
key = ("head", name)
@ -867,32 +924,230 @@ class Comparison:
))
def compare(repo, plugin, lineage, contents):
class NormalizationCache:
"""Header-free contents of CE inputs from earlier runs, keyed by content and file name (Mycila styles follow the
name). One SQLite file per normalization signature: a different Mycila setup, template or check misses the cache.
The cache only ever costs or saves time: when SQLite fails, the run continues without it."""
def __init__(self, directory, signature):
self.directory = directory
self.lock = threading.Lock()
self.added = 0
self.hits = 0
self.database = None
self.unavailable = None
directory.mkdir(parents=True, exist_ok=True)
self.path = directory / f"{signature}.sqlite"
try:
try:
self.database = self.open()
except sqlite3.OperationalError:
raise # locked by another run or unreadable: not damage, so the file stays
except sqlite3.DatabaseError:
# A damaged cache only costs time: start it again instead of failing the check.
self.path.unlink()
self.database = self.open()
except sqlite3.Error as exc:
self.disable(exc)
return
os.utime(self.path)
# Only files named like this cache's own: --cache may point at a directory that holds other SQLite files.
own = [path for path in directory.iterdir() if CACHE_FILE.fullmatch(path.name)]
kept = positive_setting(CACHE_SIGNATURES_VARIABLE, CACHE_SIGNATURES_KEPT)
for stale in sorted(own, key=lambda path: path.stat().st_mtime)[:-kept]:
stale.unlink()
def open(self):
database = sqlite3.connect(self.path, check_same_thread=False)
try:
database.execute("CREATE TABLE IF NOT EXISTS normalized (input TEXT PRIMARY KEY, content BLOB NOT NULL)")
# Opening reads only the schema: a file damaged below it would fail on the first lookup instead.
if database.execute("PRAGMA quick_check").fetchone()[0] != "ok":
raise sqlite3.DatabaseError(f"{self.path} is damaged")
except BaseException:
database.close() # before any unlink: Windows cannot remove an open file
raise
return database
def disable(self, exc):
"""Continues the run without the cache; what earlier puts committed stays valid. Reported by close(), so
that a progress line in the middle of the run stays intact."""
self.unavailable = self.unavailable or str(exc)
if self.database is not None:
try:
self.database.close()
except sqlite3.Error:
pass
self.database = None
@staticmethod
def input(name, raw):
return hashlib.sha256(raw).hexdigest() + "/" + PurePosixPath(name).name
def get(self, inputs):
found = {}
with self.lock:
if self.database is None:
return found
try:
for key, raw in inputs.items():
row = self.database.execute("SELECT content FROM normalized WHERE input = ?",
(self.input(key[0], raw),)).fetchone()
if row is not None:
found[key] = bytes(row[0])
except sqlite3.Error as exc:
self.disable(exc)
return {}
self.hits += len(found)
return found
def put(self, entries):
with self.lock:
if self.database is None:
return
try:
self.database.executemany("INSERT OR IGNORE INTO normalized VALUES (?, ?)",
[(self.input(key[0], raw), content) for key, raw, content in entries])
# Committed at once: the write lock is held only briefly, so another run on the same cache can add too.
self.database.commit()
except sqlite3.Error as exc:
self.disable(exc)
return
self.added += len(entries)
def close(self):
if self.database is not None:
self.database.close()
self.database = None
if self.unavailable:
console.line(f"The cache in {self.directory} was unavailable ({self.unavailable}); "
"the run continued without it", "dim")
class NoCache:
added = hits = 0
def get(self, inputs):
return {}
def put(self, entries):
pass
def close(self):
pass
def cache_signature(repo, plugin):
digest = hashlib.sha256(CACHE_FORMAT.encode())
version, configuration = plugin_signature(plugin)
for part in (Path(__file__).read_bytes(), version.encode(), configuration,
*((repo / name).read_bytes() for name in TEMPLATES.values())):
digest.update(len(part).to_bytes(8, "big") + part)
return digest.hexdigest()[:32]
def normalize(repo, plugin, cache, inputs):
"""Header-free contents of CE inputs ({key: raw bytes}, key[0] the file name), from the cache when it has them."""
found = cache.get(inputs)
missing = {key: raw for key, raw in inputs.items() if key not in found}
if missing:
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for key, raw in missing.items():
mycila.add(key, key[0], raw)
mycila.strip_headers()
grown = [key[0] for key, raw in missing.items() if len(mycila.contents[key]) > len(raw)]
if grown:
raise Failure(f"Mycila grew these files while removing their headers: {grown[:20]}")
found |= {key: mycila.contents[key] for key in missing}
cache.put([(key, raw, found[key]) for key, raw in missing.items()])
return found
def staged_size(content):
return len(staged(content))
def could_be_copy(size, destinations):
"""Git scores a pair 0 unless the smaller blob is at least COPY_SIMILARITY % of the larger (diffcore-rename
estimate_similarity)."""
return any(100 * min(size, other) >= COPY_SIMILARITY * max(size, other) for other in destinations)
def git_finds_copy(repo, plugin, source, destination):
"""Whether the copy search, normalized_copies itself, matches destination, a new path, to source, a CE file."""
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
staging = Mycila(repo, Path(temporary), plugin)
staging.add(("Source.java", "probe"), "Source.java", source)
staging.add(("head", "Destination.java"), "Destination.java", destination)
found = normalized_copies(staging, {("Source.java", "probe"): "probe"}, {"Destination.java"}, staging.nonempty())
return "Destination.java" in found
def size_filter_holds(repo, plugin):
"""Whether the installed Git still never matches a source that could_be_copy rules out. The filter relies on Git
measuring similarity against the larger blob (estimate_similarity divides by the larger size, and diffcore-delta.c
counts at most the smaller blob as copied), so a source below COPY_SIMILARITY % of a destination can never reach
the threshold. The probe asks the real copy search twice: a source of exactly COPY_SIMILARITY % of a destination
must be found, the same source one byte shorter must not. That catches a Git that measures against anything but
the larger blob; nothing else in this repository would notice such a change, and the filter would then drop CE
files Git matches. Both answers are compared with could_be_copy itself, so a change of the Python rule that no
longer matches Git turns the filter off as well. Each case runs in its own repository, so a found boundary pair
cannot hide the other answer."""
destination = b"".join(b"line %05d\n" % index for index in range(100))
boundary = destination[:len(destination) * COPY_SIMILARITY // 100]
sources = [boundary, boundary[:-1]]
rule = [could_be_copy(len(source), [len(destination)]) for source in sources]
answers = parallel(lambda source: git_finds_copy(repo, plugin, source, destination), sources)
return rule == answers == [True, False]
def could_shrink_to_copy(raw_size, destinations):
"""Normalizing never grows a file: below COPY_SIMILARITY % of the smallest destination it stays out of Git's reach."""
return 100 * raw_size >= COPY_SIMILARITY * min(destinations)
def compare(repo, plugin, lineage, contents, cache, in_scope):
names = list(contents)
new_paths = {name for name in names if not lineage.versions(name)}
# Copy sources follow every path in scope that CE lacks, not only the checked ones: with --since they would
# otherwise depend on the files a pull request changes and miss copies that a full run finds. Without new paths
# nothing is searched for copies, so no CE file needs to be read for it.
copy_source_types = {name for name in in_scope if not lineage.versions(name)} if new_paths else set()
sources = {}
for base, files in lineage.trees.items():
for name in names:
if name in files:
sources.setdefault((name, files[name]), base)
for key in comparable_ce_files(files, new_paths).items():
for key in comparable_ce_files(files, copy_source_types).items():
sources.setdefault(key, base)
versions = {(name, oid) for name in names for _, oid in lineage.versions(name)}
# Git breaks ties between equally similar copy sources by path. Sources are staged in key order, padded so that
# paths sort like ranks: --since, a full run and the size filter all present any two sources in the same order.
slots = {("head", name): f"{index:08d}" for index, name in enumerate(sorted(names))}
slots |= {key: f"{index:08d}" for index, key in enumerate(sorted(sources))}
bytes_by_id = blobs(repo, [oid for _, oid in sources])
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for name, content in contents.items():
mycila.add(("head", name), name, content)
for path, oid in sorted(sources):
mycila.add((path, oid), path, bytes_by_id[oid])
mycila.add(("head", name), name, content, slots[("head", name)])
console.begin("Recognizing headers")
recognized = mycila.current_headers([("head", name) for name in names])
console.end()
console.begin("Comparing against CE")
normalized = mycila.strip_headers()
head_hashes, copy_sources = parallel(lambda job: job(), [
mycila.strip_headers,
lambda: normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in versions})])
headers = mycila.header_states(recognized)
copies = normalized_copies(mycila, sources, new_paths, mycila.nonempty())
merges = clean_merges(repo, plugin, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions)")
destinations = {name: mycila.contents[("head", name)] for name in sorted(new_paths)
if mycila.contents[("head", name)].strip()}
normalized = head_hashes | {key: comparison_hash(content) for key, content in copy_sources.items()}
copies, searched, size_filter = copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id,
destinations, copy_sources)
normalized |= searched
merges = clean_merges(repo, plugin, cache, lineage, names, normalized)
console.end(f"done ({len(normalized)} file versions, {len(searched)} of {len(sources) - len(versions)} "
f"other CE files searched for copies, {cache.hits} from the cache)")
return Comparison(
lineage=lineage,
contents=contents,
@ -902,34 +1157,64 @@ def compare(repo, plugin, lineage, contents):
merges=merges,
ce_directories=frozenset(str(parent) for files in lineage.trees.values()
for path in files for parent in PurePosixPath(path).parents),
size_filter=size_filter,
)
def clean_merges(repo, plugin, lineage, names, normalized):
merged = {}
for index, left in enumerate(lineage.bases):
for right in lineage.bases[index + 1:]:
ancestors = git(repo, "merge-base", "--all", left, right).decode().split()
if len(ancestors) != 1:
def copy_candidates(repo, plugin, cache, sources, versions, slots, bytes_by_id, destinations, copy_sources):
"""CE files similar to the paths that CE does not have, normalized only when Git could match them by size; the
comparison hashes of the other CE files searched for them; and whether the size filter was used, None when there
was nothing to search for."""
if not destinations:
return {}, {}, None
sizes = [staged_size(content) for content in destinations.values()]
# Slower, never wrong: when the installed Git disagrees with the size rule, every CE file is searched.
size_filter = size_filter_holds(repo, plugin)
others = sorted(key for key in sources if key not in versions
and (not size_filter or could_shrink_to_copy(len(bytes_by_id[key[1]]), sizes)))
found = normalize(repo, plugin, cache, {key: bytes_by_id[key[1]] for key in others})
searched = {key: comparison_hash(content) for key, content in found.items()}
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
staging = Mycila(repo, Path(temporary), plugin)
for key, content in (found | copy_sources).items():
staging.add(key, key[0], content, slots[key])
for name, content in destinations.items():
staging.add(("head", name), name, content, slots[("head", name)])
reachable = {key: sources[key] for key in [*others, *copy_sources]
if not size_filter or could_be_copy(staged_size(staging.contents[key]), sizes)}
return normalized_copies(staging, reachable, set(destinations), staging.nonempty()), searched, size_filter
def clean_merges(repo, plugin, cache, lineage, names, normalized):
pairs = [(left, right) for index, left in enumerate(lineage.bases) for right in lineage.bases[index + 1:]]
def ancestry(pair):
ancestors = git(repo, "merge-base", "--all", *pair).decode().split()
return (ancestors[0], tree(repo, ancestors[0])) if len(ancestors) == 1 else None
candidates = []
for (left, right), common in zip(pairs, parallel(ancestry, pairs)):
if common is None:
continue
ancestor, files = common
for name in names:
ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name)
if ours is None or theirs is None or ours == theirs or name not in files:
continue
if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}:
continue
ancestry = tree(repo, ancestors[0])
for name in names:
ours, theirs = lineage.trees[left].get(name), lineage.trees[right].get(name)
if ours is None or theirs is None or ours == theirs or name not in ancestry:
continue
if normalized[("head", name)] in {normalized[(name, ours)], normalized[(name, theirs)]}:
continue
content = merge_blobs(repo, ours, ancestry[name], theirs)
if content is not None:
merged[(name, left, right)] = (content, {"path": name, "merge": [left, right],
"base": ancestors[0]})
candidates.append(((name, left, right), (ours, files[name], theirs), ancestor))
# Base pairs share most blobs: every distinct three-way merge runs once, all of them in parallel.
triples = list(dict.fromkeys(triple for _, triple, _ in candidates))
contents = dict(zip(triples, parallel(lambda triple: merge_blobs(repo, *triple), triples)))
merged = {}
for key, triple, ancestor in candidates:
if contents[triple] is not None:
merged[key] = (contents[triple], {"path": key[0], "merge": [key[1], key[2]], "base": ancestor})
if not merged:
return {}
with tempfile.TemporaryDirectory(prefix="license-provenance-") as temporary:
mycila = Mycila(repo, Path(temporary), plugin)
for key, (content, _) in merged.items():
mycila.add(key, key[0], content)
hashes = mycila.strip_headers()
found = normalize(repo, plugin, cache, {key: content for key, (content, _) in merged.items()})
hashes = {key: comparison_hash(content) for key, content in found.items()}
result = {}
for key, (_, description) in merged.items():
if hashes[key] == normalized[("head", key[0])]:
@ -937,6 +1222,89 @@ def clean_merges(repo, plugin, lineage, names, normalized):
return result
@dataclass(frozen=True)
class Selection:
since: str
merge_base: str
paths: frozenset | None
reason: str
@property
def full(self):
return self.paths is None
def report(self):
return {"since": self.since, "mergeBase": self.merge_base, "full": self.full, "reason": self.reason}
def merge_base(repo, since):
commit = resolve(repo, since)
bases = run(["git", "merge-base", commit, "HEAD"], repo, ok=(0, 1)).stdout.decode().split()
if not bases:
raise Failure(f"HEAD shares no history with {since}.")
return bases[0]
def changed_paths(repo, commit):
"""Paths that differ between the commit and the working tree, untracked files included."""
tracked = git(repo, "diff", "--name-only", "--no-renames", "-z", commit, "--")
untracked = git(repo, "ls-files", "--others", "--exclude-standard", "-z")
return {path.decode("utf-8") for path in (tracked + b"\0" + untracked).split(b"\0") if path}
def committed(repo, commit, name):
result = run(["git", "cat-file", "blob", f"{commit}:{name}"], repo, ok=(0, 128))
return result.stdout if result.returncode == 0 else None
def committed_plugin(repo, commit):
content = committed(repo, commit, "pom.xml")
try:
return None if content is None else plugin_signature(parse_plugin(xml_plain(io.BytesIO(content))))
except (Failure, ET.ParseError):
return None
def committed_curations(repo, commit):
content = committed(repo, commit, CURATIONS)
if content is None:
return {}
try:
return {entry["path"]: entry for entry in json.loads(content)["curations"]}
except (ValueError, KeyError, TypeError):
return None
def select_changes(repo, since, bases, ce_bases, plugin, curations):
"""Files to check against a PR target: the changed ones, unless a change can move verdicts of unchanged files."""
base = merge_base(repo, since)
def full(reason):
return Selection(since, base, None, reason)
try:
if sorted(ce_bases(base)) != sorted(bases):
return full("the CE commits merged into the branch changed")
except Failure:
return full("the CE commits merged at the merge base cannot be resolved")
if committed_plugin(repo, base) != plugin_signature(plugin):
return full("the Mycila configuration in the root pom.xml changed")
changed = changed_paths(repo, base)
checker = sorted(path for path in changed
if path.startswith(CHECKER_PATHS) and path not in {CURATIONS, README})
if checker:
return full(f"the check itself changed ({checker[0]})")
previous = committed_curations(repo, base)
curated = set(curations) if previous is None else {
name for name in set(previous) | set(curations) if previous.get(name) != curations.get(name)}
paths = frozenset(changed | curated)
return Selection(since, base, paths, f"{len(paths)} changed paths")
def git_version():
return run(["git", "--version"], Path.cwd()).stdout.decode().strip().removeprefix("git version ")
def current_branch(repo):
branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD").decode().strip()
return "" if branch == "HEAD" else branch
@ -1058,15 +1426,19 @@ def print_findings(rows, curation_issues, ref_names):
f"Rerun with --fix to remove them from {CURATIONS}", style=None)
def print_summary(rows, curation_issues, report):
def print_summary(rows, curation_issues, report, label="files"):
findings = sum(row["status"] != "match" for row in rows) + len(curation_issues)
restamped = sum("previousHeader" in row for row in rows)
note = f" ({restamped} restamped)" if restamped else ""
if findings:
console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} files{note}. Report: {report}",
console.line(f"{findings} finding{'s' if findings != 1 else ''} in {len(rows)} {label}{note}. Report: {report}",
"red")
return
console.line(f"All {len(rows)} files carry the expected header{note}.", "green")
if not rows:
console.line(f"No {label} to check.", "green")
console.line(f"Report: {report}")
return
console.line(f"All {len(rows)} {label} carry the expected header{note}.", "green")
counts = Counter(row["expectedHeader"] for row in rows)
console.line(" " + " · ".join(f"{header} {counts[header]}" for header in TEMPLATES if counts[header]))
console.line(f"Report: {report}")
@ -1166,16 +1538,43 @@ def check(args):
curation_bytes = curation_path.read_bytes()
curations = load_curations(curation_path)
console.begin("Resolving Git history")
bases = merged_ce_bases(repo, head, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, head)
def ce_bases(commit):
return merged_ce_bases(repo, commit, ce["commit"]) if "ref" in ce else relicensed_ce_bases(repo, commit)
bases = ce_bases(head)
lineage = Lineage.load(repo, head, bases)
console.end("done (CE base " + ", ".join(ref_name(base, ref_names) for base in bases) + ")")
selection = None
if args.since:
console.begin(f"Selecting files changed since {args.since}")
selection = select_changes(repo, args.since, bases, ce_bases, plugin, curations)
console.end(("full check: " if selection.full else "") + selection.reason
+ f" (merge base {selection.merge_base[:11]})")
console.begin("Collecting Mycila scope")
scope = discover_scope(repo, plugin)
console.end(f"{len(scope.eligible)} files ({scope.ignored} Git-ignored skipped)")
contents = {name: (repo / name).read_bytes() for name in scope.eligible}
comparison = compare(repo, plugin, lineage, contents)
checked = (scope.eligible if selection is None or selection.full
else [name for name in scope.eligible if name in selection.paths])
if selection is not None and not selection.full:
console.line(f"Checking {len(checked)} of {len(scope.eligible)} files in scope", "dim")
contents = {name: (repo / name).read_bytes() for name in checked}
rows = []
size_filter = None
if contents:
cache = (NoCache() if args.no_cache
else NormalizationCache((repo / args.cache).resolve(), cache_signature(repo, plugin)))
try:
comparison = compare(repo, plugin, lineage, contents, cache, scope.eligible)
finally:
cache.close()
rows = [comparison.classify(name, curations.get(name)) for name in checked]
size_filter = comparison.size_filter
console.line()
rows = [comparison.classify(name, curations.get(name)) for name in scope.eligible]
if size_filter is False:
console.line(f"Git's copy detection (git {git_version()}) and the size rule of the copy search disagree; "
"every CE file was searched for copies. Report this to the maintainers of the check.", "red")
console.line()
orphaned = [{"path": name, "status": "stale-curation", "reason": "file is no longer in scope"}
for name in sorted(set(curations) - set(scope.eligible))]
ensure_inputs_unchanged(repo, lineage, curation_path, curation_bytes, contents)
@ -1190,6 +1589,8 @@ def check(args):
"head": lineage.head,
"ce": ce | {"bases": list(lineage.bases)},
"scope": {"supported": len(scope.eligible), "unknown": scope.unknown, "modules": scope.modules},
"selection": selection.report() if selection is not None else None,
"copySearch": {"sizeFilter": size_filter},
"summary": dict(summary),
"restamped": sorted(row["path"] for row in rows if "previousHeader" in row),
"removedCurations": removed,
@ -1203,7 +1604,7 @@ def check(args):
print_restamped(rows)
print_removed_curations(removed)
print_findings(rows, orphaned, ref_names)
print_summary(rows, orphaned, report)
print_summary(rows, orphaned, report, "files" if selection is None or selection.full else "changed files")
return 1 if orphaned or summary.keys() - {"match"} else 0
@ -1215,7 +1616,15 @@ def main(argv=None):
"without it, CE is the history of HEAD that does not contain the relicensing commit")
parser.add_argument("--ce-remote", default=CE_REMOTE,
help=f"Git URL or path of the CE repository to fetch --ce-ref from (default: {CE_REMOTE})")
parser.add_argument("--since", metavar="REF",
help="check only files changed since the merge base of REF and HEAD, uncommitted and "
"untracked files included; falls back to the full check when the CE commits, the "
"root Mycila configuration or the check itself changed")
parser.add_argument("--output", default="target/license-provenance/report.json")
parser.add_argument("--cache", default=CACHE_DIRECTORY, metavar="DIRECTORY",
help="header-free CE contents from earlier runs, reused while the Mycila setup, the "
f"templates and the check stay the same (default: {CACHE_DIRECTORY})")
parser.add_argument("--no-cache", action="store_true", help="normalize every CE input again")
parser.add_argument("--fix", action="store_true",
help="restamp files whose expected header the check determined and remove redundant or "
"orphaned curations; unrecognized headers are kept")

6
tools/src/main/python/license-headers/curations.json

@ -1243,12 +1243,6 @@
"reason": "PE converter autocomplete styling. The entire body is a host-scoped Material icon-link border/color reset, also present in unrelated CE autocomplete controls. This trivial shared UI style does not establish CE provenance for a PE converter component. Reviewed candidate ui-ngx/src/app/modules/home/components/profile/tenant-profile-autocomplete.component.scss at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 95fd62939ec09897ed96164f7a2a47d6805c3245).",
"contentHash": "sha256:03445abafd2f4f71cd541c2ee3c33e195e37ad711630971fc35fd393c66419ff"
},
{
"path": "ui-ngx/src/app/modules/home/components/converter/converter-dialog.component.html",
"header": "busl",
"reason": "PE view template converter-dialog.component.html. Reviewed form fields, bindings and entity/component selection implement the PE feature; the candidate shares standard Material dialog/form/tab scaffolding rather than a CE feature implementation. Reviewed CE candidate ui-ngx/src/app/modules/home/components/entity/add-entity-dialog.component.html at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob 955f8f58be2d9d462570164005f4a2ee693b0dd7).",
"contentHash": "sha256:845e3846f9f41be29dc209df6c28c8870c3886886018155735affb0c49c5a9f9"
},
{
"path": "ui-ngx/src/app/modules/home/components/converter/converter-test-dialog.component.scss",
"header": "busl",

682
tools/src/main/python/license-headers/test_check_license_headers.py

@ -4,9 +4,11 @@
#
from contextlib import redirect_stderr, redirect_stdout
import hashlib
import io
import json
import os
import sqlite3
from pathlib import Path
import tempfile
import textwrap
@ -17,6 +19,19 @@ import xml.etree.ElementTree as ET
import check_license_headers as p
CONNECT = sqlite3.connect
def impatient_sqlite():
"""SQLite that waits 0.1 s instead of 5 s for another connection's lock."""
return patch.object(sqlite3, "connect", lambda *args, **kwargs: CONNECT(*args, **kwargs | {"timeout": 0.1}))
def signature(label):
"""A cache signature as cache_signature() shapes it: 32 hex characters."""
return hashlib.sha256(label.encode()).hexdigest()[:32]
def temporary_directory(test):
directory = tempfile.TemporaryDirectory()
test.addCleanup(directory.cleanup)
@ -240,6 +255,57 @@ class DecisionTests(unittest.TestCase):
stderr.getvalue())
class ParallelTests(unittest.TestCase):
def test_jobs_follow_the_machine_unless_configured(self):
for cpus, expected in ((12, 11), (2, 1), (1, 1), (None, 1)):
with patch.dict(os.environ, {p.JOBS_VARIABLE: ""}), patch.object(p.os, "cpu_count", return_value=cpus):
self.assertEqual(expected, p.jobs(), f"{cpus} CPUs")
with patch.dict(os.environ, {p.JOBS_VARIABLE: "3"}):
self.assertEqual(3, p.jobs())
for wrong in ("0", "-2", "many"):
with patch.dict(os.environ, {p.JOBS_VARIABLE: wrong}), self.assertRaisesRegex(p.Failure, p.JOBS_VARIABLE):
p.jobs()
def test_parallel_keeps_item_order_and_raises_the_first_failure(self):
with patch.dict(os.environ, {p.JOBS_VARIABLE: "4"}):
self.assertEqual([item * 2 for item in range(50)], p.parallel(lambda item: item * 2, range(50)))
self.assertEqual([], p.parallel(lambda item: item, []))
def failing(item):
if item == 7:
raise p.Failure("item 7")
return item
with self.assertRaisesRegex(p.Failure, "item 7"):
p.parallel(failing, range(20))
class MycilaGuardTests(unittest.TestCase):
def tool(self):
tool = p.Mycila(this_repository(), temporary_directory(self), fixture_plugin())
tool.add(("head", "A.java"), "A.java", b"// header\ncode")
return tool
def test_guard_restores_the_file_end_and_rejects_a_rewritten_one(self):
tool = self.tool()
with tool.guarded([("head", "A.java")]):
tool.file(("head", "A.java")).write_bytes(tool.file(("head", "A.java")).read_bytes().replace(b"// header\n", b""))
self.assertEqual(b"code", tool.contents[("head", "A.java")])
with self.assertRaisesRegex(p.Failure, "Mycila rewrote the end"):
with tool.guarded([("head", "A.java")]):
tool.file(("head", "A.java")).write_bytes(b"code\n")
def test_scope_reports_are_accepted_only_from_target_directories(self):
repo = temporary_directory(self)
(repo / "module/target").mkdir(parents=True)
(repo / "module/target/token.json").write_text("{}")
self.assertEqual([repo / "module/target/token.json"], p.scope_reports(repo, "token.json"))
(repo / "other").mkdir()
(repo / "other/token.json").write_text("{}")
with self.assertRaisesRegex(p.Failure, "Unexpected scope report location"):
p.scope_reports(repo, "token.json")
class InputTests(unittest.TestCase):
def test_header_state_recognizes_legacy_thingsboard_headers(self):
ce = b"/**\n * Copyright \xc2\xa9 2016-2025 The Thingsboard Authors\n *\n * Licensed under the Apache License\n */\n"
@ -270,6 +336,8 @@ class InputTests(unittest.TestCase):
self.assertEqual(b"// SPDX-A\n// SPDX-B", p.swap_header(b"// SPDX-X\n// SPDX-Y\n// SPDX-Z", new, old))
with self.assertRaises(p.Failure):
p.swap_header(b"// SPDX-A\n\n// SPDX-B\ncode\n", old, new)
with self.assertRaises(p.Failure):
p.swap_header(b"// SPDX-A\n# SPDX-B\ncode\n", old, new)
with self.assertRaises(p.Failure):
p.swap_header(b"code\n", old, new)
@ -355,6 +423,30 @@ class InputTests(unittest.TestCase):
self.assertEqual(f"{p.TEMPLATE_DIRECTORY}/license-header-{p.NON_CE}.txt", p.TEMPLATES[p.NON_CE])
self.assertTrue((this_repository() / p.TEMPLATES[p.NON_CE]).is_file())
def test_committed_plugin_tracks_the_root_mycila_configuration(self):
git = GitFixture(temporary_directory(self), "main")
def pom(header):
return textwrap.dedent(f"""\
<project xmlns="http://maven.apache.org/POM/4.0.0"><build><pluginManagement><plugins><plugin>
<groupId>com.mycila</groupId><artifactId>license-maven-plugin</artifactId><version>5.1.2</version>
<configuration><header>{header}</header></configuration>
</plugin></plugins></pluginManagement></build></project>
""")
git.write("pom.xml", pom("a.txt"))
first = git.commit("pom")
git.write("pom.xml", "<!-- reformatted -->\n" + pom("a.txt"))
same = git.commit("comment only")
git.write("pom.xml", pom("b.txt"))
changed = git.commit("other header")
current = p.plugin_signature(p.read_plugin(git.root))
self.assertEqual(p.committed_plugin(git.root, first), p.committed_plugin(git.root, same))
self.assertNotEqual(p.committed_plugin(git.root, same), current)
self.assertEqual(p.committed_plugin(git.root, changed), current)
git("rm", "-q", "pom.xml")
self.assertIsNone(p.committed_plugin(git.root, git.commit("no pom")))
def test_plugin_version_and_configuration_come_from_root_pom(self):
repo = temporary_directory(self)
p.git(repo, "init")
@ -390,13 +482,13 @@ class GitHistoryTests(unittest.TestCase):
git("checkout", "lts-4.2")
git("merge", "--no-ff", "side", "-m", "integrate")
merged = git("rev-parse", "HEAD")
changes = p.history(git.root, "HEAD")
changes = p.history(git.root, ["HEAD"])
self.assertEqual({initial, merged}, {change.commit for change in changes})
self.assertEqual(source, changes[0].path)
git("rm", source)
git.commit("delete")
deleted = p.history(git.root, "HEAD", "--diff-filter=D")
deleted = p.history(git.root, ["HEAD"], "--diff-filter=D")
self.assertEqual(["D"], [change.status for change in deleted])
self.assertEqual(b"merged result\n", p.blobs(git.root, [deleted[0].old])[deleted[0].old])
@ -491,6 +583,71 @@ class GitHistoryTests(unittest.TestCase):
self.assertEqual([(removal, git("rev-parse", f"{removal}:Kept.java"))], lineage.versions("Kept.java"))
self.assertEqual([], lineage.versions("Gone.java"))
def test_lineage_walks_shared_history_of_several_bases_once(self):
git = GitFixture(temporary_directory(self), "ce")
git.write("Shared.java", "deleted before the bases diverged\n")
git.write("Left.java", "deleted on the left base\n")
git.write("Right.java", "deleted on the right base\n")
git.commit("CE base")
git("rm", "Shared.java")
shared = git.commit("shared removal")
git("checkout", "-b", "right")
git("rm", "Right.java")
right = git.commit("right removal")
git("checkout", "ce")
git("rm", "Left.java")
left = git.commit("left removal")
separately = {}
for base in (left, right):
for change in p.history(git.root, [base], "--diff-filter=D"):
separately.setdefault(change.path, set()).add(change.commit)
together = p.history(git.root, [left, right], "--diff-filter=D")
self.assertEqual(3, len(together), "the shared removal is listed once")
self.assertEqual(separately, {change.path: {change.commit} for change in together})
lineage = p.Lineage.load(git.root, left, [left, right])
self.assertEqual({"Shared.java": shared + "^1", "Left.java": left + "^1", "Right.java": right + "^1"},
{path: entry["ref"] for path, entry in lineage.deleted.items()})
with self.assertRaises(p.Failure):
p.history(git.root, [])
with self.assertRaises(p.Failure):
p.history(git.root, ["--all"])
def test_clean_merges_match_each_file_with_its_own_merge_in_any_order(self):
git = GitFixture(temporary_directory(self), "ce")
for header, name in p.TEMPLATES.items():
git.write(name, f"fixture {header}\n")
lines = "".join(f"line {index}\n" for index in range(12))
git.write("A.java", "A\n" + lines)
git.write("B.java", "B\n" + lines)
base = git.commit("CE base")
bases = {}
for branch, line in (("left", "line 0"), ("middle", "line 5"), ("right", "line 11")):
git("checkout", "-q", "-b", branch, base)
git.write("A.java", "A\n" + lines.replace(line, branch))
git.write("B.java", "B\n" + lines.replace(line, branch))
bases[branch] = git.commit(branch)
lineage = p.Lineage.load(git.root, bases["left"], sorted(bases.values()))
# HEAD carries A merged from left and right, B merged from middle and right: two distinct merges.
head = {"A.java": "A\n" + lines.replace("line 0", "left").replace("line 11", "right"),
"B.java": "B\n" + lines.replace("line 5", "middle").replace("line 11", "right")}
normalized = {("head", name): p.comparison_hash(text.encode()) for name, text in head.items()}
for files in lineage.trees.values():
for name, oid in files.items():
normalized[(name, oid)] = p.comparison_hash(p.blobs(git.root, [oid])[oid])
def strip_headers(tool):
return {key: p.comparison_hash(content) for key, content in tool.contents.items()}
expected = {"A.java": sorted([bases["left"], bases["right"]]),
"B.java": sorted([bases["middle"], bases["right"]])}
with patch.object(p.Mycila, "strip_headers", strip_headers):
for workers in ("1", "4"):
with patch.dict(os.environ, {p.JOBS_VARIABLE: workers}):
merges = p.clean_merges(git.root, fixture_plugin(), p.NoCache(), lineage, list(head), normalized)
self.assertEqual(expected, {name: sorted(merge["merge"]) for name, merge in merges.items()},
f"{workers} workers")
self.assertEqual({base}, {merge["base"] for merge in merges.values()})
def test_merge_blobs_returns_only_clean_merges(self):
git = GitFixture(temporary_directory(self), "main")
git.write("File.java", "one\ntwo\nthree\nfour\nfive\n")
@ -569,6 +726,10 @@ class FetchTests(unittest.TestCase):
third = self.ce.commit("third")
self.assertEqual(third, self.fetch("lts-4.2"))
def test_a_local_branch_of_the_same_name_does_not_shadow_the_fetched_tip(self):
self.local("branch", "lts-4.2")
self.assertEqual(self.second, self.fetch("lts-4.2"))
def test_missing_ref_and_option_like_ref_are_rejected(self):
with self.assertRaisesRegex(p.Failure, r"(?s)cannot fetch 'missing' from .*couldn't find remote ref missing"):
self.fetch("missing")
@ -609,7 +770,7 @@ class CheckCommandTests(unittest.TestCase):
self.scope = ["Base.java", "Changed.java", "Fixed.java", "Merged.java", "New.java", "Source.java"]
self.output = self.repo / "target/report.json"
def check(self, *args, scope=None):
def check(self, *args, scope=None, base_plugin=fixture_plugin(), normalizer=None):
def recognized(content):
for header in p.TEMPLATES:
if content.startswith(fixture(header).encode()):
@ -639,9 +800,10 @@ class CheckCommandTests(unittest.TestCase):
with (patch.object(p.Path, "cwd", return_value=self.repo),
patch.object(p, "RELICENSING_COMMIT", self.relicensing),
patch.object(p, "read_plugin", return_value=fixture_plugin()),
patch.object(p, "committed_plugin", return_value=p.plugin_signature(base_plugin)),
patch.object(p, "discover_scope", return_value=p.Scope(scope or self.scope, [], [], 0)),
patch.object(p.Mycila, "current_headers", current_headers),
patch.object(p.Mycila, "strip_headers", strip_headers),
patch.object(p.Mycila, "strip_headers", normalizer or strip_headers),
patch.object(p.Mycila, "restamp", restamp),
redirect_stdout(io.StringIO()), redirect_stderr(stderr)):
code = p.main(["check", "--output", str(self.output), *args])
@ -737,6 +899,160 @@ class CheckCommandTests(unittest.TestCase):
code, report, _ = self.check("--fix", scope=scope)
self.assertEqual((0, []), (code, report["removedCurations"]))
def pull_request(self):
self.git("checkout", "-q", "-b", "feature")
return self.git("rev-parse", "master")
def checked(self, report):
return sorted(row["path"] for row in report["files"])
def test_files_changed_during_the_scan_fail_the_check(self):
compare = p.compare
def edit_while_scanning(*args):
result = compare(*args)
self.git.write("Base.java", fixture("apache") + "edited during the scan\n")
return result
with patch.object(p, "compare", edit_while_scanning):
code, report, output = self.check()
self.assertEqual((2, None), (code, report))
self.assertIn("changed during the scan", output)
def test_since_checks_only_changed_and_untracked_files(self):
target = self.pull_request()
self.git.write("New.java", fixture("apache") + "TB feature\n")
self.git.commit("wrong header on a TB file")
self.git.write("Added.java", fixture(p.NON_CE) + "untracked TB file\n")
code, report, output = self.check("--since", "master", scope=self.scope + ["Added.java"])
self.assertEqual(1, code)
self.assertEqual(["Added.java", "New.java"], self.checked(report))
self.assertEqual("mismatch", self.rows(report)["New.java"]["status"])
self.assertEqual({"since": "master", "mergeBase": target, "full": False, "reason": "2 changed paths"},
report["selection"])
self.assertEqual(7, report["scope"]["supported"])
self.assertIn("Checking 2 of 7 files in scope", output)
self.assertIn("1 finding in 2 changed files", output)
def test_since_without_changes_checks_nothing_but_orphaned_curations(self):
self.pull_request()
code, report, output = self.check("--since", "master")
self.assertEqual((0, []), (code, report["files"]))
self.assertIn("No changed files to check.", output)
orphaned = dict(path="Gone.java", header=p.NON_CE, reason="Reviewed", contentHash=p.raw_hash(b"gone"))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[orphaned])))
self.git.commit("curation of a file that is not in scope")
code, report, _ = self.check("--since", "master")
self.assertEqual(1, code)
self.assertEqual(["Gone.java"], [issue["path"] for issue in report["curationIssues"]])
def test_since_checks_files_whose_curation_changed(self):
curation = dict(path="New.java", header="apache", reason="Reviewed",
contentHash=p.raw_hash((self.repo / "New.java").read_bytes()))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
self.git.commit("curate New.java")
self.pull_request()
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[])))
self.git.commit("drop the curation")
code, report, _ = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(["New.java"], self.checked(report))
self.assertEqual("not in CE, no CE evidence", self.rows(report)["New.java"]["reason"])
def test_since_checks_every_file_when_new_ce_commits_are_merged(self):
self.pull_request()
self.git("checkout", "-q", "lts-4.3")
self.git.write("Fixed.java", fixture("apache") + "second lts addition\n")
self.git.commit("second CE fix")
self.git("checkout", "-q", "feature")
self.git("merge", "-q", "--no-ff", "lts-4.3", "-m", "integrate second CE fix")
code, report, output = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual("the CE commits merged into the branch changed", report["selection"]["reason"])
self.assertTrue(report["selection"]["full"])
self.assertIn("full check: the CE commits merged into the branch changed", output)
def test_since_checks_every_file_when_the_check_changes(self):
self.pull_request()
self.git.write(p.TEMPLATES["apache"], "fixture apache, reworded\n")
self.git.commit("change a template")
_, report, _ = self.check("--since", "master")
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual(f"the check itself changed ({p.TEMPLATES['apache']})", report["selection"]["reason"])
def test_since_checks_every_file_when_the_mycila_configuration_changes(self):
self.pull_request()
_, report, _ = self.check("--since", "master", base_plugin=fixture_plugin("1"))
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual("the Mycila configuration in the root pom.xml changed", report["selection"]["reason"])
def test_since_does_not_orphan_curations_of_unchanged_files(self):
curation = dict(path="Source.java", header="apache", reason="Reviewed",
contentHash=p.raw_hash((self.repo / "Source.java").read_bytes()))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
self.git.commit("curate Source.java")
self.pull_request()
self.git.write("New.java", fixture(p.NON_CE) + "TB feature, changed\n")
self.git.commit("unrelated change")
code, report, _ = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(["New.java"], self.checked(report))
self.assertEqual([], report["curationIssues"])
def test_since_finds_a_copy_of_a_ce_file_with_another_extension_as_a_full_run_does(self):
# CE sources of the copy search follow the extensions of every path CE lacks: New.java brings .java in.
self.pull_request()
self.git.write("Copy.kt", fixture(p.NON_CE) + self.body)
self.git.commit("copy a CE file into another language")
scope = self.scope + ["Copy.kt"]
_, full, _ = self.check(scope=scope)
code, since, _ = self.check("--since", "master", scope=scope)
self.assertEqual(1, code)
self.assertEqual(["Copy.kt"], self.checked(since))
row = self.rows(since)["Copy.kt"]
self.assertEqual(self.rows(full)["Copy.kt"], row)
self.assertEqual(("unresolved", ["Source.java"]),
(row["status"], [copy["path"] for copy in row["copyCandidates"]]))
def test_since_checks_every_file_when_the_merge_base_has_no_ce_bases(self):
self.pull_request()
_, report, output = self.check("--since", "lts-4.3")
self.assertEqual(sorted(self.scope), self.checked(report))
self.assertEqual("the CE commits merged at the merge base cannot be resolved", report["selection"]["reason"])
def test_since_checks_every_curated_file_when_the_target_curations_cannot_be_read(self):
self.git.write(p.CURATIONS, "not JSON")
self.git.commit("damage curations.json")
self.pull_request()
curation = dict(path="Source.java", header="apache", reason="Reviewed",
contentHash=p.raw_hash((self.repo / "Source.java").read_bytes()))
self.git.write(p.CURATIONS, json.dumps(dict(schemaVersion=1, curations=[curation])))
self.git.commit("repair curations.json")
code, report, _ = self.check("--since", "master")
self.assertEqual(0, code)
self.assertEqual(["Source.java"], self.checked(report))
self.assertEqual(["Source.java"], report["redundantCurations"])
def test_since_does_not_check_every_file_when_only_the_readme_or_curations_of_the_check_change(self):
self.pull_request()
self.git.write(p.README, "notes\n")
self.git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": [] }')
self.git.commit("document the check")
code, report, _ = self.check("--since", "master")
self.assertEqual((0, []), (code, report["files"]))
self.assertEqual({"since": "master", "mergeBase": self.git("rev-parse", "master"), "full": False,
"reason": "2 changed paths"}, report["selection"])
def test_since_needs_shared_history(self):
self.git("checkout", "-q", "--orphan", "unrelated")
self.git.write("Other.java", "other\n")
self.git.commit("unrelated")
self.git("checkout", "-q", "master")
code, _, output = self.check("--since", "unrelated")
self.assertEqual(2, code)
self.assertIn("HEAD shares no history with unrelated", output)
def test_missing_relicensing_commit_fails_before_the_scan(self):
self.relicensing = "0" * 40
code, report, output = self.check()
@ -886,10 +1202,366 @@ def stamped(header, extension):
return text[:-1] if extension in {"java", "ts"} else text
class CopySearchTests(unittest.TestCase):
check = CheckCommandTests.check
rows = CheckCommandTests.rows
BODY = "".join(f" copied statement number {index};\n" for index in range(40))
def test_size_filter_follows_git_similarity_threshold(self):
git = GitFixture(temporary_directory(self), "main")
destination = ("".join(f"line {index:04d}\n" for index in range(100))).encode()
half = destination[:len(destination) // 2]
for source, expected in ((half, True), (half[:-1], False)):
self.assertEqual(expected, p.could_be_copy(len(source), [len(destination)]))
tool = p.Mycila.__new__(p.Mycila)
tool.root, tool.paths, tool.contents = git.root, {}, {}
tool.add(("Source.java", "0" * 40), "Source.java", source)
tool.add(("head", "Destination.java"), "Destination.java", destination)
found = p.normalized_copies(tool, {("Source.java", "0" * 40): "ref"}, {"Destination.java"},
tool.nonempty())
self.assertEqual(expected, "Destination.java" in found, f"{len(source)} of {len(destination)} bytes")
for path in ("files", ".git"):
p.run(["rm", "-rf", path], git.root)
def test_filter_before_normalizing_drops_exactly_the_unreachable_sources(self):
# Normalizing removes a header and never grows a file: a source of raw size r can end up at any size up to r.
for destinations in ([7], [7, 30], [30, 7], [12, 13, 60]):
for raw in range(1, 70):
reachable = any(p.could_be_copy(size, destinations) for size in range(1, raw + 1))
self.assertEqual(reachable, p.could_shrink_to_copy(raw, destinations), f"{raw} → {destinations}")
def setUp(self):
self.repo = temporary_directory(self)
self.git = git = GitFixture(self.repo, "master")
git.write(".gitignore", "target/\n")
for category, name in p.TEMPLATES.items():
git.write(name, f"fixture {category}\n")
git.write(p.CURATIONS, '{"schemaVersion": 1, "curations": []}')
# Sorted CE sources: a/ (small), b/Alpha, c/ (small), e/Gamma. Alpha and Gamma are identical: Alpha ranks first
# among all CE files and wins the tie, whichever sources the size filter drops and whatever else is checked.
for name in ("a/Small0.java", "a/Small1.java", *(f"c/Small{index}.java" for index in range(2, 10))):
git.write(name, fixture("apache") + "x\n")
git.write("b/Alpha.java", fixture("apache") + self.BODY)
git.write("e/Gamma.java", fixture("apache") + self.BODY)
git.commit("CE")
git.write("d/Delta.java", fixture(p.NON_CE) + self.BODY)
self.relicensing = git.commit("relicensing")
self.scope = ["d/Delta.java"]
self.output = self.repo / "target/report.json"
def test_size_filter_keeps_the_copy_search_result(self):
_, filtered, output = self.check()
with patch.object(p, "size_filter_holds", return_value=False):
_, unfiltered, unfiltered_output = self.check()
self.assertEqual(unfiltered["files"], filtered["files"])
self.assertEqual(({"sizeFilter": True}, {"sizeFilter": False}),
(filtered["copySearch"], unfiltered["copySearch"]))
self.assertNotIn("and the size rule of the copy search disagree", output)
self.assertIn("and the size rule of the copy search disagree", unfiltered_output)
row = self.rows(filtered)["d/Delta.java"]
self.assertEqual(("unresolved", "apache"), (row["status"], row["suggestedHeader"]))
self.assertEqual(["b/Alpha.java"], [copy["path"] for copy in row["copyCandidates"]])
self.assertIn("2 of 12 other CE files searched for copies", output)
self.assertIn("12 of 12 other CE files searched for copies", unfiltered_output)
def test_since_reports_the_copy_a_full_run_reports_among_equally_similar_sources(self):
# TB files beside the new one shift where the checked inputs sit among all inputs of a full run.
others = [f"t/Tb{index}.java" for index in range(7)]
self.git("reset", "-q", "--hard", "HEAD~1")
for name in others:
self.git.write(name, fixture(p.NON_CE) + f"TB source {name}\n")
self.relicensing = self.git.commit("relicensing with TB files")
self.git("checkout", "-q", "-b", "feature")
self.git.write("d/Delta.java", fixture(p.NON_CE) + self.BODY)
self.git.commit("copy of a CE file under a new path")
scope = sorted(others + ["d/Delta.java"])
_, full, _ = self.check(scope=scope)
_, since, _ = self.check("--since", "master", scope=scope)
self.assertEqual(["d/Delta.java"], [row["path"] for row in since["files"]])
row = self.rows(full)["d/Delta.java"]
self.assertEqual(("unresolved", 1), (row["status"], len(row["copyCandidates"])))
self.assertEqual("b/Alpha.java", row["copyCandidates"][0]["path"])
self.assertEqual(row, self.rows(since)["d/Delta.java"])
def test_without_the_size_filter_git_searches_every_ce_file(self):
searched = []
copies = p.normalized_copies
def spy(mycila, source_refs, names, nonempty):
if "d/Delta.java" in names: # not the size probe
searched.append(sorted(key[0] for key in source_refs))
return copies(mycila, source_refs, names, nonempty)
with patch.object(p, "normalized_copies", spy):
self.check()
with patch.object(p, "size_filter_holds", return_value=False):
self.check()
filtered, unfiltered = searched
self.assertEqual(["b/Alpha.java", "e/Gamma.java"], filtered)
self.assertEqual(12, len(unfiltered))
def probe(self):
return p.size_filter_holds(this_repository(), fixture_plugin())
def test_size_filter_holds_for_the_installed_git(self):
self.assertTrue(self.probe())
def test_a_python_rule_that_no_longer_matches_git_turns_the_size_filter_off(self):
stricter = lambda size, destinations: any(100 * min(size, other) > p.COPY_SIMILARITY * max(size, other)
for other in destinations)
with patch.object(p, "could_be_copy", stricter):
self.assertFalse(self.probe())
def test_report_marks_the_size_filter_only_when_copies_were_searched(self):
_, report, _ = self.check()
self.assertEqual({"sizeFilter": True}, report["copySearch"])
self.git.write("d/Delta.java", fixture("apache") + "base implementation\n")
self.git.commit("Delta in CE as well")
with patch.object(p, "RELICENSING_COMMIT", "0" * 40), patch.object(p, "relicensed_ce_bases",
return_value=[self.git("rev-parse", "HEAD")]):
_, report, output = self.check()
self.assertEqual({"sizeFilter": None}, report["copySearch"])
self.assertNotIn("and the size rule of the copy search disagree", output)
def test_size_filter_is_off_when_git_answers_otherwise_on_either_side_of_the_boundary(self):
boundary = 1000 * p.COPY_SIMILARITY // 100 + 100 * p.COPY_SIMILARITY // 100 # 100 lines of 11 bytes
def git(at_boundary, below):
return lambda repo, plugin, source, destination: at_boundary if len(source) == boundary else below
for at_boundary, below, holds in ((True, False, True), # Git follows the rule
(True, True, False), # looser: a CE file below the boundary matches
(False, False, False), # the boundary pair does not match either
(False, True, False)):
with patch.object(p, "git_finds_copy", git(at_boundary, below)):
self.assertEqual(holds, self.probe(), (at_boundary, below))
def test_probe_pairs_sit_on_both_sides_of_the_boundary(self):
sizes = []
def finds(repo, plugin, source, destination):
sizes.append((len(source), len(destination)))
return len(source) % 2 == 0
with patch.dict(os.environ, {p.JOBS_VARIABLE: "1"}), patch.object(p, "git_finds_copy", finds):
self.assertTrue(self.probe())
(boundary, destination), (below, _) = sizes
self.assertEqual((boundary * 100, below), (p.COPY_SIMILARITY * destination, boundary - 1))
def test_size_filter_follows_the_configured_similarity(self):
with patch.object(p, "COPY_SIMILARITY", 60):
self.assertTrue(self.probe())
self.assertTrue(p.could_be_copy(600, [1000]))
self.assertFalse(p.could_be_copy(599, [1000]))
def test_a_file_grown_by_normalizing_fails_the_check(self):
def strip_headers(tool):
tool.removed, tool.stacked = {key: b"" for key in tool.contents}, set()
for key, content in list(tool.contents.items()):
tool.write(key, content + b"appended by a broken normalizer\n")
return {key: p.comparison_hash(content) for key, content in tool.contents.items()}
code, _, output = self.check(normalizer=strip_headers)
self.assertEqual(2, code)
self.assertIn("Mycila grew these files while removing their headers", output)
class CacheTests(unittest.TestCase):
LINES = CheckCommandTests.LINES
setUp = CheckCommandTests.setUp
check = CheckCommandTests.check
def normalizer(self, seen):
def strip_headers(tool):
seen.append(sorted(tool.contents))
tool.removed, tool.stacked = {}, set()
for key, body in list(tool.contents.items()):
first, _, rest = body.partition(b"\n")
header = first.startswith(b"// ")
tool.removed[key] = first + b"\n" if header else b""
tool.write(key, rest if header else body)
return {key: p.comparison_hash(body) for key, body in tool.contents.items()}
return strip_headers
def cache(self):
return self.repo / p.CACHE_DIRECTORY
def test_a_second_run_takes_ce_inputs_from_the_cache_and_reports_the_same(self):
first, second = [], []
_, cold, _ = self.check(normalizer=self.normalizer(first))
databases = {path.name: path.read_bytes() for path in self.cache().glob("*.sqlite")}
_, warm, output = self.check(normalizer=self.normalizer(second))
self.assertEqual(cold, warm)
self.assertTrue(any(key[0] != "head" for batch in first for key in batch))
self.assertEqual({"head"}, {key[0] for batch in second for key in batch})
# CI saves the cache only when its bytes changed: a run that only reads it must leave them as they were.
self.assertTrue(databases)
self.assertEqual(databases, {path.name: path.read_bytes() for path in self.cache().glob("*.sqlite")})
self.assertRegex(output, r"[1-9][0-9]* from the cache")
def test_without_the_cache_nothing_is_read_or_written(self):
self.check()
seen = []
_, report, output = self.check("--no-cache", normalizer=self.normalizer(seen))
self.assertTrue(any(key[0] != "head" for batch in seen for key in batch))
self.assertIn(" 0 from the cache", output)
shutil_tree = sorted(path.name for path in self.cache().iterdir())
self.check("--no-cache")
self.assertEqual(shutil_tree, sorted(path.name for path in self.cache().iterdir()))
def test_entries_are_keyed_by_content_and_file_name(self):
cache = p.NormalizationCache(temporary_directory(self), signature("signature"))
cache.put([(("A.java", "a"), b"// header\nbody\n", b"body\n")])
self.assertEqual({("moved/A.java", "b"): b"body\n"}, cache.get({("moved/A.java", "b"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("B.java", "b"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("A.xml", "a"): b"// header\nbody\n"}))
self.assertEqual({}, cache.get({("A.java", "a"): b"// header\nother\n"}))
cache.close()
def test_signature_follows_everything_that_shapes_normalization(self):
repo = temporary_directory(self)
for header, name in p.TEMPLATES.items():
(repo / name).parent.mkdir(parents=True, exist_ok=True)
(repo / name).write_text(f"fixture {header}\n")
signature = p.cache_signature(repo, fixture_plugin("1"))
self.assertEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("2")))
other = p.Plugin("1", ET.fromstring("<configuration><mapping><java>SLASHSTAR_STYLE</java></mapping></configuration>"))
self.assertNotEqual(signature, p.cache_signature(repo, other))
with patch.object(p, "CACHE_FORMAT", "other"):
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
(repo / p.TEMPLATES["apache"]).write_text("reworded\n")
self.assertNotEqual(signature, p.cache_signature(repo, fixture_plugin("1")))
def test_only_recent_signatures_are_kept(self):
directory = temporary_directory(self)
for index in range(p.CACHE_SIGNATURES_KEPT + 2):
stale = directory / f"{signature(f'old{index}')}.sqlite"
stale.write_bytes(b"")
os.utime(stale, (index, index))
cache = p.NormalizationCache(directory, signature("current"))
kept = sorted(path.name for path in directory.glob("*.sqlite"))
self.assertEqual(p.CACHE_SIGNATURES_KEPT, len(kept))
self.assertIn(f"{signature('current')}.sqlite", kept)
cache.close()
def test_a_damaged_cache_is_started_again(self):
directory = temporary_directory(self)
(directory / f"{signature('damaged')}.sqlite").write_bytes(b"not a database, cut off by a failed restore")
cache = p.NormalizationCache(directory, signature("damaged"))
self.assertEqual({}, cache.get({("A.java", "a"): b"raw"}))
cache.put([(("A.java", "a"), b"raw", b"normalized")])
cache.close()
self.assertEqual({("A.java", "a"): b"normalized"},
p.NormalizationCache(directory, signature("damaged")).get({("A.java", "a"): b"raw"}))
def test_a_cache_damaged_after_its_schema_is_started_again(self):
directory = temporary_directory(self)
cache = p.NormalizationCache(directory, signature("damaged"))
cache.put([((f"F{index}.java", "a"), f"raw {index}".encode(), b"normalized" * 400) for index in range(300)])
cache.close()
database = directory / f"{signature('damaged')}.sqlite"
page = 4096
with database.open("r+b") as file:
# The schema and the root pages stay readable, so the file opens; every lookup below them fails.
file.seek(4 * page)
file.write(b"\xff" * (database.stat().st_size - 4 * page))
cache = p.NormalizationCache(directory, signature("damaged"))
self.assertEqual({}, cache.get({("F0.java", "a"): b"raw 0"}))
cache.put([(("A.java", "a"), b"raw", b"normalized")])
cache.close()
self.assertEqual({("A.java", "a"): b"normalized"},
p.NormalizationCache(directory, signature("damaged")).get({("A.java", "a"): b"raw"}))
def test_the_cache_of_a_branch_checked_long_ago_survives_newer_signatures(self):
directory = temporary_directory(self)
p.NormalizationCache(directory, signature("revisited")).close()
os.utime(directory / f"{signature('revisited')}.sqlite", (1, 1))
for index in range(p.CACHE_SIGNATURES_KEPT):
(directory / f"{signature(f'newer{index}')}.sqlite").write_bytes(b"")
cache = p.NormalizationCache(directory, signature("revisited"))
cache.put([(("A.java", "a"), b"raw", b"normalized")])
cache.close()
self.assertTrue((directory / f"{signature('revisited')}.sqlite").exists())
def test_pruning_leaves_files_the_cache_did_not_create(self):
directory = temporary_directory(self)
foreign = [directory / name for name in ("notes.sqlite", "ABCDEF0123456789ABCDEF0123456789.sqlite", "other.db")]
for path in foreign:
path.write_bytes(b"")
os.utime(path, (1, 1))
for index in range(p.CACHE_SIGNATURES_KEPT):
(directory / f"{signature(f'newer{index}')}.sqlite").write_bytes(b"")
p.NormalizationCache(directory, signature("current")).close()
self.assertTrue(all(path.exists() for path in foreign))
self.assertEqual(p.CACHE_SIGNATURES_KEPT, len([path for path in directory.iterdir()
if p.CACHE_FILE.fullmatch(path.name)]))
def test_the_number_of_signatures_kept_can_be_set(self):
directory = temporary_directory(self)
for index in range(2):
stale = directory / f"{signature(f'old{index}')}.sqlite"
stale.write_bytes(b"")
os.utime(stale, (index, index))
with patch.dict(os.environ, {p.CACHE_SIGNATURES_VARIABLE: "1"}):
p.NormalizationCache(directory, signature("current")).close()
self.assertEqual([f"{signature('current')}.sqlite"], [path.name for path in directory.glob("*.sqlite")])
with patch.dict(os.environ, {p.CACHE_SIGNATURES_VARIABLE: "0"}), self.assertRaises(p.Failure):
p.NormalizationCache(directory, signature("current"))
def test_entries_are_committed_at_once_so_another_run_can_add_its_own(self):
directory = temporary_directory(self)
first = p.NormalizationCache(directory, signature("shared"))
second = p.NormalizationCache(directory, signature("shared"))
first.put([(("A.java", "a"), b"raw a", b"a")])
second.put([(("B.java", "b"), b"raw b", b"b")])
self.assertEqual({("B.java", "b"): b"b"}, first.get({("B.java", "b"): b"raw b"}))
self.assertEqual({("A.java", "a"): b"a"}, second.get({("A.java", "a"): b"raw a"}))
first.close()
second.close()
def test_a_cache_locked_by_another_run_is_skipped_and_kept(self):
directory = temporary_directory(self)
path = directory / f"{signature('locked')}.sqlite"
p.NormalizationCache(directory, signature("locked")).close()
other = sqlite3.connect(path, timeout=0)
other.execute("BEGIN EXCLUSIVE")
try:
with impatient_sqlite():
cache = p.NormalizationCache(directory, signature("locked"))
self.assertEqual({}, cache.get({("A.java", "a"): b"raw"}))
cache.put([(("A.java", "a"), b"raw", b"normalized")])
output = io.StringIO()
with redirect_stderr(output):
cache.close()
self.assertIn("continued without it", output.getvalue())
self.assertEqual(0, cache.added)
finally:
other.rollback()
other.close()
self.assertTrue(path.exists())
def test_a_lock_after_opening_downgrades_the_run_to_no_cache(self):
directory = temporary_directory(self)
path = directory / f"{signature('busy')}.sqlite"
with impatient_sqlite():
cache = p.NormalizationCache(directory, signature("busy"))
other = sqlite3.connect(path, timeout=0)
other.execute("BEGIN EXCLUSIVE")
try:
cache.put([(("A.java", "a"), b"raw", b"normalized")])
self.assertEqual({}, cache.get({("A.java", "a"): b"raw"}))
with redirect_stderr(io.StringIO()):
cache.close()
finally:
other.rollback()
other.close()
self.assertEqual(0, cache.added)
@unittest.skipUnless(os.environ.get("LICENSE_HEADERS_MAVEN_TESTS") == "1", "opt-in Maven fixtures")
class MavenTests(unittest.TestCase):
def test_scope_reports_respect_module_relative_exclusions(self):
repo = temporary_directory(self)
repo = temporary_directory(self).resolve() # macOS: /var/folders is a symlink to /private/var/folders
p.git(repo, "init")
(repo / "header.txt").write_text("SPDX-FileCopyrightText: Copyright Example\n"
"SPDX-License-Identifier: Apache-2.0\n")

1
ui-ngx/package.json

@ -145,7 +145,6 @@
"eslint-plugin-jsdoc": "^62.9.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"eslint-plugin-tailwindcss": "^3.18.3",
"ngrx-store-freeze": "^0.2.4",
"normalize-package-data": "8.0.0",
"packageurl-js": "2.0.1",
"patch-package": "^8.0.1",

2
ui-ngx/src/app/core/core.state.ts

@ -1,7 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { ActionReducerMap, MetaReducer } from '@ngrx/store';
import { storeFreeze } from 'ngrx-store-freeze';
import { environment as env } from '@env/environment';
@ -31,7 +30,6 @@ export const metaReducers: MetaReducer<AppState>[] = [
initStateFromLocalStorage
];
if (!env.production) {
metaReducers.unshift(storeFreeze);
metaReducers.unshift(debug);
}

63
ui-ngx/src/app/core/guards/auth.guard.ts

@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Injectable, NgZone } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { ActivatedRouteSnapshot, Data, Params, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { AuthService } from '../auth/auth.service';
import { select, Store } from '@ngrx/store';
import { AppState } from '../core.state';
@ -151,33 +151,19 @@ export class AuthGuard {
if (data.auth && data.auth.indexOf(authority) === -1) {
this.dialogService.forbidden();
return of(false);
} else if (isDefined(data.canActivate$)) {
return (data.canActivate$ as (userPermissionsService: UserPermissionsService, params: any) => Observable<boolean>)(this.userPermissionsService, params).pipe(
catchError(() => of(false)),
map((allow) => {
if (!allow) {
} else if (data.requiredMenuLink) {
return this.menuService.isMenuLinkAvailable(data.requiredMenuLink).pipe(
take(1),
mergeMap((available) => {
if (!available) {
this.dialogService.forbidden();
return of(false);
}
return allow;
})
);
} else if (isDefined(data.canActivate) && !data.canActivate(this.userPermissionsService)) {
this.dialogService.forbidden();
return of(false);
} else if (data.redirectTo) {
let redirect;
if (isObject(data.redirectTo)) {
redirect = data.redirectTo[authority];
} else {
redirect = data.redirectTo;
}
return this.menuService.getRedirectPath(path, redirect).pipe(
map((redirectPath) => {
return this.router.parseUrl(redirectPath);
return this.checkRouteData(data, params, path, authority);
})
);
} else {
return of(true);
return this.checkRouteData(data, params, path, authority);
}
}
}
@ -186,6 +172,37 @@ export class AuthGuard {
);
}
private checkRouteData(data: Data, params: Params, path: string, authority: Authority): Observable<boolean | UrlTree> {
if (isDefined(data.canActivate$)) {
return (data.canActivate$ as (userPermissionsService: UserPermissionsService, params: any) => Observable<boolean>)(this.userPermissionsService, params).pipe(
catchError(() => of(false)),
map((allow) => {
if (!allow) {
this.dialogService.forbidden();
}
return allow;
})
);
} else if (isDefined(data.canActivate) && !data.canActivate(this.userPermissionsService)) {
this.dialogService.forbidden();
return of(false);
} else if (data.redirectTo) {
let redirect;
if (isObject(data.redirectTo)) {
redirect = data.redirectTo[authority];
} else {
redirect = data.redirectTo;
}
return this.menuService.getRedirectPath(path, redirect).pipe(
map((redirectPath) => {
return this.router.parseUrl(redirectPath);
})
);
} else {
return of(true);
}
}
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {

9
ui-ngx/src/app/core/services/menu.service.ts

@ -5,7 +5,7 @@ import { Injectable } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { AppState } from '../core.state';
import { getCurrentOpenedMenuSections, selectAuth, selectIsAuthenticated } from '../auth/auth.selectors';
import { filter, map, take } from 'rxjs/operators';
import { distinctUntilChanged, filter, map, take } from 'rxjs/operators';
import {
buildUserHome,
buildUserMenu,
@ -249,6 +249,13 @@ export class MenuService {
);
}
public isMenuLinkAvailable(id: string): Observable<boolean> {
return this.menuLinkById(id).pipe(
map(link => !!link),
distinctUntilChanged()
);
}
public menuLinksByIds(ids: string[]): Observable<Array<MenuSection>> {
return this.availableMenuLinks$.pipe(
map((links) => links.filter(link => ids.includes(link.id)).sort((a, b) => {

4
ui-ngx/src/app/core/utils.ts

@ -1240,9 +1240,9 @@ export const getFilenameFromHttpHeader = (headers: HttpHeaders): string => {
if (filenameStarMatch && filenameStarMatch[1]) {
return decodeURIComponent(filenameStarMatch[1]);
}
const filenameMatch = /filename="([^"]+)"/i.exec(header);
const filenameMatch = /filename="((?:[^"\\]|\\.)+)"/i.exec(header);
if (filenameMatch && filenameMatch[1]) {
return filenameMatch[1];
return filenameMatch[1].replace(/\\(.)/g, '$1');
}
}
return headers.get('x-filename') ?? '';

3
ui-ngx/src/app/modules/home/components/converter/converter-dialog.component.html

@ -25,7 +25,8 @@
<tb-converter
#converterComponent
[entity]="converter"
[isEdit]="true">
[isEdit]="true"
[converterName]="converterName">
</tb-converter>
</div>
<div mat-dialog-actions class="flex items-center justify-end">

2
ui-ngx/src/app/modules/home/components/converter/converter-dialog.component.ts

@ -39,6 +39,7 @@ export class ConverterDialogComponent extends DialogComponent<ConverterDialogCom
isEdit: boolean;
dialogTitle:string;
converter: Converter;
converterName: string;
@ViewChild('converterComponent', {static: true}) converterComponent: ConverterComponent;
@ -55,6 +56,7 @@ export class ConverterDialogComponent extends DialogComponent<ConverterDialogCom
ngOnInit() {
const {disabledIntegrationType, ...converterInfo} = this.data.convertor
this.converter = converterInfo as Converter;
this.converterName = this.isEdit ? null : this.converter.name;
}
ngAfterViewInit() {

21
ui-ngx/src/app/modules/home/components/converter/converter.component.ts

@ -47,8 +47,8 @@ import {
} from '@shared/models/integration.models';
import { capitalize, deepClone, isDefinedAndNotNull, isEmptyStr, isNotEmptyStr } from '@core/utils';
import { NULL_UUID } from '@shared/models/id/has-uuid';
import { catchError, filter, map } from 'rxjs/operators';
import { forkJoin, merge, Observable, of, shareReplay } from 'rxjs';
import { catchError, filter, map, startWith } from 'rxjs/operators';
import { combineLatest, defer, forkJoin, merge, Observable, of, shareReplay } from 'rxjs';
import { ContentType } from '@shared/models/constants';
import { ConverterLibraryService } from '@core/http/converter-library.service';
import { EntityType } from '@shared/models/entity-type.models';
@ -197,13 +197,14 @@ export class ConverterComponent extends EntityComponent<Converter> implements On
}
private updateIntegrationsInfo(): void {
this.integrationInfo$ = this.entityForm.get('integrationType').valueChanges.pipe(
filter((integrationType) => !!integrationType),
map((integrationType: IntegrationType) => {
if (this.integrationsConvertersInfo) {
return this.integrationsConvertersInfo[integrationType];
}
}),
const typeControl = this.entityForm.get('integrationType');
// The type can be set before the template subscribes (e.g. preset from the integration form)
this.integrationInfo$ = combineLatest([
this.integrationService.getIntegrationsConvertersInfoCached(),
defer(() => typeControl.valueChanges.pipe(startWith(typeControl.value)))
]).pipe(
filter(([, type]) => !!type),
map(([info, type]) => info?.[type]),
shareReplay(1)
);
}
@ -268,7 +269,7 @@ export class ConverterComponent extends EntityComponent<Converter> implements On
}
this.updateForm(converter, false);
} else {
this.entityForm.get('name').patchValue('', {emitEvent: false});
this.entityForm.get('name').patchValue(this.predefinedConverterName ?? '', {emitEvent: false});
}
}

14
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-image-dialog.component.html

@ -23,13 +23,15 @@
<fieldset [disabled]="(isLoading$ | async) || (takingScreenshot$ | async)" class="flex flex-col items-stretch justify-center gap-2">
<div [formGroup]="dashboardRectFormGroup" class="flex flex-col items-center justify-center gap-2">
<mat-form-field class="rect-field" appearance="outline">
<mat-label>Top %</mat-label>
<mat-label>{{ 'position.top' | translate }}</mat-label>
<input matInput formControlName="top" type="number" step="1" min="0" max="100">
<span class="mr-2" matSuffix>%</span>
</mat-form-field>
<div class="flex flex-row items-center justify-center gap-2">
<mat-form-field class="rect-field" appearance="outline">
<mat-label>Left %</mat-label>
<mat-form-field class="rect-field" appearance="outline">
<mat-label>{{ 'position.left' | translate }}</mat-label>
<input matInput formControlName="left" type="number" step="1" min="0" max="100">
<span class="mr-2" matSuffix>%</span>
</mat-form-field>
<div class="tb-image-preview-container">
@if (!imageUrl) {
@ -39,13 +41,15 @@
}
</div>
<mat-form-field class="rect-field" appearance="outline">
<mat-label>Right %</mat-label>
<mat-label>{{ 'position.right' | translate }}</mat-label>
<input matInput formControlName="right" type="number" step="1" min="0" max="100">
<span class="mr-2" matSuffix>%</span>
</mat-form-field>
</div>
<mat-form-field class="rect-field" appearance="outline">
<mat-label>Bottom %</mat-label>
<mat-label>{{ 'position.bottom' | translate }}</mat-label>
<input matInput formControlName="bottom" type="number" step="1" min="0" max="100">
<span class="mr-2" matSuffix>%</span>
</mat-form-field>
</div>
<div class="flex flex-row items-center justify-center">

5
ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-image-dialog.component.scss

@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
$previewSize: 300px !default;
:host {
mat-form-field.rect-field {
max-width: 80px;
max-width: 96px;
}
.tb-image-preview {

14
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -237,7 +237,7 @@
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
<mat-icon class="tb-progress-success tb-update-reveal">check_circle</mat-icon>
}
@default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
@ -258,9 +258,6 @@
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-existing-' + plan.resolution | translate }}</span>
}
@if (plan.shared) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@ -277,14 +274,17 @@
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
@case ('success') {
<span class="tb-progress-status-done">{{ updateOutcomeOf(plan) | translate }}</span>
<span class="tb-progress-status-done tb-update-reveal">{{ updateOutcomeOf(plan) | translate }}</span>
}
@case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span>
}
@default {
@if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-no-conflicts' | translate }}</span>
<!-- A resolved name conflict shows the choice: Use existing, Overwrite or Create copy -->
@if (ws.reviewing && plan?.existing && plan.confirmed) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-install-' + plan.resolution | translate }}</span>
} @else if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ plannedOutcomeOf(plan) | translate }}</span>
}
}
}

33
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss

@ -25,6 +25,12 @@
flex-direction: column;
max-height: 90vh;
// The content takes the height left by the header and the actions, so a long form scrolls inside it
.mat-mdc-dialog-content {
flex: 1 1 auto;
min-height: 0;
}
@media #{$mat-lt-md} {
max-height: 100%;
height: 100%;
@ -49,8 +55,10 @@
flex: 1;
padding: 0;
}
// The current step fills the content area and scrolls itself: the stepper may give it overflow: hidden
.mat-horizontal-stepper-content.mat-horizontal-stepper-content-current {
height: 100%;
overflow-y: auto;
}
.mat-horizontal-stepper-header.mat-step-header {
padding: 0 12px;
@ -329,8 +337,8 @@
font-weight: 500;
line-height: 16px;
letter-spacing: 0.4px;
color: #305680;
background: rgba(48, 86, 128, 0.08);
color: var(--tb-primary-500);
background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent);
border-radius: 4px;
padding: 2px 8px;
}
@ -348,6 +356,27 @@
color: #198038;
}
// Update: the outcome of a row shows in when the row gets it
.tb-update-reveal {
display: inline-block;
animation: tb-update-reveal 200ms ease-out;
@media (prefers-reduced-motion: reduce) {
animation: none;
}
}
@keyframes tb-update-reveal {
from {
opacity: 0;
transform: scale(0.6);
}
to {
opacity: 1;
transform: scale(1);
}
}
.tb-progress-status-progress {
color: rgba(0, 0, 0, 0.54);
}

180
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

@ -68,7 +68,8 @@ export interface DeviceInstallDialogData {
item: MpItemVersionView;
reviewMode?: boolean;
selectedInstallMethod?: string;
installState?: Record<string, any>;
// Review mode: the installed package, whose install state the wizard shows
reviewed?: DeviceInstalledItemDescriptor;
entityGroupId?: string;
customerId?: string;
// Set when the wizard updates an installed package to the item version
@ -197,7 +198,7 @@ export interface WizardStep {
formFields?: FormFieldDefinition[];
// Fields the dialog adds on top of the package's form file
extraFormFields?: FormFieldDefinition[];
// Key of the step's form values in the install state; the label when not set
// Form: the key of its values in the install state
stateKey?: string;
// Update: the keys of the form's fields the installed version didn't have
newFieldKeys?: Set<string>;
@ -224,6 +225,8 @@ export interface ConnectionCheck {
}
const ENTITY_STEP_MIN_DELAY = 2000;
// Update: the rows show the outcome of the one request one after another, this far apart
const UPDATE_REVEAL_INTERVAL = 150;
// Where the wizard keeps the converter it builds for a step with "default": true, as if the package had that file
const DEFAULT_CONVERTER_PATH = 'tb-default-converter/';
const DEFAULT_RANDOM_SIZE = 20;
@ -462,10 +465,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
console.error('Failed to fetch connectivity settings', _e);
}
// Review mode: restore state and start wizard with stored values
if (this.data.reviewMode && this.data.installState && this.data.selectedInstallMethod) {
if (this.data.reviewMode && this.data.reviewed?.installState && this.data.selectedInstallMethod) {
this.reviewMode = true;
this.selectedInstallMethod = this.data.selectedInstallMethod;
this.restoreInstallState(this.data.installState);
this.restoreInstallState();
this.startWizard();
// After startWizard: the transport fields it adds take part in resolving the file
this.resolveGatewayDockerCompose();
@ -1049,24 +1052,21 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// --- Private ---
/** withFormValues false: only the entity outputs, e.g. to keep the values the user has just entered. */
private restoreInstallState(installState: Record<string, any>, withFormValues = true): void {
for (const [stepName, data] of Object.entries(installState)) {
if (withFormValues && data.formValues) {
Object.assign(this.formValues, data.formValues);
}
if (data.entityOutput) {
// Find the step type alias from the raw steps to set the correct entity output key
const rawSteps = this.packageInfo.installSteps[this.selectedInstallMethod] || [];
const matchingStep = rawSteps.find(s => this.stateKeysOf(s).includes(stepName)) ??
// Update: a step the new version renamed or gave an id
(this.data.update ? rawSteps.find(s => this.storedStateOf(s)?.key === stepName) : undefined);
if (matchingStep) {
const alias = stepTypeAliasMap[matchingStep.type];
if (alias) {
this.entityOutputs.set(alias, data.entityOutput);
}
}
/**
* Takes the installed package's form values and the outputs of its entity steps, by alias.
* withFormValues false: only the entity outputs, e.g. to keep the values the user has just entered.
*/
private restoreInstallState(withFormValues = true): void {
if (withFormValues) {
for (const state of Object.values(this.installedDescriptor?.installState ?? {})) {
Object.assign(this.formValues, state?.formValues);
}
}
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] || []) {
const alias = stepTypeAliasMap[step.type];
const output = alias ? this.storedStateOf(step)?.state.entityOutput : undefined;
if (output) {
this.entityOutputs.set(alias, output);
}
}
}
@ -1088,7 +1088,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
if (this.data.update) {
// The instructions before the Update step refer to the installed entities, e.g. ${device.token}
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
}
this.buildWizardSteps();
this.wizardStarted = true;
@ -1159,7 +1159,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.wizardSteps.push({
type: 'form',
label: step.name,
stateKey: step.id,
stateKey: this.stateKeyOf(step),
rawSteps: [step],
completed: this.reviewMode
});
@ -1302,7 +1302,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// except the transport fields, which take the current Device connectivity settings; otherwise use defaults
let storedValues: Record<string, any> | undefined;
if (this.reviewMode) {
storedValues = this.data.installState?.[ws.stateKey ?? ws.label]?.formValues;
storedValues = this.installedDescriptor.installState[ws.stateKey]?.formValues;
} else if (this.data.update && ws.stateKey !== TRANSPORT_STEP_STATE_KEY && ws.rawSteps[0]) {
// Also when the new version renamed the step
storedValues = this.storedStateOf(ws.rawSteps[0])?.state.formValues;
@ -1462,15 +1462,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private showCompletedEntitySteps(ws: WizardStep): void {
ws.entitySteps = ws.rawSteps.map(s => {
const alias = stepTypeAliasMap[s.type];
const output = alias ? this.entityOutputs.get(alias) : null;
const key = this.stateKeysOf(s).find(k => this.data.installState?.[k]);
const storedState = key ? this.data.installState[key] : undefined;
const storedState = this.storedStateOf(s)?.state;
return {
step: s,
status: 'success' as const,
resolvedName: this.resolveVariables(s.name),
entityOutput: output || undefined,
entityOutput: storedState?.entityOutput,
resolution: storedState?.resolution || 'created'
};
});
@ -1507,6 +1504,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
private async runEntitySteps(ws: WizardStep): Promise<void> {
const duplicateKey = this.duplicateStateKey();
if (duplicateKey) {
ws.progressError = this.translate.instant('iot-hub.device-install-duplicate-step', { key: duplicateKey });
this.cdr.detectChanges();
return;
}
for (const ep of ws.entitySteps) {
if (ep.status === 'success') {
continue;
@ -1943,7 +1946,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/** The metadata entries resolved with the form values the package was installed with, as the text-only update has no forms. */
private metadataWithInstalledValues(step: DeviceInstallStep): Record<string, string | null> | undefined {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
try {
return this.integrationMetadataOf(step);
} finally {
@ -2121,12 +2124,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
}
/** Update: what the update will do with the entity of a row; the same as updateOutcomeOf says once it succeeded. */
plannedOutcomeOf(plan: EntityStepPlan): string {
return { update: 'iot-hub.device-update-will-update', create: 'iot-hub.device-update-will-create',
keep: 'iot-hub.device-update-no-changes' }[this.outcomeOf(plan)];
}
/** Update: what the update did with the entity of a row, once it succeeded. */
updateOutcomeOf(plan: EntityStepPlan | undefined): string {
return { update: 'iot-hub.device-update-updated', create: 'iot-hub.device-update-created',
keep: 'iot-hub.device-update-skipped' }[this.outcomeOf(plan)];
}
/**
* Update: an entity kept or used as it is counts as not changed, even an integration the server adds the step's
* metadata entries to; one a name conflict resolves to overwrite counts as updated.
*/
private outcomeOf(plan: EntityStepPlan | undefined): 'update' | 'create' | 'keep' {
if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') {
return 'iot-hub.done';
return 'keep';
}
return plan.action === 'overwrite' || plan.resolution === 'overwrite' ? 'iot-hub.device-update-updated' : 'iot-hub.device-update-created';
return plan.action === 'create' && plan.resolution !== 'overwrite' ? 'create' : 'update';
}
textWithLink(key: string): { before: string; link: string; after: string } {
@ -2152,7 +2170,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/**
* Update: sends what the check planned to the server, which applies all of it in one transaction together with
* the new version of the installed item, or nothing. The rows run together: the request is one.
* the new version of the installed item, or nothing. The rows run together: the request is one. A success shows
* row by row, and the update counts as running until the last row shows it.
*/
async runUpdate(ws: WizardStep): Promise<void> {
ws.reviewing = false;
@ -2175,23 +2194,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} catch (e: any) {
result = { success: false, errorMessage: this.failureMessage(e) };
}
ws.updating = false;
if (!result.success) {
ws.updating = false;
// Nothing was changed: the transaction was rolled back
const message = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error');
for (const ep of ws.entitySteps) {
const failed = ep.step.name === result.failedStep;
const failed = this.stateKeyOf(ep.step) === result.failedStep;
ep.status = failed ? 'error' : 'skipped';
ep.errorMessage = failed ? message : null;
}
ws.progressError = message;
// The steps refer to the installed entities again
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
this.cdr.detectChanges();
return;
}
for (const ep of ws.entitySteps) {
const output = result.outputs?.[ep.step.name];
const interval = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ? 0 : UPDATE_REVEAL_INTERVAL;
for (const [index, ep] of ws.entitySteps.entries()) {
if (index > 0 && interval) {
await this.delay(interval);
}
const output = result.outputs?.[this.stateKeyOf(ep.step)];
const plan = this.entityPlans.get(ep);
const resolution = plan?.previous?.resolution ?? plan?.resolution ?? 'created';
if (output) {
@ -2202,8 +2225,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.markEntityStepSuccess(ws, ep, entityOutput, resolution);
} else {
ep.status = 'success';
this.cdr.detectChanges();
}
}
ws.updating = false;
this.installRegistered = true;
ws.progressDone = true;
ws.completed = true;
@ -2215,7 +2240,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const state: Record<string, any> = {};
for (const ws of this.wizardSteps) {
if (ws.type === 'form' && ws.formGroup) {
state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() };
state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() };
}
}
return state;
@ -2402,7 +2427,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
* the update shows that someone changed it.
*/
private async checkDefaultConverters(): Promise<void> {
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
let ownDefaultConverterIds: Set<string> | undefined;
try {
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
@ -2446,7 +2471,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!this.previousPackageInfo) {
return false;
}
this.restoreInstallState(this.data.update.descriptor.installState ?? {});
this.restoreInstallState();
try {
return (this.packageInfo.installSteps[this.selectedInstallMethod] ?? []).every(step => {
if (step.type === InstallStepType.SHOW_FORM) {
@ -2491,7 +2516,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
const formValues = step.type === InstallStepType.SHOW_FORM ? this.storedStateOf(step)?.state.formValues : undefined;
if (formValues) {
formState[step.id ?? step.name] = { formValues };
formState[this.stateKeyOf(step)] = { formValues };
}
}
try {
@ -2576,25 +2601,62 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return !!descriptor?.createdEntityIds?.some(created => created.id === id) && !usedExisting;
}
/** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */
private stateKeysOf(step: DeviceInstallStep): string[] {
return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)];
/** The installed package: the one the wizard updates, or the one review mode shows. */
private get installedDescriptor(): DeviceInstalledItemDescriptor | undefined {
return this.data.update?.descriptor ?? this.data.reviewed;
}
/**
* The key of the step's install state: its id, or else its type and name, so that two steps of an install method
* never share it. A form without an id keeps its name, which no entity step's type-and-name key equals; a step id
* equal to a form's name is caught by the duplicate check on install, and by the server on update.
* The server keys the steps of an update the same way.
*/
private stateKeyOf(step: DeviceInstallStep): string {
return step.id ?? (step.type === InstallStepType.SHOW_FORM ? step.name : `${step.type}:${step.name}`);
}
/**
* Update: the install state of a step of the new version, under the key of the installed step it replaces.
* A key two steps of the install method share (forms included: a form's values are saved under its key too), so one's
* install state would overwrite the other's; null when none.
*/
private duplicateStateKey(): string | null {
const keys = new Set<string>();
for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) {
if (step.type !== InstallStepType.SHOW_FORM && !ENTITY_STEP_TYPES.has(step.type)) {
continue;
}
const key = this.stateKeyOf(step);
if (keys.has(key)) {
return key;
}
keys.add(key);
}
return null;
}
/**
* The installed package's install state of a step; in an update, under the key of the installed step it replaces.
* Without the installed version's steps (e.g. it can't be downloaded any more), a step that has gained an id
* is also looked up under its own name, which the installed version keyed it by.
* is also looked up as the installed version had it, without the id.
*/
private storedStateOf(step: DeviceInstallStep): { key: string; state: any } | undefined {
const installState = this.data.update?.descriptor.installState ?? {};
const previousStep = this.findPreviousStep(step);
const keys = [...(previousStep ? this.stateKeysOf(previousStep) : []), ...this.stateKeysOf(step)];
if (!this.previousPackageInfo && step.id) {
keys.push(step.name, this.resolveVariables(step.name));
}
const key = keys.find(k => k && installState[k]);
return key ? { key, state: installState[key] } : undefined;
const installState = this.installedDescriptor?.installState ?? {};
const steps = [this.findPreviousStep(step), step,
this.data.update && !this.previousPackageInfo && step.id ? { ...step, id: undefined } : undefined]
.filter((s): s is DeviceInstallStep => !!s);
const key = steps.map(s => this.stateKeyOf(s)).find(k => installState[k]);
if (key) {
return { key, state: installState[key] };
}
// Legacy: an entity step without an id was keyed by its name, as written or resolved, so a later step of the same
// name overwrote its state. Such a state is the step's only when it records an entity of the step's type.
const entityType = this.stepTypeToEntityType(step.type);
const legacyKey = steps.filter(s => !s.id && s.type !== InstallStepType.SHOW_FORM)
.flatMap(s => [s.name, this.resolveVariables(s.name)])
.find(k => installState[k] && this.installedDescriptor.createdEntityIds?.some(
created => created.id === installState[k].entityOutput?.id && created.entityType === entityType));
return legacyKey ? { key: legacyKey, state: installState[legacyKey] } : undefined;
}
private formStepChanged(step: DeviceInstallStep): boolean {
@ -2651,7 +2713,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private async checkUpdate(ws: WizardStep): Promise<void> {
const run = ++this.updateCheckRun;
// Templates refer to the package's entities, e.g. ${deviceProfile.id}: until the steps run, the installed ones
this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false);
this.restoreInstallState(false);
ws.entitySteps = ws.rawSteps.map(s => ({
step: s,
status: 'pending' as const,
@ -2842,12 +2904,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const state: Record<string, any> = {};
for (const ws of this.wizardSteps) {
if (ws.type === 'form' && ws.formGroup) {
state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() };
state[ws.stateKey] = { formValues: ws.formGroup.getRawValue() };
} else if (ws.type === 'progress' && ws.entitySteps) {
for (const ep of ws.entitySteps) {
if (ep.status === 'success' && ep.entityOutput) {
const metadata = this.addedMetadataOf(ep.step);
state[ep.step.id ?? ep.step.name] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created',
state[this.stateKeyOf(ep.step)] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created',
...(ep.step.default ? { defaultConverter: true } : {}), ...(metadata ? { metadata } : {}) };
}
}

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -239,7 +239,7 @@ export class IotHubActionsService {
return this.openDeviceInstallDialog(item, {
reviewMode: true,
selectedInstallMethod: deviceDescriptor.selectedInstallMethod,
installState: deviceDescriptor.installState
reviewed: deviceDescriptor
});
}
@ -265,7 +265,7 @@ export class IotHubActionsService {
}
private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
options?: { reviewMode?: boolean; selectedInstallMethod?: string; reviewed?: DeviceInstalledItemDescriptor;
entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable<any> {
return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, {
panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'],

30
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html

@ -11,11 +11,33 @@
<div class="tb-converter-update-name">{{ data.update.converter.name }}</div>
@if (data.usedBy.length) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span>
<ul class="tb-converter-update-packages">
@for (name of data.usedBy; track $index) {
<li>{{ name }}</li>
<div>
<ul class="tb-converter-update-packages">
@for (name of usedByShown; track $index) {
<li>{{ name }}</li>
}
</ul>
@if (usedByHidden.length) {
<div id="tb-converter-update-more" class="tb-converter-update-more" [class.expanded]="usedByExpanded"
[attr.aria-hidden]="!usedByExpanded">
<ul class="tb-converter-update-packages">
@for (name of usedByHidden; track $index) {
<li>{{ name }}</li>
}
</ul>
</div>
}
</ul>
</div>
@if (usedByHidden.length) {
<button type="button" class="tb-converter-update-toggle self-start" aria-controls="tb-converter-update-more"
[attr.aria-expanded]="usedByExpanded" (click)="usedByExpanded = !usedByExpanded">
@if (usedByExpanded) {
{{ 'iot-hub.device-update-shared-less' | translate }}
} @else {
{{ 'iot-hub.device-update-shared-more' | translate:{ count: usedByHidden.length } }}
}
</button>
}
}
@if (data.modified) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">

32
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss

@ -43,6 +43,38 @@
color: rgba(0, 0, 0, 0.54);
}
// Material expansion-panel timing
.tb-converter-update-more {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 225ms cubic-bezier(0.4, 0, 0.2, 1);
> ul {
overflow: hidden;
min-height: 0;
}
&.expanded {
grid-template-rows: 1fr;
}
@media (prefers-reduced-motion: reduce) {
transition: none;
}
}
.tb-converter-update-toggle {
padding: 0;
border: none;
background: none;
font-size: 12px;
font-weight: 500;
line-height: 16px;
color: var(--tb-primary-500);
cursor: pointer;
&:hover,
&:focus-visible {
text-decoration: underline;
}
}
.tb-converter-update-link {
color: #305680;
text-decoration: underline;

9
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts

@ -21,6 +21,8 @@ export interface IotHubConverterUpdateDialogData {
usedBy: string[];
}
const USED_BY_SHOWN = 3;
/**
* Brings an installed device package's default converter to ThingsBoard's default converter now, without a new version of
* the package. Closes with true once it is updated.
@ -34,6 +36,9 @@ export interface IotHubConverterUpdateDialogData {
export class TbIotHubConverterUpdateDialogComponent extends DialogComponent<TbIotHubConverterUpdateDialogComponent, boolean> {
readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified'));
readonly usedByShown: string[];
readonly usedByHidden: string[];
usedByExpanded = false;
updating = false;
errorMessage: string | null = null;
@ -46,6 +51,10 @@ export class TbIotHubConverterUpdateDialogComponent extends DialogComponent<TbIo
private translate: TranslateService
) {
super(store, router, dialogRef);
// Collapse only when at least 2 packages would be hidden
const shownCount = data.usedBy.length > USED_BY_SHOWN + 1 ? USED_BY_SHOWN : data.usedBy.length;
this.usedByShown = data.usedBy.slice(0, shownCount);
this.usedByHidden = data.usedBy.slice(shownCount);
}
downloadCurrent(): void {

1
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -113,6 +113,7 @@ export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, ex
installState: {},
steps: [{
name: update.converter.name,
// The server keys the step's state by its id: the state stays under the key it has
id: update.stateKey,
type: 'UPLINK_CONVERTER',
action: 'OVERWRITE',

9
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html

@ -9,7 +9,14 @@
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-delete-desc">{{ description }}</p>
@if (keptReferences) {
<tb-image-references [references]="keptReferences"></tb-image-references>
<div class="tb-form-hint tb-primary-fill">
<mat-icon>info_outline</mat-icon>
<div class="flex flex-col">
<div class="font-medium">{{ keptTitle }}</div>
<div>{{ keptReason }}</div>
<tb-image-references class="mt-3" [references]="keptReferences"></tb-image-references>
</div>
</div>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -32,6 +32,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
// A device package keeps the entities other installed packages use, and the dialog lists them before the user confirms
keptReferences: ResourceReferences | null = null;
keptTitle: string;
keptReason: string;
constructor(
protected store: Store<AppState>,
@ -42,15 +44,15 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
private translate: TranslateService
) {
super(store, router, dialogRef);
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const kept = data.keptEntities;
if (kept?.entities.length) {
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
// Kept because other packages use them, because the user had them before the package, or both
const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' :
!kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used';
this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length });
} else {
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' :
!kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used';
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length });
this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length });
}
}

12
ui-ngx/src/app/modules/home/components/notification/notification-bell.component.html

@ -5,8 +5,10 @@
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<button mat-icon-button #showNotificationButton (click)="showNotification($event, showNotificationButton)">
<tb-icon aria-hidden="false" [matBadge]="(count$ | async)" [matBadgeHidden]="!(count$ | async)" matBadgeColor="warn" matBadgeSize="small">
{{ (wl.isPrimaryColorPanels$() | async) ? 'notifications' : 'notifications_none' }}
</tb-icon>
</button>
@if (available$ | async) {
<button mat-icon-button #showNotificationButton (click)="showNotification($event, showNotificationButton)">
<tb-icon aria-hidden="false" [matBadge]="(count$ | async)" [matBadgeHidden]="!(count$ | async)" matBadgeColor="warn" matBadgeSize="small">
{{ (wl.isPrimaryColorPanels$() | async) ? 'notifications' : 'notifications_none' }}
</tb-icon>
</button>
}

33
ui-ngx/src/app/modules/home/components/notification/notification-bell.component.ts

@ -11,8 +11,8 @@ import {
ViewContainerRef
} from '@angular/core';
import { NotificationWebsocketService } from '@core/ws/notification-websocket.service';
import { BehaviorSubject, ReplaySubject, Subscription } from 'rxjs';
import { distinctUntilChanged, map, share, skip, tap } from 'rxjs/operators';
import { BehaviorSubject, combineLatest, ReplaySubject, Subject, Subscription } from 'rxjs';
import { distinctUntilChanged, map, share, shareReplay, skip, takeUntil, tap } from 'rxjs/operators';
import { MatIconButton } from '@angular/material/button';
import { TbPopoverService } from '@shared/components/popover.service';
import { ShowNotificationPopoverComponent } from '@home/components/notification/show-notification-popover.component';
@ -21,6 +21,8 @@ import { select, Store } from '@ngrx/store';
import { selectIsAuthenticated } from '@core/auth/auth.selectors';
import { AppState } from '@core/core.state';
import { WhiteLabelingService } from '@core/http/white-labeling.service';
import { MenuService } from '@core/services/menu.service';
import { MenuId } from '@core/services/menu.models';
@Component({
selector: 'tb-notification-bell',
@ -33,6 +35,11 @@ export class NotificationBellComponent implements OnDestroy {
private notificationSubscriber: NotificationSubscriber;
private notificationCountSubscriber: Subscription;
private countSubject = new BehaviorSubject(0);
private destroy$ = new Subject<void>();
readonly available$ = this.menuService.isMenuLinkAvailable(MenuId.notification_inbox).pipe(
shareReplay({bufferSize: 1, refCount: true})
);
count$ = this.countSubject.asObservable().pipe(
distinctUntilChanged(),
@ -51,15 +58,25 @@ export class NotificationBellComponent implements OnDestroy {
private renderer: Renderer2,
private viewContainerRef: ViewContainerRef,
private store: Store<AppState>,
private menuService: MenuService,
public wl: WhiteLabelingService) {
this.store.pipe(select(selectIsAuthenticated)).subscribe((value) => {
if (value) {
combineLatest([
this.store.pipe(select(selectIsAuthenticated)),
this.available$
]).pipe(
takeUntil(this.destroy$)
).subscribe(([authenticated, available]) => {
if (authenticated && available) {
this.initSubscription();
} else {
this.unsubscribeSubscription();
}
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
this.unsubscribeSubscription();
}
@ -89,6 +106,9 @@ export class NotificationBellComponent implements OnDestroy {
}
private initSubscription() {
if (this.notificationSubscriber) {
return;
}
this.notificationSubscriber = NotificationSubscriber.createNotificationCountSubscription(this.notificationWsService, this.zone);
this.notificationCountSubscriber = this.notificationSubscriber.notificationCount$.pipe(
skip(1),
@ -98,8 +118,9 @@ export class NotificationBellComponent implements OnDestroy {
}
private unsubscribeSubscription() {
this.notificationCountSubscriber.unsubscribe();
this.notificationSubscriber.unsubscribe();
this.notificationCountSubscriber?.unsubscribe();
this.notificationCountSubscriber = null;
this.notificationSubscriber?.unsubscribe();
this.notificationSubscriber = null;
}
}

2
ui-ngx/src/app/modules/home/components/router-tabs.component.html

@ -14,7 +14,7 @@
[class.tb-router-tabs-container-bordered]="showTabsBar || (!hideTabs && !!tabsHeaderComponentRef)">
@if (showTabsBar) {
<nav mat-tab-nav-bar mat-stretch-tabs="false" class="tb-router-tabs flex-1" [tabPanel]="tabPanel">
@for (tab of tabs; track tab) {
@for (tab of tabs; track tab.path) {
<a
routerLink="{{tab.path}}"
replaceUrl="{{ replaceUrl }}"

28
ui-ngx/src/app/modules/home/components/router-tabs.component.ts

@ -8,7 +8,7 @@ import { AppState } from '@core/core.state';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { MenuService } from '@core/services/menu.service';
import { distinctUntilChanged, filter, map, mergeMap, startWith, take } from 'rxjs/operators';
import { merge, Observable } from 'rxjs';
import { combineLatest, merge, Observable } from 'rxjs';
import { MenuSection, menuSectionMap } from '@core/services/menu.models';
import { ActiveComponentService } from '@core/services/active-component.service';
import { TbAnchorComponent } from '@shared/components/tb-anchor.component';
@ -54,10 +54,14 @@ export class RouterTabsComponent extends PageComponent implements OnInit {
viewContainerRef.createComponent(this.replaceComponent);
} else {
if (this.activatedRoute.snapshot.data.useChildrenRoutesForTabs) {
this.tabs$ = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
startWith(''),
map(() => this.buildTabsForRoutes(this.activatedRoute))
this.tabs$ = combineLatest([
this.router.events.pipe(
filter((event) => event instanceof NavigationEnd),
startWith('')
),
this.menuService.availableMenuLinks()
]).pipe(
map(([, menuLinks]) => this.buildTabsForRoutes(this.activatedRoute, menuLinks))
);
} else {
this.tabs$ = merge(this.menuService.menuSections(),
@ -115,19 +119,17 @@ export class RouterTabsComponent extends PageComponent implements OnInit {
return [];
}
private buildTabsForRoutes(activatedRoute: ActivatedRoute): Array<MenuSection> {
private buildTabsForRoutes(activatedRoute: ActivatedRoute, menuLinks: Array<MenuSection>): Array<MenuSection> {
const sectionPath = this.getSectionPath(activatedRoute);
const authority = getCurrentAuthUser(this.store).authority;
const children = activatedRoute.routeConfig.children.filter(page => {
if (page.path !== '') {
if (page.data?.auth) {
return page.data?.auth.includes(authority);
} else {
return true;
}
} else {
if (page.path === '') {
return false;
}
if (page.data?.auth && !page.data.auth.includes(authority)) {
return false;
}
return !page.data?.requiredMenuLink || menuLinks.some(link => link.id === page.data.requiredMenuLink);
});
if (children.length) {
return children.map(tab => {

2
ui-ngx/src/app/modules/home/components/rule-node/action/gps-geo-action-config.component.html

@ -78,7 +78,7 @@
!geoActionConfigForm.get('fetchPerimeterInfoFromMessageMetadata').value) {
<div class="flex flex-col">
<div class="flex flex-row gap-4">
<mat-form-field class="flex-1">
<mat-form-field class="flex-1" appearance="outline">
<mat-label>{{ 'rule-node-config.circle-center-latitude' | translate }}</mat-label>
<input type="number" min="-90" max="90" step="0.1" matInput formControlName="centerLatitude" required>
@if (geoActionConfigForm.get('centerLatitude').hasError('required')) {

4
ui-ngx/src/app/modules/home/pages/notification/notification-routing.module.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { RouterModule, Routes } from '@angular/router';
import { Authority } from '@shared/models/authority.enum';
import { NgModule } from '@angular/core';
@ -38,6 +39,7 @@ const routes: Routes = [
component: EntitiesTableComponent,
data: {
auth: [Authority.TENANT_ADMIN, Authority.CUSTOMER_USER, Authority.SYS_ADMIN],
requiredMenuLink: MenuId.notification_inbox,
title: 'notification.inbox',
breadcrumb: {
menuId: MenuId.notification_inbox

16
ui-ngx/src/app/modules/home/pages/notification/rule/rule-notification-dialog.component.ts

@ -10,6 +10,7 @@ import {
ComponentLifecycleEventTranslationMap,
DeviceEvent,
DeviceEventTranslationMap,
isSysAdminNotificationType,
NotificationRule,
NotificationTarget,
TriggerType,
@ -552,19 +553,8 @@ export class RuleNotificationDialogComponent extends
}
private allowTriggerTypes(): TriggerType[] {
const sysAdminAllowTriggerTypes = new Set([
TriggerType.ENTITIES_LIMIT,
TriggerType.API_USAGE_LIMIT,
TriggerType.NEW_PLATFORM_VERSION,
TriggerType.RATE_LIMITS,
TriggerType.TASK_PROCESSING_FAILURE,
TriggerType.RESOURCES_SHORTAGE
]);
if (this.isSysAdmin()) {
return Array.from(sysAdminAllowTriggerTypes);
}
return Object.values(TriggerType).filter(type => !sysAdminAllowTriggerTypes.has(type));
const isSysAdmin = this.isSysAdmin();
return Object.values(TriggerType).filter(type => isSysAdminNotificationType(type) === isSysAdmin);
}
get allowEntityTypeForEntityAction(): EntityType[] {

40
ui-ngx/src/app/modules/home/pages/notification/settings/notification-setting-form.component.html

@ -5,31 +5,25 @@
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<form [formGroup]="notificationSettingsFormGroup" class="flex flex-col">
<div class="flex flex-row" style="height: 48px;">
<div class="flex max-w-50% flex-full items-center justify-start">
<form [formGroup]="notificationSettingsFormGroup" class="contents">
<div class="col-span-full grid h-12 grid-cols-subgrid items-center">
<mat-checkbox color="primary"
[disabled]="disabled"
(click)="$event.stopPropagation()"
(change)="changeInstanceTypeCheckBox($event.checked)"
[checked]="getChecked()"
[indeterminate]="getIndeterminate()">
<span class="notification-type"
[class.notification-type-disabled]="!notificationSettingsFormGroup.get('enabled').value">
{{notificationTemplateTypeTranslateMap.get(notificationSettingsFormGroup.get('name').value)?.name | translate}}
</span>
</mat-checkbox>
@for (deliveryMethod of deliveryMethods; track deliveryMethod) {
<mat-checkbox color="primary"
[disabled]="disabled"
(click)="$event.stopPropagation()"
(change)="changeInstanceTypeCheckBox($event.checked)"
[checked]="getChecked()"
[indeterminate]="getIndeterminate()">
<span class="notification-type"
[class.notification-type-disabled]="!notificationSettingsFormGroup.get('enabled').value">
{{notificationTemplateTypeTranslateMap.get(notificationSettingsFormGroup.get('name').value)?.name | translate}}
</span>
</mat-checkbox>
</div>
@for (deliveryMethod of deliveryMethods; track deliveryMethod) {
<div class="flex flex-1 flex-row">
<div class="flex flex-1 items-center justify-start">
<mat-checkbox color="primary"
[disabled]="disabled"
[checked]="getChecked(deliveryMethod)"
(click)="toggleDeliviryMethod(deliveryMethod)"
></mat-checkbox>
</div>
</div>
[checked]="getChecked(deliveryMethod)"
(click)="toggleDeliviryMethod(deliveryMethod)"
></mat-checkbox>
}
</div>
</form>

4
ui-ngx/src/app/modules/home/pages/notification/settings/notification-setting-form.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR, UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { deepClone, isDefinedAndNotNull } from '@core/utils';
@ -21,6 +22,7 @@ import {
multi: true
}
],
host: { class: 'contents' },
standalone: false
})
export class NotificationSettingFormComponent implements ControlValueAccessor, OnInit, OnDestroy {

2
ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings-routing.modules.ts

@ -7,6 +7,7 @@ import { Authority } from '@shared/models/authority.enum';
import { inject } from '@angular/core';
import { NotificationSettingsComponent } from '@home/pages/notification/settings/notification-settings.component';
import { NotificationService } from '@core/http/notification.service';
import { MenuId } from '@core/services/menu.models';
export const notificationUserSettingsRoutes: Routes = [
{
@ -15,6 +16,7 @@ export const notificationUserSettingsRoutes: Routes = [
canDeactivate: [ConfirmOnExitGuard],
data: {
auth: [Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER],
requiredMenuLink: MenuId.notification_inbox,
title: 'account.notification-settings',
breadcrumb: {
label: 'account.notification-settings',

54
ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.html

@ -5,8 +5,8 @@
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<div>
<mat-card appearance="outlined" class="settings-card tb-absolute-fill">
<div class="notification-settings tb-absolute-fill">
<mat-card appearance="outlined" class="settings-card">
<mat-card-header>
<div class="flex flex-1 flex-row items-start justify-between xs:flex-col xs:justify-start xs:gap-2">
<div class="flex flex-1 flex-col">
@ -30,9 +30,10 @@
<mat-card-content style="padding-top: 16px; overflow: hidden;">
<form [formGroup]="notificationSettings" class="notification-form">
<section class="notification-section">
<div class="notification-section-block">
<div class="flex flex-row items-center justify-start" style="height: 44px;">
<div class="max-w-50% flex-full">
<div class="notification-section-block"
[style.--tb-notification-delivery-methods-count]="notificationDeliveryMethods?.length ?? 0">
<div class="notification-header col-span-full grid grid-cols-subgrid">
<div class="col-span-full grid h-11 grid-cols-subgrid items-center">
<mat-checkbox color="warn"
[disabled]="readonly"
(click)="$event.stopPropagation()"
@ -41,32 +42,27 @@
[checked]="getChecked()">
<mat-label translate>notification.settings.type</mat-label>
</mat-checkbox>
</div>
@for (deliveryMethods of notificationDeliveryMethods; track deliveryMethods) {
<div class="flex-1">
<div class="flex flex-1 items-center justify-start">
<mat-checkbox color="warn"
[disabled]="readonly"
[checked]="getChecked(deliveryMethods)"
(change)="changeInstanceTypeCheckBox($event.checked, deliveryMethods)"
[indeterminate]="getIndeterminate(deliveryMethods)"
(click)="$event.stopPropagation()">
<mat-label>{{ notificationDeliveryMethodInfoMap.get(deliveryMethods).name | translate }}</mat-label>
</mat-checkbox>
</div>
</div>
}
</div>
<mat-divider></mat-divider>
@for (settingsControl of notificationSettingsFormArray.controls; track settingsControl; let i = $index) {
<div>
<tb-notification-setting-form [formControl]="settingsControl"
[deliveryMethods]="notificationDeliveryMethods">
</tb-notification-setting-form>
@if (!$last) {
<mat-divider></mat-divider>
@for (deliveryMethods of notificationDeliveryMethods; track deliveryMethods) {
<mat-checkbox class="min-w-30 whitespace-nowrap pr-4" color="warn"
[disabled]="readonly"
[checked]="getChecked(deliveryMethods)"
(change)="changeInstanceTypeCheckBox($event.checked, deliveryMethods)"
[indeterminate]="getIndeterminate(deliveryMethods)"
(click)="$event.stopPropagation()">
<mat-label>{{ notificationDeliveryMethodInfoMap.get(deliveryMethods).name | translate }}</mat-label>
</mat-checkbox>
}
</div>
<mat-divider class="col-span-full"></mat-divider>
</div>
@for (settingsControl of notificationSettingsFormArray.controls; track settingsControl) {
<tb-notification-setting-form
[formControl]="settingsControl"
[deliveryMethods]="notificationDeliveryMethods">
</tb-notification-setting-form>
@if (!$last) {
<mat-divider class="col-span-full"></mat-divider>
}
}
</div>
</section>

36
ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.scss

@ -1,22 +1,46 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
@import "constants";
:host {
.notification-settings {
display: flex;
flex-direction: column;
}
.mat-mdc-card.settings-card {
min-height: 0;
@media #{$mat-gt-sm} {
width: fit-content;
min-width: min(800px, 100%);
max-width: 100%;
}
.mat-mdc-card-content {
display: flex;
flex-direction: column;
min-height: 0;
}
.mat-headline-5 {
margin: 0;
}
.notification-form {
height: 100%;
min-height: min-content;
max-height: min-content;
display: flex;
flex-direction: column;
min-height: 0;
}
.notification-section {
height: 100%;
min-height: 0;
border: 1px solid rgba(0, 0, 0, 0.12);
overflow: scroll;
overflow: auto;
&-block {
min-width: 470px;
display: grid;
grid-template-columns: minmax(240px, 1fr) repeat(var(--tb-notification-delivery-methods-count), max-content);
}
.notification-header {
position: sticky;
top: 0;
z-index: 2;
background-color: var(--mat-card-outlined-container-color, white);
}
}
}

99
ui-ngx/src/app/modules/home/pages/notification/settings/notification-settings.component.ts

@ -5,20 +5,26 @@ import { Component, OnInit } from '@angular/core';
import { PageComponent } from '@shared/components/page.component';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { AbstractControl, UntypedFormArray, UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { FormArray, FormControl, UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { HasConfirmForm } from '@core/guards/confirm-on-exit.guard';
import { TranslateService } from '@ngx-translate/core';
import { ActivatedRoute } from '@angular/router';
import { deepClone, isDefinedAndNotNull } from '@core/utils';
import {
isNotificationTypeReceivable,
NotificationDeliveryMethod,
NotificationDeliveryMethodInfoMap,
NotificationType,
NotificationUserSetting,
NotificationUserSettings
} from '@shared/models/notification.models';
import { NotificationService } from '@core/http/notification.service';
import { DialogService } from '@core/services/dialog.service';
import { Operation, Resource } from '@shared/models/security.models';
import { UserPermissionsService } from '@core/http/user-permissions.service';
import { getCurrentAuthState } from '@core/auth/auth.selectors';
type NotificationSettingRow = NotificationUserSetting & { name: string };
@Component({
selector: 'tb-notification-settings',
@ -40,6 +46,8 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn
NotificationDeliveryMethod.MICROSOFT_TEAMS
]);
private userPrefs: {[key: string]: NotificationUserSetting} = {};
constructor(protected store: Store<AppState>,
private route: ActivatedRoute,
private translate: TranslateService,
@ -70,31 +78,43 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn
}
private patchNotificationSettings(settings: NotificationUserSettings) {
const notificationSettingsControls: Array<AbstractControl> = [];
if (settings.prefs) {
this.prepareNotificationSettings(settings.prefs).forEach(setting =>
notificationSettingsControls.push(this.fb.control({value: setting, disabled: this.readonly}, [Validators.required]))
);
this.userPrefs = settings.prefs ?? {};
this.setPrefsValue(this.prepareNotificationSettings(this.userPrefs));
}
private setPrefsValue(prefs: NotificationSettingRow[]) {
const prefsArray = this.notificationSettingsFormArray;
const sameRows = prefsArray.length === prefs.length &&
prefs.every((pref, index) => prefsArray.at(index).value?.name === pref.name);
if (sameRows) {
prefsArray.patchValue(prefs, {emitEvent: false});
} else {
this.notificationSettings.setControl('prefs', this.fb.array(
prefs.map(pref => this.fb.control({value: pref, disabled: this.readonly}, [Validators.required]))
), {emitEvent: false});
}
this.notificationSettings.setControl('prefs', this.fb.array(notificationSettingsControls), {emitEvent: false});
}
private prepareNotificationSettings(prefs: any) {
return Object.entries(prefs).map((value: any) => {
value[1].name = value[0];
if (!value[1].enabled && Object.values(value[1].enabledDeliveryMethods).some(deliveryMethod => deliveryMethod === true)) {
const enabledDeliveryMethod = deepClone(value[1].enabledDeliveryMethods);
Object.keys(enabledDeliveryMethod).forEach(key => {
enabledDeliveryMethod[key] = false;
});
value[1].enabledDeliveryMethods = enabledDeliveryMethod;
}
value[1].enabledDeliveryMethods = Object.assign(
this.notificationDeliveryMethods.reduce((a, v) => ({ ...a, [v]: true}), {}),
value[1].enabledDeliveryMethods
);
return value[1];
});
private prepareNotificationSettings(prefs: {[key: string]: NotificationUserSetting}): NotificationSettingRow[] {
const authState = getCurrentAuthState(this.store);
return Object.entries(deepClone(prefs))
.filter(([type]) =>
isNotificationTypeReceivable(type as NotificationType, authState.authUser.authority, authState.edgesSupportEnabled))
.map((value: any) => {
value[1].name = value[0];
if (!value[1].enabled && Object.values(value[1].enabledDeliveryMethods).some(deliveryMethod => deliveryMethod === true)) {
const enabledDeliveryMethod = deepClone(value[1].enabledDeliveryMethods);
Object.keys(enabledDeliveryMethod).forEach(key => {
enabledDeliveryMethod[key] = false;
});
value[1].enabledDeliveryMethods = enabledDeliveryMethod;
}
value[1].enabledDeliveryMethods = Object.assign(
this.notificationDeliveryMethods.reduce((a, v) => ({ ...a, [v]: true}), {}),
value[1].enabledDeliveryMethods
);
return value[1];
});
}
resetSettings() {
@ -107,18 +127,11 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn
).subscribe(
result => {
if (result) {
const settings = this.prepareNotificationSettings(this.route.snapshot.data.userSettings.prefs);
const notificationSettingsControls: Array<AbstractControl> = [];
this.notificationSettings.reset({});
if (settings) {
settings.forEach((setting) => {
setting.enabled = true;
setting.enabledDeliveryMethods = this.notificationDeliveryMethods.reduce((a, v) => ({ ...a, [v]: true}), {});
notificationSettingsControls.push(this.fb.control(setting, [Validators.required]));
});
}
this.notificationSettings.setControl('prefs', this.fb.array(notificationSettingsControls), {emitEvent: false});
this.save();
const allMethodsEnabled = this.notificationDeliveryMethods.reduce((a, v) => ({ ...a, [v]: true}), {});
this.setPrefsValue(this.prepareNotificationSettings(this.userPrefs).map(setting =>
({...setting, enabled: true, enabledDeliveryMethods: allMethodsEnabled})
));
this.save({});
}
}
);
@ -163,21 +176,19 @@ export class NotificationSettingsComponent extends PageComponent implements OnIn
this.notificationSettings.markAsDirty();
};
get notificationSettingsFormArray(): UntypedFormArray {
return this.notificationSettings.get('prefs') as UntypedFormArray;
get notificationSettingsFormArray(): FormArray<FormControl> {
return this.notificationSettings.get('prefs') as FormArray<FormControl>;
}
save(): void {
const settings = {prefs: {}};
this.notificationSettings.getRawValue().prefs.forEach(value => {
const key = value.name;
delete value.name;
settings.prefs[key] = value;
save(basePrefs = this.userPrefs): void {
const settings = {prefs: deepClone(basePrefs)};
(this.notificationSettings.getRawValue().prefs as NotificationSettingRow[]).forEach(({name, ...pref}) => {
settings.prefs[name] = pref;
});
this.notificationService.saveNotificationUserSettings(settings).subscribe(
(userSettings) => {
this.notificationSettings.get('prefs').reset({});
this.patchNotificationSettings(userSettings);
this.notificationSettings.markAsPristine();
}
);
}

21
ui-ngx/src/app/modules/home/pages/notification/template/template-notification-dialog.component.ts

@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { NotificationTemplate, NotificationType } from '@shared/models/notification.models';
import { isSysAdminNotificationType, NotificationTemplate, NotificationType } from '@shared/models/notification.models';
import { Component, Inject, OnDestroy, ViewChild } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
@ -18,8 +18,6 @@ import { BreakpointObserver } from '@angular/cdk/layout';
import { MediaBreakpoints } from '@shared/models/constants';
import { TranslateService } from '@ngx-translate/core';
import { TemplateConfiguration } from '@home/pages/notification/template/template-configuration';
import { AuthUser } from '@shared/models/user.model';
import { Authority } from '@shared/models/authority.enum';
export interface TemplateNotificationDialogData {
template?: NotificationTemplate;
@ -176,22 +174,9 @@ export class TemplateNotificationDialogComponent
}
private allowNotificationType(): NotificationType[] {
const sysAdminAllowNotificationTypes = new Set([
NotificationType.ENTITIES_LIMIT,
NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST,
NotificationType.ADDON_ACCESS_REQUEST,
NotificationType.ADDON_ACCESS_ERROR,
NotificationType.PLAN_UPGRADE_REQUEST,
NotificationType.API_USAGE_LIMIT,
NotificationType.NEW_PLATFORM_VERSION,
NotificationType.RATE_LIMITS,
NotificationType.TASK_PROCESSING_FAILURE,
NotificationType.RESOURCES_SHORTAGE
]);
if (this.isSysAdmin()) {
return [NotificationType.GENERAL, ...sysAdminAllowNotificationTypes];
return Object.values(NotificationType).filter(type => type === NotificationType.GENERAL || isSysAdminNotificationType(type));
}
return Object.values(NotificationType).filter(type => !sysAdminAllowNotificationTypes.has(type));
return Object.values(NotificationType).filter(type => !isSysAdminNotificationType(type));
}
}

2
ui-ngx/src/app/shared/components/dashboard-select-panel.component.html

@ -6,7 +6,7 @@
-->
<div class="mat-content mat-padding flex flex-col">
<mat-form-field>
<mat-form-field appearance="outline" subscriptSizing="dynamic">
<mat-label>{{'dashboard.select-dashboard' | translate}}</mat-label>
<mat-select matInput [(ngModel)]="dashboardId"
(ngModelChange)="dashboardSelected(dashboardId)">

2
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -216,7 +216,7 @@ export interface DeviceInstallStep {
type: InstallStepType;
name: string;
// Optional stable id of the step, unique within the install method: the key of the step's install state,
// so the next version can rename the step. Without it, the name is the key.
// so the next version can rename the step. Without it, the key is the type and the name; a form's is its name.
id?: string;
file?: string;
template?: string;

6
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -62,7 +62,8 @@ export interface DeviceUpdateStep {
serverAttributes?: any;
sharedAttributes?: any;
resolution?: string;
// The package step's id, which keys its install state; the name when not set
// The package step's stable id, so that a next version can rename the step. When set it is also the step's install
// state key: the default converter update sends the stored key here to write the state back under it
id?: string;
// INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry
metadata?: Record<string, string | null>;
@ -80,12 +81,13 @@ export interface DeviceUpdateRequest {
steps: DeviceUpdateStep[];
}
/** All of the update was applied, or none of it: failedStep names the step that failed, if one did. */
/** All of the update was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */
export interface DeviceUpdateResult {
success: boolean;
errorMessage?: string;
failedStep?: string;
descriptor?: DeviceInstalledItemDescriptor;
// By install state key of the step
outputs?: Record<string, any>;
}

46
ui-ngx/src/app/shared/models/notification.models.ts

@ -23,6 +23,7 @@ import { UserPermissionsService } from '@core/http/user-permissions.service';
import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { Operation, Resource } from '@shared/models/security.models';
import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models';
import { Authority } from '@shared/models/authority.enum';
export interface Notification {
readonly id: NotificationId;
@ -805,6 +806,51 @@ export const singleNotificationTypeTemplate = (type: NotificationType) => {
type === NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST;
}
const sysAdminNotificationTypes: ReadonlySet<NotificationType> = new Set([
NotificationType.ENTITIES_LIMIT,
NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST,
NotificationType.ADDON_ACCESS_REQUEST,
NotificationType.ADDON_ACCESS_ERROR,
NotificationType.PLAN_UPGRADE_REQUEST,
NotificationType.API_USAGE_LIMIT,
NotificationType.NEW_PLATFORM_VERSION,
NotificationType.RATE_LIMITS,
NotificationType.TASK_PROCESSING_FAILURE,
NotificationType.RESOURCES_SHORTAGE
]);
const adminRequestNotificationTypes: ReadonlySet<NotificationType> = new Set([
NotificationType.ENTITIES_LIMIT_INCREASE_REQUEST,
NotificationType.ADDON_ACCESS_REQUEST,
NotificationType.ADDON_ACCESS_ERROR,
NotificationType.PLAN_UPGRADE_REQUEST
]);
const edgeNotificationTypes: ReadonlySet<NotificationType> = new Set([
NotificationType.EDGE_CONNECTION,
NotificationType.EDGE_COMMUNICATION_FAILURE
]);
export const isSysAdminNotificationType = (type: NotificationType | TriggerType): boolean =>
sysAdminNotificationTypes.has(type as NotificationType);
export const isNotificationTypeReceivable = (type: NotificationType, authority: Authority, edgesSupportEnabled: boolean): boolean => {
switch (authority) {
case Authority.SYS_ADMIN:
return type === NotificationType.GENERAL || sysAdminNotificationTypes.has(type);
case Authority.CUSTOMER_USER:
if (adminRequestNotificationTypes.has(type)) {
return false;
}
break;
default:
if (type === NotificationType.PLAN_UPGRADE_REQUEST) {
return false;
}
}
return edgesSupportEnabled || !edgeNotificationTypes.has(type);
};
export function notificationAiAssistantConfig(store: Store<AppState>,
userPermissionsService: UserPermissionsService,
translate: TranslateService,

11003
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

File diff suppressed because it is too large

15600
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

File diff suppressed because it is too large

21
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -6445,10 +6445,11 @@
"install-success-desc": "'{{name}}' has been installed successfully",
"remove": "Remove",
"remove-confirm-title": "Remove '{{name}}'?",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant",
"remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:",
"remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant.",
"remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }",
"remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.",
"remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway",
"select-entity-for-cf": "Select entity for calculated field '{{name}}'",
@ -6588,17 +6589,19 @@
"device-installing-title": "Installing \"{{name}}\"",
"device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update",
"device-update-no-conflicts": "No conflicts",
"device-update-will-update": "Will be updated",
"device-update-will-create": "Will be created",
"device-update-no-changes": "No changes",
"device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.",
"device-update-shared-more": "and {{count}} more",
"device-update-shared-less": "Show less",
"device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.",
"device-update-modified": "Has local changes. You can download the current version <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.",
"device-update-existing-use-existing": "Already exists. The existing one will be used.",
"device-update-existing-overwrite": "Already exists. It will be overwritten.",
"device-update-existing-create-copy": "Already exists. A copy will be created.",
"device-install-duplicate-step": "Two install steps of this device package have the same key: {{key}}. Report it to the package's creator.",
"device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update",
"device-update-skipped": "Not changed",
"device-update-skipped": "Unchanged",
"device-update-updated": "Updated",
"device-update-created": "Created",
"device-update-try-again": "Try again",

4
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -7361,8 +7361,8 @@
"position": {
"top": "Viršus",
"bottom": "Apačia",
"left": "Kairioji pusė",
"right": "Dešinioji pusė"
"left": "Kairė",
"right": "Dešinė"
},
"profile": {
"profile": "Profilis",

12
ui-ngx/yarn.lock

@ -4022,11 +4022,6 @@ deep-extend@~0.6.0:
resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac"
integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==
deep-freeze-strict@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/deep-freeze-strict/-/deep-freeze-strict-1.1.1.tgz#77d0583ca24a69be4bbd9ac2fae415d55523e5b0"
integrity sha512-QemROZMM2IvhAcCFvahdX2Vbm4S/txeq5rFYU9fh4mQP79WTMW5c/HkQ2ICl1zuzcDZdPZ6zarDxQeQMsVYoNA==
deep-is@^0.1.3:
version "0.1.4"
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831"
@ -6437,13 +6432,6 @@ negotiator@^1.0.0:
resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-1.0.0.tgz#b6c91bb47172d69f93cfd7c357bbb529019b5f6a"
integrity sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==
ngrx-store-freeze@^0.2.4:
version "0.2.4"
resolved "https://registry.yarnpkg.com/ngrx-store-freeze/-/ngrx-store-freeze-0.2.4.tgz#146687cdf7e21244eb9003c7e883f2125847076c"
integrity sha512-90awpbbMa/x2H81eWWYniyli3LJ1PZU/FaztL10d9Rp/4kw2+97pqyLjdxSPxcOv9St//m9kfuWZ7gyoVDjgcg==
dependencies:
deep-freeze-strict "^1.1.1"
ngx-captcha@^14.0.0:
version "14.0.0"
resolved "https://registry.yarnpkg.com/ngx-captcha/-/ngx-captcha-14.0.0.tgz#6595d06857f87efd954da4774f02d40e762c0d86"

Loading…
Cancel
Save