diff --git a/.gitignore b/.gitignore index 3a4af54b75..e9a4e11b85 100644 --- a/.gitignore +++ b/.gitignore @@ -30,9 +30,10 @@ pom.xml.versionsBackup **/build **/target **/Californium.properties +**/Californium3.properties **/.env .instance_id rebuild-docker.sh */.run/** .run/** -.run \ No newline at end of file +.run diff --git a/README.md b/README.md index 5520645541..581e71977d 100644 --- a/README.md +++ b/README.md @@ -12,20 +12,20 @@ ThingsBoard documentation is hosted on [thingsboard.io](https://thingsboard.io/d ## IoT use cases -[**Smart metering**](https://thingsboard.io/smart-metering/) -[![Smart metering](https://user-images.githubusercontent.com/8308069/31455788-6888a948-aec1-11e7-9819-410e0ba785e0.gif "Smart metering")](https://thingsboard.io/smart-metering/) - -[**IoT Rule Engine**](https://thingsboard.io/docs/user-guide/rule-engine-2-0/re-getting-started/) -[![IoT Rule Engine](https://thingsboard.io/images/demo/send-email-rule-chain.gif "IoT Rule Engine")](https://thingsboard.io/docs/user-guide/rule-engine-2-0/re-getting-started/) - [**Smart energy**](https://thingsboard.io/smart-energy/) -[![Smart energy](https://cloud.githubusercontent.com/assets/8308069/24495682/aebd45d0-153e-11e7-8de4-7360ed5b41ae.gif "Smart energy")](https://thingsboard.io/smart-energy/) +[![Smart energy](https://user-images.githubusercontent.com/8308069/152984256-eb48564a-645c-468d-912b-f554b63104a5.gif "Smart energy")](https://thingsboard.io/smart-energy/) + +[**Fleet tracking**](https://thingsboard.io/fleet-tracking/) +[![Fleet tracking](https://user-images.githubusercontent.com/8308069/152984528-0054ed55-8b8b-4cda-ba45-02fe95a81222.gif "Fleet tracking")](https://thingsboard.io/fleet-tracking/) [**Smart farming**](https://thingsboard.io/smart-farming/) -[![Smart farming](https://cloud.githubusercontent.com/assets/8308069/24496824/10dc1144-1542-11e7-8aa1-5d3a281d5a1a.gif "Smart farming")](https://thingsboard.io/smart-farming/) +[![Smart farming](https://user-images.githubusercontent.com/8308069/152984443-a98b7d3d-ff7a-4037-9011-e71e1e6f755f.gif "Smart farming")](https://thingsboard.io/smart-farming/) -[**Fleet tracking**](https://thingsboard.io/fleet-tracking/) -[![Fleet tracking](https://cloud.githubusercontent.com/assets/8308069/24497169/3a1a61e0-1543-11e7-8d55-3c8a13f35634.gif "Fleet tracking")](https://thingsboard.io/fleet-tracking/) +[**IoT Rule Engine**](https://thingsboard.io/docs/user-guide/rule-engine-2-0/re-getting-started/) +[![IoT Rule Engine](https://thingsboard.io/images/demo/send-email-rule-chain.gif "IoT Rule Engine")](https://thingsboard.io/docs/user-guide/rule-engine-2-0/re-getting-started/) + +[**Smart metering**](https://thingsboard.io/smart-metering/) +[![Smart metering](https://user-images.githubusercontent.com/8308069/31455788-6888a948-aec1-11e7-9819-410e0ba785e0.gif "Smart metering")](https://thingsboard.io/smart-metering/) ## Getting Started diff --git a/application/pom.xml b/application/pom.xml index 405f3b4d7d..2d6dda0bbe 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -1,6 +1,6 @@ + + + + + + Email verification code + + + + + + + + + + + +
+
+ + +
+ + + + + + + + + + + + + + + + + + +
+

Your verification code:

+
+

${code}

+
+ Please verify your access using the code above. +
+ This code will expire in ${expirationTimeSeconds} seconds. +
+ If you didn't request this code, you can ignore this email. +
+ — The Thingsboard +
+ +
+
+ + diff --git a/application/src/main/resources/templates/account.activated.ftl b/application/src/main/resources/templates/account.activated.ftl index b13829f8d2..b34b5743e9 100644 --- a/application/src/main/resources/templates/account.activated.ftl +++ b/application/src/main/resources/templates/account.activated.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/account.lockout.ftl b/application/src/main/resources/templates/account.lockout.ftl index 6967ee19b3..fa21653cb9 100644 --- a/application/src/main/resources/templates/account.lockout.ftl +++ b/application/src/main/resources/templates/account.lockout.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -88,7 +88,7 @@ background-color: #f6f6f6; - Thingsboard user account ${lockoutAccount} has been lockout due to failed credentials were provided more than ${maxFailedLoginAttempts} times. + Thingsboard user account ${lockoutAccount} has been locked out due to multiple authentication failures (more than ${maxFailedLoginAttempts}). diff --git a/application/src/main/resources/templates/activation.ftl b/application/src/main/resources/templates/activation.ftl index 3b6717cc9b..955ed25b56 100644 --- a/application/src/main/resources/templates/activation.ftl +++ b/application/src/main/resources/templates/activation.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/password.was.reset.ftl b/application/src/main/resources/templates/password.was.reset.ftl index 9d86fc645d..eef35a2a87 100644 --- a/application/src/main/resources/templates/password.was.reset.ftl +++ b/application/src/main/resources/templates/password.was.reset.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/reset.password.ftl b/application/src/main/resources/templates/reset.password.ftl index 147ca64ba0..e1392e9c30 100644 --- a/application/src/main/resources/templates/reset.password.ftl +++ b/application/src/main/resources/templates/reset.password.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/state.disabled.ftl b/application/src/main/resources/templates/state.disabled.ftl index 56ad255e10..45eeda76bd 100644 --- a/application/src/main/resources/templates/state.disabled.ftl +++ b/application/src/main/resources/templates/state.disabled.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/state.enabled.ftl b/application/src/main/resources/templates/state.enabled.ftl index 4ca400ad9b..f14657e937 100644 --- a/application/src/main/resources/templates/state.enabled.ftl +++ b/application/src/main/resources/templates/state.enabled.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/state.warning.ftl b/application/src/main/resources/templates/state.warning.ftl index 479ae09432..cfba216cb1 100644 --- a/application/src/main/resources/templates/state.warning.ftl +++ b/application/src/main/resources/templates/state.warning.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/templates/test.ftl b/application/src/main/resources/templates/test.ftl index f09057f187..3d8af9806e 100644 --- a/application/src/main/resources/templates/test.ftl +++ b/application/src/main/resources/templates/test.ftl @@ -1,6 +1,6 @@ <#-- - Copyright © 2016-2021 The Thingsboard Authors + Copyright © 2016-2022 The Thingsboard Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index 6ff108968d..775c1021b9 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -1,5 +1,5 @@ # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ server: address: "${HTTP_BIND_ADDRESS:0.0.0.0}" # Server bind port port: "${HTTP_BIND_PORT:8080}" + # Server forward headers strategy + forward_headers_strategy: "${HTTP_FORWARD_HEADERS_STRATEGY:NONE}" # Server SSL configuration ssl: # Enable/disable SSL support @@ -71,7 +73,7 @@ server: dynamic_page_link: refresh_interval: "${TB_SERVER_WS_DYNAMIC_PAGE_LINK_REFRESH_INTERVAL_SEC:60}" refresh_pool_size: "${TB_SERVER_WS_DYNAMIC_PAGE_LINK_REFRESH_POOL_SIZE:1}" - max_alarm_queries_per_refresh_interval: "${TB_SERVER_WS_MAX_ALARM_QUERIES_PER_REFRESH_INTERVAL:3}" + max_alarm_queries_per_refresh_interval: "${TB_SERVER_WS_MAX_ALARM_QUERIES_PER_REFRESH_INTERVAL:10}" max_per_user: "${TB_SERVER_WS_DYNAMIC_PAGE_LINK_MAX_PER_USER:10}" max_entities_per_data_subscription: "${TB_SERVER_WS_MAX_ENTITIES_PER_DATA_SUBSCRIPTION:10000}" max_entities_per_alarm_subscription: "${TB_SERVER_WS_MAX_ENTITIES_PER_ALARM_SUBSCRIPTION:10000}" @@ -165,7 +167,7 @@ ui: # Help parameters help: # Base url for UI help assets - base-url: "${UI_HELP_BASE_URL:https://raw.githubusercontent.com/thingsboard/thingsboard-ui-help/release-3.3.3}" + base-url: "${UI_HELP_BASE_URL:https://raw.githubusercontent.com/thingsboard/thingsboard-ui-help/release-3.3.4}" database: ts_max_intervals: "${DATABASE_TS_MAX_INTERVALS:700}" # Max number of DB queries generated by single API call to fetch telemetry records @@ -174,8 +176,6 @@ database: ts_latest: type: "${DATABASE_TS_LATEST_TYPE:sql}" # cassandra, sql, or timescale (for hybrid mode, DATABASE_TS_TYPE value should be cassandra, or timescale) -# note: timescale works only with postgreSQL database for DATABASE_ENTITIES_TYPE. - # Cassandra driver configuration parameters cassandra: # Thingsboard cluster name @@ -278,6 +278,16 @@ sql: stats_print_interval_ms: "${SQL_TS_LATEST_BATCH_STATS_PRINT_MS:10000}" batch_threads: "${SQL_TS_LATEST_BATCH_THREADS:3}" # batch thread count have to be a prime number like 3 or 5 to gain perfect hash distribution update_by_latest_ts: "${SQL_TS_UPDATE_BY_LATEST_TIMESTAMP:true}" + events: + batch_size: "${SQL_EVENTS_BATCH_SIZE:10000}" + batch_max_delay: "${SQL_EVENTS_BATCH_MAX_DELAY_MS:100}" + stats_print_interval_ms: "${SQL_EVENTS_BATCH_STATS_PRINT_MS:10000}" + batch_threads: "${SQL_EVENTS_BATCH_THREADS:3}" # batch thread count have to be a prime number like 3 or 5 to gain perfect hash distribution + edge_events: + batch_size: "${SQL_EDGE_EVENTS_BATCH_SIZE:1000}" + batch_max_delay: "${SQL_EDGE_EVENTS_BATCH_MAX_DELAY_MS:100}" + stats_print_interval_ms: "${SQL_EDGE_EVENTS_BATCH_STATS_PRINT_MS:10000}" + batch_threads: "${SQL_EDGE_EVENTS_BATCH_THREADS:3}" # batch thread count have to be a prime number like 3 or 5 to gain perfect hash distribution # Specify whether to sort entities before batch update. Should be enabled for cluster mode to avoid deadlocks batch_sort: "${SQL_BATCH_SORT:false}" # Specify whether to remove null characters from strValue of attributes and timeseries before insert @@ -377,8 +387,6 @@ cache: attributes: # make sure that if cache.type is 'redis' and cache.attributes.enabled is 'true' that you change 'maxmemory-policy' Redis config property to 'allkeys-lru', 'allkeys-lfu' or 'allkeys-random' enabled: "${CACHE_ATTRIBUTES_ENABLED:true}" - -caffeine: specs: relations: timeToLiveInMinutes: "${CACHE_SPECS_RELATIONS_TTL:1440}" @@ -428,6 +436,9 @@ caffeine: edges: timeToLiveInMinutes: "${CACHE_SPECS_EDGES_TTL:1440}" maxSize: "${CACHE_SPECS_EDGES_MAX_SIZE:10000}" + twoFaVerificationCodes: + timeToLiveInMinutes: "${CACHE_SPECS_TWO_FA_VERIFICATION_CODES_TTL:60}" + maxSize: "${CACHE_SPECS_TWO_FA_VERIFICATION_CODES_MAX_SIZE:100000}" redis: # standalone or cluster @@ -468,12 +479,16 @@ redis: maxWaitMills: "${REDIS_POOL_CONFIG_MAX_WAIT_MS:60000}" numberTestsPerEvictionRun: "${REDIS_POOL_CONFIG_NUMBER_TESTS_PER_EVICTION_RUN:3}" blockWhenExhausted: "${REDIS_POOL_CONFIG_BLOCK_WHEN_EXHAUSTED:true}" + # TTL for short-living SET commands that are used to replace DEL in order to enable transaction support + evictTtlInMs: "${REDIS_EVICT_TTL_MS:60000}" # Check new version updates parameters updates: # Enable/disable updates checking. enabled: "${UPDATES_ENABLED:true}" +spring.main.allow-circular-references: "true" + # spring freemarker configuration spring.freemarker.checkTemplateLocation: "false" @@ -483,7 +498,7 @@ spring.mvc.cors: # Intercept path "[/api/**]": #Comma-separated list of origins to allow. '*' allows all origins. When not set,CORS support is disabled. - allowed-origins: "*" + allowed-origin-patterns: "*" #Comma-separated list of methods to allow. '*' allows all methods. allowed-methods: "*" #Comma-separated list of headers to allow in a request. '*' allows all headers. @@ -507,7 +522,7 @@ spring.servlet.multipart.max-file-size: "50MB" spring.servlet.multipart.max-request-size: "50MB" spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation: "true" -spring.jpa.properties.hibernate.order_by.default_null_ordering: "last" +spring.jpa.properties.hibernate.order_by.default_null_ordering: "${SPRING_JPA_PROPERTIES_HIBERNATE_ORDER_BY_DEFAULT_NULL_ORDERING:last}" # SQL DAO Configuration spring: @@ -521,7 +536,6 @@ spring: open-in-view: "false" hibernate: ddl-auto: "none" - database-platform: "${SPRING_JPA_DATABASE_PLATFORM:org.hibernate.dialect.PostgreSQLDialect}" datasource: driverClassName: "${SPRING_DRIVER_CLASS_NAME:org.postgresql.Driver}" url: "${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/thingsboard}" @@ -622,6 +636,13 @@ transport: log: enabled: "${TB_TRANSPORT_LOG_ENABLED:true}" max_length: "${TB_TRANSPORT_LOG_MAX_LENGTH:1024}" + rate_limits: + # Enable or disable generic rate limits. Device and Tenant specific rate limits are controlled in Tenant Profile. + ip_limits_enabled: "${TB_TRANSPORT_IP_RATE_LIMITS_ENABLED:false}" + # Maximum number of connect attempts with invalid credentials + max_wrong_credentials_per_ip: "${TB_TRANSPORT_MAX_WRONG_CREDENTIALS_PER_IP:10}" + # Timeout to expire block IP addresses + ip_block_timeout: "${TB_TRANSPORT_IP_BLOCK_TIMEOUT:60000}" # Local HTTP transport parameters http: enabled: "${HTTP_ENABLED:true}" @@ -633,6 +654,9 @@ transport: enabled: "${MQTT_ENABLED:true}" bind_address: "${MQTT_BIND_ADDRESS:0.0.0.0}" bind_port: "${MQTT_BIND_PORT:1883}" + # Enable proxy protocol support. Disabled by default. If enabled, supports both v1 and v2. + # Useful to get the real IP address of the client in the logs and for rate limits. + proxy_enabled: "${MQTT_PROXY_PROTOCOL_ENABLED:false}" timeout: "${MQTT_TIMEOUT:10000}" msg_queue_size_per_device_limit: "${MQTT_MSG_QUEUE_SIZE_PER_DEVICE_LIMIT:100}" # messages await in the queue before device connected state. This limit works on low level before TenantProfileLimits mechanism netty: @@ -684,6 +708,7 @@ transport: bind_address: "${COAP_BIND_ADDRESS:0.0.0.0}" bind_port: "${COAP_BIND_PORT:5683}" timeout: "${COAP_TIMEOUT:10000}" + piggyback_timeout: "${COAP_PIGGYBACK_TIMEOUT:500}" psm_activity_timer: "${COAP_PSM_ACTIVITY_TIMER:10000}" paging_transmission_window: "${COAP_PAGING_TRANSMISSION_WINDOW:10000}" dtls: @@ -736,7 +761,7 @@ transport: # Server X509 Certificates support credentials: # Whether to enable LWM2M server X509 Certificate/RPK support - enabled: "${LWM2M_SERVER_CREDENTIALS_ENABLED:true}" + enabled: "${LWM2M_SERVER_CREDENTIALS_ENABLED:false}" # Server credentials type (PEM - pem certificate file; KEYSTORE - java keystore) type: "${LWM2M_SERVER_CREDENTIALS_TYPE:PEM}" # PEM server credentials @@ -772,7 +797,7 @@ transport: # Bootstrap server X509 Certificates support credentials: # Whether to enable LWM2M bootstrap server X509 Certificate/RPK support - enabled: "${LWM2M_BS_CREDENTIALS_ENABLED:true}" + enabled: "${LWM2M_BS_CREDENTIALS_ENABLED:false}" # Server credentials type (PEM - pem certificate file; KEYSTORE - java keystore) type: "${LWM2M_BS_CREDENTIALS_TYPE:PEM}" # PEM server credentials @@ -799,19 +824,19 @@ transport: # X509 trust certificates trust-credentials: # Whether to load X509 trust certificates - enabled: "${LWM2M_TRUST_CREDENTIALS_ENABLED:true}" + enabled: "${LWM2M_TRUST_CREDENTIALS_ENABLED:false}" # Trust certificates store type (PEM - pem certificates file; KEYSTORE - java keystore) type: "${LWM2M_TRUST_CREDENTIALS_TYPE:PEM}" # PEM certificates pem: # Path to the certificates file (holds trust certificates) - cert_file: "${LWM2M_TRUST_PEM_CERT:lwm2mserver.pem}" + cert_file: "${LWM2M_TRUST_PEM_CERT:lwm2mtruststorechain.pem}" # Keystore with trust certificates keystore: # Type of the key store type: "${LWM2M_TRUST_KEY_STORE_TYPE:JKS}" # Path to the key store that holds the X509 certificates - store_file: "${LWM2M_TRUST_KEY_STORE:lwm2mserver.jks}" + store_file: "${LWM2M_TRUST_KEY_STORE:lwm2mtruststorechain.jks}" # Password used to access the key store store_password: "${LWM2M_TRUST_KEY_STORE_PASSWORD:server_ks_password}" recommended_ciphers: "${LWM2M_RECOMMENDED_CIPHERS:false}" @@ -824,8 +849,6 @@ transport: log_max_length: "${LWM2M_LOG_MAX_LENGTH:1024}" psm_activity_timer: "${LWM2M_PSM_ACTIVITY_TIMER:10000}" paging_transmission_window: "${LWM2M_PAGING_TRANSMISSION_WINDOW:10000}" - # Use redis for Security and Registration stores - redis.enabled: "${LWM2M_REDIS_ENABLED:false}" network_config: # In this section you can specify custom parameters for LwM2M network configuration and expose the env variables to configure outside # - key: "PROTOCOL_STAGE_THREAD_COUNT" # value: "${LWM2M_PROTOCOL_STAGE_THREAD_COUNT:4}" @@ -1036,7 +1059,7 @@ queue: # For BATCH only batch-size: "${TB_QUEUE_RE_MAIN_SUBMIT_STRATEGY_BATCH_SIZE:1000}" # Maximum number of messages in batch processing-strategy: - type: "${TB_QUEUE_RE_MAIN_PROCESSING_STRATEGY_TYPE:SKIP_ALL_FAILURES}" # SKIP_ALL_FAILURES, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT + type: "${TB_QUEUE_RE_MAIN_PROCESSING_STRATEGY_TYPE:SKIP_ALL_FAILURES}" # SKIP_ALL_FAILURES, SKIP_ALL_FAILURES_AND_TIMED_OUT, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT # For RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT retries: "${TB_QUEUE_RE_MAIN_PROCESSING_STRATEGY_RETRIES:3}" # Number of retries, 0 is unlimited failure-percentage: "${TB_QUEUE_RE_MAIN_PROCESSING_STRATEGY_FAILURE_PERCENTAGE:0}" # Skip retry if failures or timeouts are less then X percentage of messages; @@ -1053,7 +1076,7 @@ queue: # For BATCH only batch-size: "${TB_QUEUE_RE_HP_SUBMIT_STRATEGY_BATCH_SIZE:100}" # Maximum number of messages in batch processing-strategy: - type: "${TB_QUEUE_RE_HP_PROCESSING_STRATEGY_TYPE:RETRY_FAILED_AND_TIMED_OUT}" # SKIP_ALL_FAILURES, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT + type: "${TB_QUEUE_RE_HP_PROCESSING_STRATEGY_TYPE:RETRY_FAILED_AND_TIMED_OUT}" # SKIP_ALL_FAILURES, SKIP_ALL_FAILURES_AND_TIMED_OUT, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT # For RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT retries: "${TB_QUEUE_RE_HP_PROCESSING_STRATEGY_RETRIES:0}" # Number of retries, 0 is unlimited failure-percentage: "${TB_QUEUE_RE_HP_PROCESSING_STRATEGY_FAILURE_PERCENTAGE:0}" # Skip retry if failures or timeouts are less then X percentage of messages; @@ -1070,7 +1093,7 @@ queue: # For BATCH only batch-size: "${TB_QUEUE_RE_SQ_SUBMIT_STRATEGY_BATCH_SIZE:100}" # Maximum number of messages in batch processing-strategy: - type: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_TYPE:RETRY_FAILED_AND_TIMED_OUT}" # SKIP_ALL_FAILURES, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT + type: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_TYPE:RETRY_FAILED_AND_TIMED_OUT}" # SKIP_ALL_FAILURES, SKIP_ALL_FAILURES_AND_TIMED_OUT, RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT # For RETRY_ALL, RETRY_FAILED, RETRY_TIMED_OUT, RETRY_FAILED_AND_TIMED_OUT retries: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_RETRIES:3}" # Number of retries, 0 is unlimited failure-percentage: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_FAILURE_PERCENTAGE:0}" # Skip retry if failures or timeouts are less then X percentage of messages; @@ -1089,7 +1112,6 @@ service: type: "${TB_SERVICE_TYPE:monolith}" # monolith or tb-core or tb-rule-engine # Unique id for this service (autogenerated if empty) id: "${TB_SERVICE_ID:}" - tenant_id: "${TB_SERVICE_TENANT_ID:}" # empty or specific tenant id. metrics: # Enable/disable actuator metrics. diff --git a/application/src/test/java/org/thingsboard/server/actors/ActorSystemContextTest.java b/application/src/test/java/org/thingsboard/server/actors/ActorSystemContextTest.java deleted file mode 100644 index 35120a7460..0000000000 --- a/application/src/test/java/org/thingsboard/server/actors/ActorSystemContextTest.java +++ /dev/null @@ -1,257 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.actors; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit.jupiter.SpringExtension; -import org.thingsboard.rule.engine.api.MailService; -import org.thingsboard.rule.engine.api.SmsService; -import org.thingsboard.rule.engine.api.sms.SmsSenderFactory; -import org.thingsboard.server.actors.service.ActorService; -import org.thingsboard.server.cluster.TbClusterService; -import org.thingsboard.server.common.transport.util.DataDecodingEncodingService; -import org.thingsboard.server.dao.asset.AssetService; -import org.thingsboard.server.dao.attributes.AttributesService; -import org.thingsboard.server.dao.audit.AuditLogService; -import org.thingsboard.server.dao.cassandra.CassandraCluster; -import org.thingsboard.server.dao.customer.CustomerService; -import org.thingsboard.server.dao.dashboard.DashboardService; -import org.thingsboard.server.dao.device.ClaimDevicesService; -import org.thingsboard.server.dao.device.DeviceService; -import org.thingsboard.server.dao.edge.EdgeEventService; -import org.thingsboard.server.dao.edge.EdgeService; -import org.thingsboard.server.dao.entityview.EntityViewService; -import org.thingsboard.server.dao.event.EventService; -import org.thingsboard.server.dao.nosql.CassandraBufferedRateReadExecutor; -import org.thingsboard.server.dao.nosql.CassandraBufferedRateWriteExecutor; -import org.thingsboard.server.dao.ota.OtaPackageService; -import org.thingsboard.server.dao.relation.RelationService; -import org.thingsboard.server.dao.resource.ResourceService; -import org.thingsboard.server.dao.rule.RuleChainService; -import org.thingsboard.server.dao.rule.RuleNodeStateService; -import org.thingsboard.server.dao.tenant.TbTenantProfileCache; -import org.thingsboard.server.dao.tenant.TenantProfileService; -import org.thingsboard.server.dao.tenant.TenantService; -import org.thingsboard.server.dao.timeseries.TimeseriesService; -import org.thingsboard.server.dao.user.UserService; -import org.thingsboard.server.queue.discovery.PartitionService; -import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; -import org.thingsboard.server.queue.usagestats.TbApiUsageClient; -import org.thingsboard.server.service.apiusage.TbApiUsageStateService; -import org.thingsboard.server.service.component.ComponentDiscoveryService; -import org.thingsboard.server.service.edge.rpc.EdgeRpcService; -import org.thingsboard.server.service.executors.DbCallbackExecutorService; -import org.thingsboard.server.service.executors.ExternalCallExecutorService; -import org.thingsboard.server.service.executors.SharedEventLoopGroupService; -import org.thingsboard.server.service.mail.MailExecutorService; -import org.thingsboard.server.service.profile.TbDeviceProfileCache; -import org.thingsboard.server.service.rpc.TbCoreDeviceRpcService; -import org.thingsboard.server.service.rpc.TbRpcService; -import org.thingsboard.server.service.rpc.TbRuleEngineDeviceRpcService; -import org.thingsboard.server.service.script.JsInvokeService; -import org.thingsboard.server.service.session.DeviceSessionCacheService; -import org.thingsboard.server.service.sms.SmsExecutorService; -import org.thingsboard.server.service.state.DeviceStateService; -import org.thingsboard.server.service.telemetry.AlarmSubscriptionService; -import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; -import org.thingsboard.server.service.transport.TbCoreToTransportService; - -import static org.assertj.core.api.Assertions.assertThat; - -@ExtendWith(SpringExtension.class) -@ContextConfiguration(classes = ActorSystemContext.class) -@EnableConfigurationProperties -@TestPropertySource(properties = { - "cache.type=caffeine", -}) -public class ActorSystemContextTest { - - @Autowired - ActorSystemContext ctx; - - @MockBean - private TbApiUsageStateService apiUsageStateService; - - @MockBean - private TbApiUsageClient apiUsageClient; - - @MockBean - private TbServiceInfoProvider serviceInfoProvider; - - @MockBean - private ActorService actorService; - - @MockBean - private ComponentDiscoveryService componentService; - - @MockBean - private DataDecodingEncodingService encodingService; - - @MockBean - private DeviceService deviceService; - - @MockBean - private TbTenantProfileCache tenantProfileCache; - - @MockBean - private TbDeviceProfileCache deviceProfileCache; - - @MockBean - private AssetService assetService; - - @MockBean - private DashboardService dashboardService; - - @MockBean - private TenantService tenantService; - - @MockBean - private TenantProfileService tenantProfileService; - - @MockBean - private CustomerService customerService; - - @MockBean - private UserService userService; - - @MockBean - private RuleChainService ruleChainService; - - @MockBean - private RuleNodeStateService ruleNodeStateService; - - @MockBean - private PartitionService partitionService; - - @MockBean - private TbClusterService clusterService; - - @MockBean - private TimeseriesService tsService; - - @MockBean - private AttributesService attributesService; - - @MockBean - private EventService eventService; - - @MockBean - private RelationService relationService; - - @MockBean - private AuditLogService auditLogService; - - @MockBean - private EntityViewService entityViewService; - - @MockBean - private TelemetrySubscriptionService tsSubService; - - @MockBean - private AlarmSubscriptionService alarmService; - - @MockBean - private JsInvokeService jsSandbox; - - @MockBean - private MailExecutorService mailExecutor; - - @MockBean - private SmsExecutorService smsExecutor; - - @MockBean - private DbCallbackExecutorService dbCallbackExecutor; - - @MockBean - private ExternalCallExecutorService externalCallExecutorService; - - @MockBean - private SharedEventLoopGroupService sharedEventLoopGroupService; - - @MockBean - private MailService mailService; - - @MockBean - private SmsService smsService; - - @MockBean - private SmsSenderFactory smsSenderFactory; - - @MockBean - private ClaimDevicesService claimDevicesService; - - @MockBean - private JsInvokeStats jsInvokeStats; - - @MockBean - private DeviceStateService deviceStateService; - - @MockBean - private DeviceSessionCacheService deviceSessionCacheService; - - @MockBean - private TbCoreToTransportService tbCoreToTransportService; - - @MockBean - private TbRuleEngineDeviceRpcService tbRuleEngineDeviceRpcService; - - @MockBean - private TbCoreDeviceRpcService tbCoreDeviceRpcService; - - @MockBean - private EdgeService edgeService; - - @MockBean - private EdgeEventService edgeEventService; - - @MockBean - private EdgeRpcService edgeRpcService; - - @MockBean - private ResourceService resourceService; - - @MockBean - private OtaPackageService otaPackageService; - - @MockBean - private TbRpcService tbRpcService; - - @MockBean - private CassandraCluster cassandraCluster; - - @MockBean - private CassandraBufferedRateReadExecutor cassandraBufferedRateReadExecutor; - - @MockBean - private CassandraBufferedRateWriteExecutor cassandraBufferedRateWriteExecutor; - - @MockBean - private RedisTemplate redisTemplate; - - @Test - void givenCaffeineCache_whenInit_thenIsLocalCacheTrue() { - assertThat(ctx.getCacheType()).isEqualTo("caffeine"); - assertThat(ctx.isLocalCacheType()).as("caffeine is the local cache type").isTrue(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/actors/device/DeviceActorMessageProcessorTest.java b/application/src/test/java/org/thingsboard/server/actors/device/DeviceActorMessageProcessorTest.java index 753ad53d90..850e048ba2 100644 --- a/application/src/test/java/org/thingsboard/server/actors/device/DeviceActorMessageProcessorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/device/DeviceActorMessageProcessorTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/actors/stats/StatsActorTest.java b/application/src/test/java/org/thingsboard/server/actors/stats/StatsActorTest.java index c058bb881e..0e928b7dd6 100644 --- a/application/src/test/java/org/thingsboard/server/actors/stats/StatsActorTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/stats/StatsActorTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,11 +59,11 @@ class StatsActorTest { @Test void givenNonEmptyStatMessage_whenOnStatsPersistMsg_thenNoAction() { statsActor.onStatsPersistMsg(new StatsPersistMsg(0, 1, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)); - verify(eventService, times(1)).save(any(Event.class)); + verify(eventService, times(1)).saveAsync(any(Event.class)); statsActor.onStatsPersistMsg(new StatsPersistMsg(1, 0, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)); - verify(eventService, times(2)).save(any(Event.class)); + verify(eventService, times(2)).saveAsync(any(Event.class)); statsActor.onStatsPersistMsg(new StatsPersistMsg(1, 1, TenantId.SYS_TENANT_ID, TenantId.SYS_TENANT_ID)); - verify(eventService, times(3)).save(any(Event.class)); + verify(eventService, times(3)).saveAsync(any(Event.class)); } } diff --git a/application/src/test/java/org/thingsboard/server/actors/stats/StatsPersistMsgTest.java b/application/src/test/java/org/thingsboard/server/actors/stats/StatsPersistMsgTest.java index e4fcf7cfc4..0b9bf49c93 100644 --- a/application/src/test/java/org/thingsboard/server/actors/stats/StatsPersistMsgTest.java +++ b/application/src/test/java/org/thingsboard/server/actors/stats/StatsPersistMsgTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/cache/CaffeineCacheDefaultConfigurationTest.java b/application/src/test/java/org/thingsboard/server/cache/CaffeineCacheDefaultConfigurationTest.java index eaab5c196e..9893f08aff 100644 --- a/application/src/test/java/org/thingsboard/server/cache/CaffeineCacheDefaultConfigurationTest.java +++ b/application/src/test/java/org/thingsboard/server/cache/CaffeineCacheDefaultConfigurationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,15 +36,15 @@ import static org.assertj.core.api.Assertions.assertThat; public class CaffeineCacheDefaultConfigurationTest { @Autowired - CaffeineCacheConfiguration caffeineCacheConfiguration; + CacheSpecsMap cacheSpecsMap; @Test public void verifyTransactionAwareCacheManagerProxy() { - assertThat(caffeineCacheConfiguration.getSpecs()).as("specs").isNotNull(); - caffeineCacheConfiguration.getSpecs().forEach((name, cacheSpecs)->assertThat(cacheSpecs).as("cache %s specs", name).isNotNull()); + assertThat(cacheSpecsMap.getSpecs()).as("specs").isNotNull(); + cacheSpecsMap.getSpecs().forEach((name, cacheSpecs)->assertThat(cacheSpecs).as("cache %s specs", name).isNotNull()); SoftAssertions softly = new SoftAssertions(); - caffeineCacheConfiguration.getSpecs().forEach((name, cacheSpecs)->{ + cacheSpecsMap.getSpecs().forEach((name, cacheSpecs)->{ softly.assertThat(name).as("cache name").isNotEmpty(); softly.assertThat(cacheSpecs.getTimeToLiveInMinutes()).as("cache %s time to live", name).isGreaterThan(0); softly.assertThat(cacheSpecs.getMaxSize()).as("cache %s max size", name).isGreaterThan(0); diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java index 7521d4b490..ed8d8632da 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,25 @@ package org.thingsboard.server.controller; import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootContextLoader; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.socket.config.annotation.EnableWebSocket; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; @ActiveProfiles("test") @RunWith(SpringRunner.class) @@ -33,9 +42,49 @@ import org.springframework.test.context.web.WebAppConfiguration; @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @Configuration @ComponentScan({"org.thingsboard.server"}) -@WebAppConfiguration -@SpringBootTest() +@EnableWebSocket +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Slf4j -public abstract class AbstractControllerTest extends AbstractWebTest { +public abstract class AbstractControllerTest extends AbstractNotifyEntityTest { + + public static final String WS_URL = "ws://localhost:"; + + @LocalServerPort + protected int wsPort; + + private TbTestWebSocketClient wsClient; // lazy + + public TbTestWebSocketClient getWsClient() { + if (wsClient == null) { + synchronized (this) { + try { + if (wsClient == null) { + wsClient = buildAndConnectWebSocketClient(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + return wsClient; + } + + @Before + public void beforeWsTest() throws Exception { + // placeholder + } + + @After + public void afterWsTest() throws Exception { + if (wsClient != null) { + wsClient.close(); + } + } + + private TbTestWebSocketClient buildAndConnectWebSocketClient() throws URISyntaxException, InterruptedException { + TbTestWebSocketClient wsClient = new TbTestWebSocketClient(new URI(WS_URL + wsPort + "/api/ws/plugins/telemetry?token=" + token)); + assertThat(wsClient.connectBlocking(TIMEOUT, TimeUnit.SECONDS)).isTrue(); + return wsClient; + } } diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractInMemoryStorageTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractInMemoryStorageTest.java index 8daa48722e..efa9d9f08a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractInMemoryStorageTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractInMemoryStorageTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,20 +23,4 @@ import org.thingsboard.server.queue.memory.InMemoryStorage; @Slf4j public abstract class AbstractInMemoryStorageTest { - @Before - public void setUpInMemoryStorage() { - log.info("set up InMemoryStorage"); - cleanupInMemStorage(); - } - - @After - public void tearDownInMemoryStorage() { - log.info("tear down InMemoryStorage"); - cleanupInMemStorage(); - } - - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - } diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java new file mode 100644 index 0000000000..d908ac8d2a --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java @@ -0,0 +1,182 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.controller; + +import lombok.extern.slf4j.Slf4j; +import org.mockito.Mockito; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.id.EntityIdFactory; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; +import org.thingsboard.server.common.msg.TbMsg; +import org.thingsboard.server.dao.audit.AuditLogService; +import org.thingsboard.server.dao.model.ModelConstants; + +import java.util.Locale; + +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.thingsboard.server.service.entitiy.DefaultTbNotificationEntityService.edgeTypeByActionType; + +@Slf4j +public abstract class AbstractNotifyEntityTest extends AbstractWebTest { + + @SpyBean + protected TbClusterService tbClusterService; + + @SpyBean + protected AuditLogService auditLogService; + + protected void testNotifyEntityAllOneTime(HasName entity, EntityId entityId, EntityId originatorId, + TenantId tenantId, CustomerId customerId, UserId userId, String userName, + ActionType actionType, Object... additionalInfo) { + testSendNotificationMsgToEdgeServiceOneTime(entityId, tenantId, actionType); + testLogEntityActionOneTime(entity, originatorId, tenantId, customerId, userId, userName, actionType, additionalInfo); + testPushMsgToRuleEngineOneTime(originatorId, tenantId); + Mockito.reset(tbClusterService, auditLogService); + } + + protected void testNotifyEntityDeleteOneTimeMsgToEdgeServiceNever(HasName entity, EntityId entityId, EntityId originatorId, + TenantId tenantId, CustomerId customerId, UserId userId, String userName, + ActionType actionType, Object... additionalInfo) { + testNotificationMsgToEdgeServiceNever(entityId); + testLogEntityActionOneTime(entity, originatorId, tenantId, customerId, userId, userName, actionType, additionalInfo); + testPushMsgToRuleEngineOneTime(entityId, tenantId); + testBroadcastEntityStateChangeEventOneTime(entityId, tenantId); + Mockito.reset(tbClusterService, auditLogService); + } + protected void testNotifyEntityNeverMsgToEdgeServiceOneTime(HasName entity, EntityId entityId, TenantId tenantId, ActionType actionType) { + testSendNotificationMsgToEdgeServiceOneTime(entityId, tenantId, actionType); + testLogEntityActionNever(entityId, entity); + testPushMsgToRuleEngineNever(entityId); + Mockito.reset(tbClusterService, auditLogService); + } + + protected void testNotifyEntityOneTimeMsgToEdgeServiceNever(HasName entity, EntityId entityId, EntityId originatorId, + TenantId tenantId, CustomerId customerId, UserId userId, String userName, + ActionType actionType, Object... additionalInfo) { + testNotificationMsgToEdgeServiceNever(entityId); + testLogEntityActionOneTime(entity, originatorId, tenantId, customerId, userId, userName, actionType, additionalInfo); + testPushMsgToRuleEngineOneTime(originatorId, tenantId); + Mockito.reset(tbClusterService, auditLogService); + } + + protected void testNotifyEntityBroadcastEntityStateChangeEventOneTimeMsgToEdgeServiceNever(HasName entity, EntityId entityId, EntityId originatorId, + TenantId tenantId, CustomerId customerId, UserId userId, String userName, + ActionType actionType, Object... additionalInfo) { + testNotificationMsgToEdgeServiceNever(entityId); + testLogEntityActionOneTime(entity, originatorId, tenantId, customerId, userId, userName, actionType, additionalInfo); + testPushMsgToRuleEngineOneTime(originatorId, tenantId); + testBroadcastEntityStateChangeEventOneTime(entityId, tenantId); + Mockito.reset(tbClusterService, auditLogService); + } + + protected void testNotifyEntityError(HasName entity, TenantId tenantId, + UserId userId, String userName, ActionType actionType, Exception exp, + Object... additionalInfo) { + CustomerId customer_NULL_UUID = (CustomerId) EntityIdFactory.getByTypeAndUuid(EntityType.CUSTOMER, ModelConstants.NULL_UUID); + EntityId entity_NULL_UUID = EntityIdFactory.getByTypeAndUuid(EntityType.valueOf(entity.getClass().toString() + .substring(entity.getClass().toString().lastIndexOf(".") + 1).toUpperCase(Locale.ENGLISH)), + ModelConstants.NULL_UUID); + testNotificationMsgToEdgeServiceNever(entity_NULL_UUID); + if (additionalInfo.length > 0) { + Mockito.verify(auditLogService, times(1)).logEntityAction(Mockito.eq(tenantId), + Mockito.eq(customer_NULL_UUID), Mockito.eq(userId), Mockito.eq(userName), + Mockito.eq(entity_NULL_UUID), Mockito.any(entity.getClass()), Mockito.eq(actionType), + Mockito.argThat(argument -> + argument.getMessage().equals(exp.getMessage())), Mockito.eq(additionalInfo)); + } else { + Mockito.verify(auditLogService, times(1)).logEntityAction(Mockito.eq(tenantId), + Mockito.eq(customer_NULL_UUID), Mockito.eq(userId), Mockito.eq(userName), + Mockito.eq(entity_NULL_UUID), Mockito.any(entity.getClass()), Mockito.eq(actionType), + Mockito.argThat(argument -> + argument.getMessage().equals(exp.getMessage()))); + } + testPushMsgToRuleEngineNever(entity_NULL_UUID); + Mockito.reset(tbClusterService, auditLogService); + } + + protected void testNotifyEntityNever(EntityId entityId, HasName entity) { + testNotificationMsgToEdgeServiceNever(entityId); + testLogEntityActionNever(entityId, entity); + testPushMsgToRuleEngineNever(entityId); + Mockito.reset(tbClusterService, auditLogService); + } + + private void testNotificationMsgToEdgeServiceNever(EntityId entityId) { + Mockito.verify(tbClusterService, never()).sendNotificationMsgToEdgeService(Mockito.any(), + Mockito.any(), Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any(), Mockito.any()); + } + + private void testLogEntityActionNever(EntityId entityId, HasName entity) { + Mockito.verify(auditLogService, never()).logEntityAction(Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(entityId.getClass()), Mockito.any(entity.getClass()), + Mockito.any(), Mockito.any()); + } + + private void testPushMsgToRuleEngineNever(EntityId entityId) { + Mockito.verify(tbClusterService, never()).pushMsgToRuleEngine(Mockito.any(), + Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any()); + } + + private void testLogEntityActionOneTime(HasName entity, EntityId originatorId, TenantId tenantId, CustomerId customerId, + UserId userId, String userName, ActionType actionType, Object... additionalInfo) { + if (additionalInfo.length == 0) { + Mockito.verify(auditLogService, times(1)).logEntityAction(Mockito.eq(tenantId), Mockito.eq(customerId), + Mockito.eq(userId), Mockito.eq(userName), Mockito.eq(originatorId), + Mockito.eq(entity), Mockito.eq(actionType), Mockito.isNull()); + } else { + String additionalInfoStr = extractParameter(String.class, 0, additionalInfo); + Mockito.verify(auditLogService, times(1)).logEntityAction(Mockito.eq(tenantId), Mockito.eq(customerId), + Mockito.eq(userId), Mockito.eq(userName), Mockito.eq(originatorId), + Mockito.eq(entity), Mockito.eq(actionType), Mockito.isNull(), Mockito.eq(additionalInfoStr)); + } + } + + private void testPushMsgToRuleEngineOneTime(EntityId originatorId, TenantId tenantId) { + Mockito.verify(tbClusterService, times(1)).pushMsgToRuleEngine(Mockito.eq(tenantId), + Mockito.eq(originatorId), Mockito.any(TbMsg.class), Mockito.isNull()); + } + + private void testSendNotificationMsgToEdgeServiceOneTime(EntityId entityId, TenantId tenantId, ActionType actionType) { + Mockito.verify(tbClusterService, times(1)).sendNotificationMsgToEdgeService(Mockito.eq(tenantId), + Mockito.isNull(), Mockito.eq(entityId), Mockito.isNull(), Mockito.isNull(), + Mockito.eq(edgeTypeByActionType(actionType))); + } + + private void testBroadcastEntityStateChangeEventOneTime(EntityId entityId, TenantId tenantId) { + Mockito.verify(tbClusterService, times(1)).broadcastEntityStateChangeEvent(Mockito.eq(tenantId), + Mockito.any(entityId.getClass()), Mockito.any(ComponentLifecycleEvent.class)); + } + + private T extractParameter(Class clazz, int index, Object... additionalInfo) { + T result = null; + if (additionalInfo != null && additionalInfo.length > index) { + Object paramObject = additionalInfo[index]; + if (clazz.isInstance(paramObject)) { + result = clazz.cast(paramObject); + } + } + return result; + } +} diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractRuleEngineControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractRuleEngineControllerTest.java index 518874c28e..ab902b82c6 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractRuleEngineControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractRuleEngineControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Event; import org.thingsboard.server.common.data.id.EntityId; @@ -35,6 +36,9 @@ import java.util.function.Predicate; /** * Created by ashvayka on 20.03.18. */ +@TestPropertySource(properties = { + "js.evaluator=mock", +}) public abstract class AbstractRuleEngineControllerTest extends AbstractControllerTest { @Autowired @@ -57,12 +61,18 @@ public abstract class AbstractRuleEngineControllerTest extends AbstractControlle } protected PageData getDebugEvents(TenantId tenantId, EntityId entityId, int limit) throws Exception { + return getEvents(tenantId, entityId, DataConstants.DEBUG_RULE_NODE, limit); + } + + protected PageData getEvents(TenantId tenantId, EntityId entityId, String eventType, int limit) throws Exception { TimePageLink pageLink = new TimePageLink(limit); return doGetTypedWithTimePageLink("/api/events/{entityType}/{entityId}/{eventType}?tenantId={tenantId}&", new TypeReference>() { - }, pageLink, entityId.getEntityType(), entityId.getId(), DataConstants.DEBUG_RULE_NODE, tenantId.getId()); + }, pageLink, entityId.getEntityType(), entityId.getId(), eventType, tenantId.getId()); } + + protected JsonNode getMetadata(Event outEvent) { String metaDataStr = outEvent.getBody().get("metadata").asText(); try { diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java index 5944cad7b3..24ee2ba371 100644 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,9 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Header; import io.jsonwebtoken.Jwt; @@ -64,8 +67,11 @@ import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.HasId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UUIDBased; +import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; @@ -96,20 +102,28 @@ import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppC @Slf4j public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { + public static final int TIMEOUT = 30; protected ObjectMapper mapper = new ObjectMapper(); protected static final String TEST_TENANT_NAME = "TEST TENANT"; + protected static final String TEST_DIFFERENT_TENANT_NAME = "TEST DIFFERENT TENANT"; protected static final String SYS_ADMIN_EMAIL = "sysadmin@thingsboard.org"; private static final String SYS_ADMIN_PASSWORD = "sysadmin"; protected static final String TENANT_ADMIN_EMAIL = "testtenant@thingsboard.org"; - private static final String TENANT_ADMIN_PASSWORD = "tenant"; + protected static final String TENANT_ADMIN_PASSWORD = "tenant"; + + protected static final String DIFFERENT_TENANT_ADMIN_EMAIL = "testdifftenant@thingsboard.org"; + private static final String DIFFERENT_TENANT_ADMIN_PASSWORD = "difftenant"; protected static final String CUSTOMER_USER_EMAIL = "testcustomer@thingsboard.org"; private static final String CUSTOMER_USER_PASSWORD = "customer"; + protected static final String DIFFERENT_CUSTOMER_USER_EMAIL = "testdifferentcustomer@thingsboard.org"; + private static final String DIFFERENT_CUSTOMER_USER_PASSWORD = "diffcustomer"; + /** See {@link org.springframework.test.web.servlet.DefaultMvcResult#getAsyncResult(long)} * and {@link org.springframework.mock.web.MockAsyncContext#getTimeout()} */ @@ -124,6 +138,12 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { protected String username; protected TenantId tenantId; + protected UserId tenantAdminUserId; + protected CustomerId tenantAdminCustomerId; + protected CustomerId customerId; + protected TenantId differentTenantId; + protected CustomerId differentCustomerId; + protected UserId customerUserId; @SuppressWarnings("rawtypes") private HttpMessageConverter mappingJackson2HttpMessageConverter; @@ -186,12 +206,15 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { tenantAdmin.setTenantId(tenantId); tenantAdmin.setEmail(TENANT_ADMIN_EMAIL); - createUserAndLogin(tenantAdmin, TENANT_ADMIN_PASSWORD); + tenantAdmin = createUserAndLogin(tenantAdmin, TENANT_ADMIN_PASSWORD); + tenantAdminUserId = tenantAdmin.getId(); + tenantAdminCustomerId = tenantAdmin.getCustomerId(); Customer customer = new Customer(); customer.setTitle("Customer"); customer.setTenantId(tenantId); Customer savedCustomer = doPost("/api/customer", customer, Customer.class); + customerId = savedCustomer.getId(); User customerUser = new User(); customerUser.setAuthority(Authority.CUSTOMER_USER); @@ -199,7 +222,8 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { customerUser.setCustomerId(savedCustomer.getId()); customerUser.setEmail(CUSTOMER_USER_EMAIL); - createUserAndLogin(customerUser, CUSTOMER_USER_PASSWORD); + customerUser = createUserAndLogin(customerUser, CUSTOMER_USER_PASSWORD); + customerUserId = customerUser.getId(); logout(); @@ -254,25 +278,63 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { } private Tenant savedDifferentTenant; + private Customer savedDifferentCustomer; protected void loginDifferentTenant() throws Exception { - loginSysAdmin(); - Tenant tenant = new Tenant(); - tenant.setTitle("Different tenant"); - savedDifferentTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedDifferentTenant); - User differentTenantAdmin = new User(); - differentTenantAdmin.setAuthority(Authority.TENANT_ADMIN); - differentTenantAdmin.setTenantId(savedDifferentTenant.getId()); - differentTenantAdmin.setEmail("different_tenant@thingsboard.org"); + if (savedDifferentTenant != null) { + login(savedDifferentTenant.getEmail(), TENANT_ADMIN_PASSWORD); + } else { + loginSysAdmin(); + + Tenant tenant = new Tenant(); + tenant.setTitle(TEST_DIFFERENT_TENANT_NAME); + savedDifferentTenant = doPost("/api/tenant", tenant, Tenant.class); + differentTenantId = savedDifferentTenant.getId(); + Assert.assertNotNull(savedDifferentTenant); + User differentTenantAdmin = new User(); + differentTenantAdmin.setAuthority(Authority.TENANT_ADMIN); + differentTenantAdmin.setTenantId(savedDifferentTenant.getId()); + differentTenantAdmin.setEmail(DIFFERENT_TENANT_ADMIN_EMAIL); + + createUserAndLogin(differentTenantAdmin, DIFFERENT_TENANT_ADMIN_PASSWORD); + } + } + + protected void loginDifferentCustomer() throws Exception { + if (savedDifferentCustomer != null) { + login(savedDifferentCustomer.getEmail(), CUSTOMER_USER_PASSWORD); + } else { + createDifferentCustomer(); + + loginTenantAdmin(); + User differentCustomerUser = new User(); + differentCustomerUser.setAuthority(Authority.CUSTOMER_USER); + differentCustomerUser.setTenantId(tenantId); + differentCustomerUser.setCustomerId(savedDifferentCustomer.getId()); + differentCustomerUser.setEmail(DIFFERENT_CUSTOMER_USER_EMAIL); - createUserAndLogin(differentTenantAdmin, "testPassword"); + createUserAndLogin(differentCustomerUser, DIFFERENT_CUSTOMER_USER_PASSWORD); + } + } + + protected void createDifferentCustomer() throws Exception { + loginTenantAdmin(); + + Customer customer = new Customer(); + customer.setTitle("Different customer"); + savedDifferentCustomer = doPost("/api/customer", customer, Customer.class); + Assert.assertNotNull(savedDifferentCustomer); + differentCustomerId = savedDifferentCustomer.getId(); + + logout(); } protected void deleteDifferentTenant() throws Exception { - loginSysAdmin(); - doDelete("/api/tenant/" + savedDifferentTenant.getId().getId().toString()) - .andExpect(status().isOk()); + if (savedDifferentTenant != null) { + loginSysAdmin(); + doDelete("/api/tenant/" + savedDifferentTenant.getId().getId().toString()) + .andExpect(status().isOk()); + } } protected User createUserAndLogin(User user, String password) throws Exception { @@ -352,18 +414,23 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { } } + protected DeviceProfile createDeviceProfile(String name) { + return createDeviceProfile(name, null); + } + protected DeviceProfile createDeviceProfile(String name, DeviceProfileTransportConfiguration deviceProfileTransportConfiguration) { DeviceProfile deviceProfile = new DeviceProfile(); deviceProfile.setName(name); deviceProfile.setType(DeviceProfileType.DEFAULT); - deviceProfile.setTransportType(DeviceTransportType.DEFAULT); deviceProfile.setDescription(name + " Test"); DeviceProfileData deviceProfileData = new DeviceProfileData(); DefaultDeviceProfileConfiguration configuration = new DefaultDeviceProfileConfiguration(); deviceProfileData.setConfiguration(configuration); if (deviceProfileTransportConfiguration != null) { + deviceProfile.setTransportType(deviceProfileTransportConfiguration.getType()); deviceProfileData.setTransportConfiguration(deviceProfileTransportConfiguration); } else { + deviceProfile.setTransportType(DeviceTransportType.DEFAULT); deviceProfileData.setTransportConfiguration(new DefaultDeviceProfileTransportConfiguration()); } deviceProfile.setProfileData(deviceProfileData); @@ -372,10 +439,11 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { return deviceProfile; } - protected MqttDeviceProfileTransportConfiguration createMqttDeviceProfileTransportConfiguration(TransportPayloadTypeConfiguration transportPayloadTypeConfiguration) { + protected MqttDeviceProfileTransportConfiguration createMqttDeviceProfileTransportConfiguration(TransportPayloadTypeConfiguration transportPayloadTypeConfiguration, boolean sendAckOnValidationException) { MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = new MqttDeviceProfileTransportConfiguration(); mqttDeviceProfileTransportConfiguration.setDeviceTelemetryTopic(MqttTopics.DEVICE_TELEMETRY_TOPIC); mqttDeviceProfileTransportConfiguration.setDeviceTelemetryTopic(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); + mqttDeviceProfileTransportConfiguration.setSendAckOnValidationException(sendAckOnValidationException); mqttDeviceProfileTransportConfiguration.setTransportPayloadTypeConfiguration(transportPayloadTypeConfiguration); return mqttDeviceProfileTransportConfiguration; } @@ -478,16 +546,24 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { return readResponse(doGet(urlTemplate, vars).andExpect(status().isOk()), responseType); } - protected T doPost(String urlTemplate, Class responseClass, String... params) throws Exception { - return readResponse(doPost(urlTemplate, params).andExpect(status().isOk()), responseClass); + protected T doPost(String urlTemplate, Class responseClass, String... params) { + try { + return readResponse(doPost(urlTemplate, params).andExpect(status().isOk()), responseClass); + } catch (Exception e) { + throw new RuntimeException(e); + } } protected T doPost(String urlTemplate, T content, Class responseClass, ResultMatcher resultMatcher, String... params) throws Exception { return readResponse(doPost(urlTemplate, content, params).andExpect(resultMatcher), responseClass); } - protected T doPost(String urlTemplate, T content, Class responseClass, String... params) throws Exception { - return readResponse(doPost(urlTemplate, content, params).andExpect(status().isOk()), responseClass); + protected T doPost(String urlTemplate, T content, Class responseClass, String... params) { + try { + return readResponse(doPost(urlTemplate, content, params).andExpect(status().isOk()), responseClass); + } catch (Exception e) { + throw new RuntimeException(e); + } } protected R doPostWithResponse(String urlTemplate, T content, Class responseClass, String... params) throws Exception { @@ -584,6 +660,10 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { return mapper.readerFor(type).readValue(content); } + protected String getErrorMessage(ResultActions result) throws Exception { + return readResponse(result, JsonNode.class).get("message").asText(); + } + public class IdComparator implements Comparator { @Override public int compare(D o1, D o2) { @@ -606,8 +686,17 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest { edge.setType(type); edge.setSecret(RandomStringUtils.randomAlphanumeric(20)); edge.setRoutingKey(RandomStringUtils.randomAlphanumeric(20)); - edge.setEdgeLicenseKey(RandomStringUtils.randomAlphanumeric(20)); - edge.setCloudEndpoint("http://localhost:8080"); return edge; } + + protected > ListenableFuture> deleteEntitiesAsync(String urlTemplate, List entities, ListeningExecutorService executor) { + List> futures = new ArrayList<>(entities.size()); + for (T entity : entities) { + futures.add(executor.submit(() -> + doDelete(urlTemplate + entity.getId().getId()) + .andExpect(status().isOk()))); + } + return Futures.allAsList(futures); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/AbstractWebsocketTest.java b/application/src/test/java/org/thingsboard/server/controller/AbstractWebsocketTest.java deleted file mode 100644 index 52f8082e22..0000000000 --- a/application/src/test/java/org/thingsboard/server/controller/AbstractWebsocketTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.controller; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Header; -import io.jsonwebtoken.Jwt; -import io.jsonwebtoken.Jwts; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.hamcrest.Matcher; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootContextLoader; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.mock.http.MockHttpInputMessage; -import org.springframework.mock.http.MockHttpOutputMessage; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.ResultMatcher; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.context.WebApplicationContext; -import org.thingsboard.server.common.data.BaseData; -import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.common.data.id.UUIDBased; -import org.thingsboard.server.common.data.page.PageLink; -import org.thingsboard.server.common.data.page.TimePageLink; -import org.thingsboard.server.common.data.security.Authority; -import org.thingsboard.server.config.ThingsboardSecurityConfiguration; -import org.thingsboard.server.service.mail.TestMailService; -import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRequest; -import org.thingsboard.server.service.security.auth.rest.LoginRequest; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -@ActiveProfiles("test") -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = AbstractControllerTest.class, loader = SpringBootContextLoader.class) -@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -@Configuration -@ComponentScan({"org.thingsboard.server"}) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@Slf4j -public abstract class AbstractWebsocketTest extends AbstractWebTest { - - protected static final String WS_URL = "ws://localhost:"; - - @LocalServerPort - protected int wsPort; - - protected TbTestWebSocketClient buildAndConnectWebSocketClient() throws URISyntaxException, InterruptedException { - TbTestWebSocketClient wsClient = new TbTestWebSocketClient(new URI(WS_URL + wsPort + "/api/ws/plugins/telemetry?token=" + token)); - Assert.assertTrue(wsClient.connectBlocking()); - return wsClient; - } - -} diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAdminControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAdminControllerTest.java index b0b2d84be9..b89133f29a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAdminControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAdminControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java new file mode 100644 index 0000000000..7f1943d8bd --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java @@ -0,0 +1,421 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.alarm.AlarmInfo; +import org.thingsboard.server.common.data.alarm.AlarmSeverity; +import org.thingsboard.server.common.data.alarm.AlarmStatus; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.page.PageData; + +import java.util.LinkedList; +import java.util.List; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@Slf4j +public abstract class BaseAlarmControllerTest extends AbstractControllerTest { + + public static final String TEST_ALARM_TYPE = "Test"; + + protected Device customerDevice; + + @Before + public void setup() throws Exception { + loginTenantAdmin(); + + Device device = new Device(); + device.setTenantId(tenantId); + device.setName("Test device"); + device.setLabel("Label"); + device.setType("Type"); + device.setCustomerId(customerId); + customerDevice = doPost("/api/device", device, Device.class); + + logout(); + } + + @After + public void teardown() throws Exception { + loginSysAdmin(); + deleteDifferentTenant(); + } + + @Test + public void testCreateAlarmViaCustomer() throws Exception { + loginCustomerUser(); + + Mockito.reset(tbClusterService, auditLogService); + + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + testNotifyEntityAllOneTime(alarm, alarm.getId(), alarm.getOriginator(), + tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.ADDED); + } + + @Test + public void testCreateAlarmViaTenant() throws Exception { + loginTenantAdmin(); + + Mockito.reset(tbClusterService, auditLogService); + + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + testNotifyEntityAllOneTime(alarm, alarm.getId(), alarm.getOriginator(), + tenantId, customerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.ADDED); + } + + @Test + public void testUpdateAlarmViaCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + alarm.setSeverity(AlarmSeverity.MAJOR); + Alarm updatedAlarm = doPost("/api/alarm", alarm, Alarm.class); + Assert.assertNotNull(updatedAlarm); + Assert.assertEquals(AlarmSeverity.MAJOR, updatedAlarm.getSeverity()); + + testNotifyEntityAllOneTime(updatedAlarm, updatedAlarm.getId(), updatedAlarm.getOriginator(), + tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.UPDATED); + } + + @Test + public void testUpdateAlarmViaTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + alarm.setSeverity(AlarmSeverity.MAJOR); + Alarm updatedAlarm = doPost("/api/alarm", alarm, Alarm.class); + Assert.assertNotNull(updatedAlarm); + Assert.assertEquals(AlarmSeverity.MAJOR, updatedAlarm.getSeverity()); + + testNotifyEntityAllOneTime(updatedAlarm, updatedAlarm.getId(), updatedAlarm.getOriginator(), + tenantId, customerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.UPDATED); + } + + @Test + public void testUpdateAlarmViaDifferentTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + alarm.setSeverity(AlarmSeverity.MAJOR); + loginDifferentTenant(); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm", alarm).andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testUpdateAlarmViaDifferentCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentCustomer(); + alarm.setSeverity(AlarmSeverity.MAJOR); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm", alarm).andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testDeleteAlarmViaCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isOk()); + + testNotifyEntityOneTimeMsgToEdgeServiceNever(alarm, alarm.getId(), alarm.getOriginator(), + tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.DELETED); + } + + @Test + public void testDeleteAlarmViaTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isOk()); + + testNotifyEntityOneTimeMsgToEdgeServiceNever(alarm, alarm.getId(), alarm.getOriginator(), + tenantId, tenantAdminCustomerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.DELETED); + } + + @Test + public void testDeleteAlarmViaDifferentTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentTenant(); + + Mockito.reset(tbClusterService, auditLogService); + + doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testDeleteAlarmViaDifferentCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentCustomer(); + + Mockito.reset(tbClusterService, auditLogService); + + doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testClearAlarmViaCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isOk()); + + Alarm foundAlarm = doGet("/api/alarm/" + alarm.getId(), Alarm.class); + Assert.assertNotNull(foundAlarm); + Assert.assertEquals(AlarmStatus.CLEARED_UNACK, foundAlarm.getStatus()); + + testNotifyEntityAllOneTime(foundAlarm, foundAlarm.getId(), foundAlarm.getOriginator(), + tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.ALARM_CLEAR); + } + + @Test + public void testClearAlarmViaTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isOk()); + Alarm foundAlarm = doGet("/api/alarm/" + alarm.getId(), Alarm.class); + Assert.assertNotNull(foundAlarm); + Assert.assertEquals(AlarmStatus.CLEARED_UNACK, foundAlarm.getStatus()); + + testNotifyEntityAllOneTime(foundAlarm, foundAlarm.getId(), foundAlarm.getOriginator(), + tenantId, customerId, tenantAdminUserId, TENANT_ADMIN_EMAIL, ActionType.ALARM_CLEAR); + } + + @Test + public void testAcknowledgeAlarmViaCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/ack").andExpect(status().isOk()); + + Alarm foundAlarm = doGet("/api/alarm/" + alarm.getId(), Alarm.class); + Assert.assertNotNull(foundAlarm); + Assert.assertEquals(AlarmStatus.ACTIVE_ACK, foundAlarm.getStatus()); + + testNotifyEntityAllOneTime(foundAlarm, foundAlarm.getId(), foundAlarm.getOriginator(), + tenantId, customerId, customerUserId, CUSTOMER_USER_EMAIL, ActionType.ALARM_ACK); + } + + @Test + public void testClearAlarmViaDifferentCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentCustomer(); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testClearAlarmViaDifferentTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentTenant(); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testAcknowledgeAlarmViaDifferentCustomer() throws Exception { + loginCustomerUser(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentCustomer(); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/ack").andExpect(status().isForbidden()); + + testNotifyEntityNever(alarm.getId(), alarm); + } + + @Test + public void testAcknowledgeAlarmViaDifferentTenant() throws Exception { + loginTenantAdmin(); + Alarm alarm = createAlarm(TEST_ALARM_TYPE); + + loginDifferentTenant(); + + Mockito.reset(tbClusterService, auditLogService); + + doPost("/api/alarm/" + alarm.getId() + "/ack").andExpect(status().isForbidden()); + } + + @Test + public void testFindAlarmsViaCustomerUser() throws Exception { + loginCustomerUser(); + + List createdAlarms = new LinkedList<>(); + + final int size = 10; + for (int i = 0; i < size; i++) { + createdAlarms.add( + createAlarm(TEST_ALARM_TYPE + i) + ); + } + + var response = doGetTyped( + "/api/alarm/" + EntityType.DEVICE + "/" + + customerDevice.getUuidId() + "?page=0&pageSize=" + size, + new TypeReference>() {} + ); + var foundAlarmInfos = response.getData(); + Assert.assertNotNull("Found pageData is null", foundAlarmInfos); + Assert.assertNotEquals( + "Expected alarms are not found!", + 0, foundAlarmInfos.size() + ); + + boolean allMatch = createdAlarms.stream() + .allMatch(alarm -> foundAlarmInfos.stream() + .map(Alarm::getType) + .anyMatch(type -> alarm.getType().equals(type)) + ); + Assert.assertTrue("Created alarm doesn't match any found!", allMatch); + } + + @Test + public void testFindAlarmsViaDifferentCustomerUser() throws Exception { + loginCustomerUser(); + + final int size = 10; + for (int i = 0; i < size; i++) { + createAlarm(TEST_ALARM_TYPE + i); + } + + loginDifferentCustomer(); + doGet("/api/alarm/" + EntityType.DEVICE + "/" + + customerDevice.getUuidId() + "?page=0&pageSize=" + size) + .andExpect(status().isForbidden()); + } + + @Test + public void testFindAlarmsViaPublicCustomer() throws Exception { + loginTenantAdmin(); + + Device device = new Device(); + device.setName("Test Public Device"); + device.setLabel("Label"); + device.setCustomerId(customerId); + device = doPost("/api/device", device, Device.class); + device = doPost("/api/customer/public/device/" + device.getUuidId(), Device.class); + + String publicId = device.getCustomerId().toString(); + + Alarm alarm = Alarm.builder() + .originator(device.getId()) + .status(AlarmStatus.ACTIVE_UNACK) + .severity(AlarmSeverity.CRITICAL) + .type("Test") + .build(); + + Mockito.reset(tbClusterService, auditLogService); + + alarm = doPost("/api/alarm", alarm, Alarm.class); + Assert.assertNotNull("Saved alarm is null!", alarm); + + testNotifyEntityNeverMsgToEdgeServiceOneTime(alarm, alarm.getId(), tenantId, ActionType.ADDED); + + logout(); + + JsonNode publicLoginRequest = JacksonUtil.toJsonNode("{\"publicId\": \"" + publicId + "\"}"); + JsonNode tokens = doPost("/api/auth/login/public", publicLoginRequest, JsonNode.class); + this.token = tokens.get("token").asText(); + + PageData pageData = doGetTyped( + "/api/alarm/DEVICE/" + device.getUuidId() + "?page=0&pageSize=1", new TypeReference>() {} + ); + + Assert.assertNotNull("Found pageData is null", pageData); + Assert.assertNotEquals("Expected alarms are not found!", 0, pageData.getTotalElements()); + + AlarmInfo alarmInfo = pageData.getData().get(0); + boolean equals = alarm.getId().equals(alarmInfo.getId()) && alarm.getType().equals(alarmInfo.getType()); + Assert.assertTrue("Created alarm doesn't match the found one!", equals); + } + + private Alarm createAlarm(String type) throws Exception { + Alarm alarm = Alarm.builder() + .tenantId(tenantId) + .customerId(customerId) + .originator(customerDevice.getId()) + .status(AlarmStatus.ACTIVE_UNACK) + .severity(AlarmSeverity.CRITICAL) + .type(type) + .build(); + + alarm = doPost("/api/alarm", alarm, Alarm.class); + Assert.assertNotNull(alarm); + + return alarm; + } +} diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java index c72b732ff6..0861ab34c8 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.EntitySubtype; +import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.asset.Asset; @@ -182,6 +183,39 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest { .andExpect(status().isNotFound()); } + @Test + public void testDeleteAssetAssignedToEntityView() throws Exception { + Asset asset1 = new Asset(); + asset1.setName("My asset 1"); + asset1.setType("default"); + Asset savedAsset1 = doPost("/api/asset", asset1, Asset.class); + + Asset asset2 = new Asset(); + asset2.setName("My asset 2"); + asset2.setType("default"); + Asset savedAsset2 = doPost("/api/asset", asset2, Asset.class); + + EntityView view = new EntityView(); + view.setEntityId(savedAsset1.getId()); + view.setTenantId(savedTenant.getId()); + view.setName("My entity view"); + view.setType("default"); + EntityView savedView = doPost("/api/entityView", view, EntityView.class); + + doDelete("/api/asset/" + savedAsset1.getId().getId().toString()) + .andExpect(status().isBadRequest()); + + savedView.setEntityId(savedAsset2.getId()); + + doPost("/api/entityView", savedView, EntityView.class); + + doDelete("/api/asset/" + savedAsset1.getId().getId().toString()) + .andExpect(status().isOk()); + + doGet("/api/asset/" + savedAsset1.getId().getId().toString()) + .andExpect(status().isNotFound()); + } + @Test public void testSaveAssetWithEmptyType() throws Exception { Asset asset = new Asset(); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAuditLogControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAuditLogControllerTest.java index 3bdb1b33a4..5369d4d30a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAuditLogControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAuditLogControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseAuthControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseAuthControllerTest.java index 3477b820f7..f64cac0f99 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseAuthControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseAuthControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseComponentDescriptorControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseComponentDescriptorControllerTest.java index 977583b4c9..7a010927c5 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseComponentDescriptorControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseComponentDescriptorControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java index 318e1413a0..1f94fa4784 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,37 +15,49 @@ */ package org.thingsboard.server.controller; -import static org.hamcrest.Matchers.containsString; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - +import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; +import org.junit.Assert; import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.security.Authority; -import org.junit.Assert; -import org.junit.Test; +import org.thingsboard.server.dao.exception.DataValidationException; -import com.fasterxml.jackson.core.type.TypeReference; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public abstract class BaseCustomerControllerTest extends AbstractControllerTest { + static final TypeReference> PAGE_DATA_CUSTOMER_TYPE_REFERENCE = new TypeReference<>() { + }; - private IdComparator idComparator = new IdComparator<>(); + ListeningExecutorService executor; private Tenant savedTenant; private User tenantAdmin; @Before public void beforeTest() throws Exception { + executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass())); + loginSysAdmin(); Tenant tenant = new Tenant(); @@ -65,6 +77,8 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest @After public void afterTest() throws Exception { + executor.shutdownNow(); + loginSysAdmin(); doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) @@ -75,41 +89,89 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest public void testSaveCustomer() throws Exception { Customer customer = new Customer(); customer.setTitle("My customer"); + + Mockito.reset(tbClusterService, auditLogService); + Customer savedCustomer = doPost("/api/customer", customer, Customer.class); + + testNotifyEntityOneTimeMsgToEdgeServiceNever(savedCustomer, savedCustomer.getId(), savedCustomer.getId(), + savedCustomer.getTenantId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), + ActionType.ADDED); + Assert.assertNotNull(savedCustomer); Assert.assertNotNull(savedCustomer.getId()); Assert.assertTrue(savedCustomer.getCreatedTime() > 0); Assert.assertEquals(customer.getTitle(), savedCustomer.getTitle()); + savedCustomer.setTitle("My new customer"); + doPost("/api/customer", savedCustomer, Customer.class); - Customer foundCustomer = doGet("/api/customer/"+savedCustomer.getId().getId().toString(), Customer.class); + testNotifyEntityAllOneTime(savedCustomer, savedCustomer.getId(), savedCustomer.getId(), savedCustomer.getTenantId(), + savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), + ActionType.UPDATED); + + Customer foundCustomer = doGet("/api/customer/" + savedCustomer.getId().getId().toString(), Customer.class); Assert.assertEquals(foundCustomer.getTitle(), savedCustomer.getTitle()); - doDelete("/api/customer/"+savedCustomer.getId().getId().toString()) - .andExpect(status().isOk()); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) + .andExpect(status().isOk()); } @Test public void testSaveCustomerWithViolationOfValidation() throws Exception { Customer customer = new Customer(); + String validationError = "Validation error: "; customer.setTitle(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of title must be equal or less than 255"))); + + Mockito.reset(tbClusterService, auditLogService); + + String msgError = "length of title must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + customer.setTitle("Normal title"); customer.setCity(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of city must be equal or less than 255"))); + msgError = "length of city must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + customer.setCity("Normal city"); customer.setCountry(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of country must be equal or less than 255"))); + msgError = "length of country must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + customer.setCountry("Ukraine"); customer.setPhone(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of phone must be equal or less than 255"))); + msgError = "length of phone must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + customer.setPhone("+3892555554512"); customer.setState(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of state must be equal or less than 255"))); + msgError = "length of state must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + customer.setState("Normal state"); customer.setZip(RandomStringUtils.randomAlphabetic(300)); - doPost("/api/customer", customer).andExpect(statusReason(containsString("length of zip or postal code must be equal or less than 255"))); + msgError = "length of zip or postal code must be equal or less than 255"; + doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(validationError + msgError)); + } @Test @@ -120,12 +182,22 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest doPost("/api/customer", savedCustomer, Customer.class); loginDifferentTenant(); + + Mockito.reset(tbClusterService, auditLogService); + doPost("/api/customer", savedCustomer, Customer.class, status().isForbidden()); - deleteDifferentTenant(); + testNotifyEntityNever(savedCustomer.getId(), savedCustomer); + + deleteDifferentTenant(); login(tenantAdmin.getName(), "testPassword1"); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) .andExpect(status().isOk()); + + testNotifyEntityBroadcastEntityStateChangeEventOneTimeMsgToEdgeServiceNever(savedCustomer, savedCustomer.getId(), + savedCustomer.getId(), savedCustomer.getTenantId(), savedCustomer.getId(), tenantAdmin.getId(), + tenantAdmin.getEmail(), ActionType.DELETED, savedCustomer.getId().getId().toString()); } @Test @@ -138,6 +210,8 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest Assert.assertNotNull(foundCustomer); Assert.assertEquals(savedCustomer, foundCustomer); + Mockito.reset(tbClusterService, auditLogService); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) .andExpect(status().isOk()); } @@ -148,9 +222,15 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest customer.setTitle("My customer"); Customer savedCustomer = doPost("/api/customer", customer, Customer.class); + Mockito.reset(tbClusterService, auditLogService); + doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) .andExpect(status().isOk()); + testNotifyEntityBroadcastEntityStateChangeEventOneTimeMsgToEdgeServiceNever(savedCustomer, savedCustomer.getId(), + savedCustomer.getId(), savedCustomer.getTenantId(), savedCustomer.getId(), tenantAdmin.getId(), + tenantAdmin.getEmail(), ActionType.DELETED, savedCustomer.getId().getId().toString()); + doGet("/api/customer/" + savedCustomer.getId().getId().toString()) .andExpect(status().isNotFound()); } @@ -158,53 +238,63 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest @Test public void testSaveCustomerWithEmptyTitle() throws Exception { Customer customer = new Customer(); + String msgError = "Customer title should be specified"; + + Mockito.reset(tbClusterService, auditLogService); + doPost("/api/customer", customer) .andExpect(status().isBadRequest()) - .andExpect(statusReason(containsString("Customer title should be specified"))); + .andExpect(statusReason(containsString(msgError))); + + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError + "!")); } @Test public void testSaveCustomerWithInvalidEmail() throws Exception { Customer customer = new Customer(); + String msgError = "Invalid email address format 'invalid@mail'"; customer.setTitle("My customer"); customer.setEmail("invalid@mail"); + + Mockito.reset(tbClusterService, auditLogService); + doPost("/api/customer", customer) .andExpect(status().isBadRequest()) - .andExpect(statusReason(containsString("Invalid email address format 'invalid@mail'"))); + .andExpect(statusReason(containsString(msgError))); -// loginSysAdmin(); -// -// doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) -// .andExpect(status().isOk()); + testNotifyEntityError(customer, savedTenant.getId(), + tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError + "!")); } @Test public void testFindCustomers() throws Exception { TenantId tenantId = savedTenant.getId(); - List customers = new ArrayList<>(); + List> futures = new ArrayList<>(135); for (int i = 0; i < 135; i++) { Customer customer = new Customer(); customer.setTenantId(tenantId); customer.setTitle("Customer" + i); - customers.add(doPost("/api/customer", customer, Customer.class)); + futures.add(executor.submit(() -> + doPost("/api/customer", customer, Customer.class))); } + List customers = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); - List loadedCustomers = new ArrayList<>(); + List loadedCustomers = new ArrayList<>(135); PageLink pageLink = new PageLink(23); PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/customers?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customers?", PAGE_DATA_CUSTOMER_TYPE_REFERENCE, pageLink); loadedCustomers.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(customers, idComparator); - Collections.sort(loadedCustomers, idComparator); + assertThat(customers).containsExactlyInAnyOrderElementsOf(loadedCustomers); - Assert.assertEquals(customers, loadedCustomers); + deleteEntitiesAsync("/api/customer/", loadedCustomers, executor).get(TIMEOUT, TimeUnit.SECONDS); } @Test @@ -212,7 +302,7 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest TenantId tenantId = savedTenant.getId(); String title1 = "Customer title 1"; - List customersTitle1 = new ArrayList<>(); + List> futures = new ArrayList<>(143); for (int i = 0; i < 143; i++) { Customer customer = new Customer(); customer.setTenantId(tenantId); @@ -220,10 +310,13 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest String title = title1 + suffix; title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); customer.setTitle(title); - customersTitle1.add(doPost("/api/customer", customer, Customer.class)); + futures.add(executor.submit(() -> + doPost("/api/customer", customer, Customer.class))); } + List customersTitle1 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + String title2 = "Customer title 2"; - List customersTitle2 = new ArrayList<>(); + futures = new ArrayList<>(175); for (int i = 0; i < 175; i++) { Customer customer = new Customer(); customer.setTenantId(tenantId); @@ -231,57 +324,48 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest String title = title2 + suffix; title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); customer.setTitle(title); - customersTitle2.add(doPost("/api/customer", customer, Customer.class)); + futures.add(executor.submit(() -> + doPost("/api/customer", customer, Customer.class))); } + List customersTitle2 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + List loadedCustomersTitle1 = new ArrayList<>(); PageLink pageLink = new PageLink(15, 0, title1); PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/customers?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customers?", PAGE_DATA_CUSTOMER_TYPE_REFERENCE, pageLink); loadedCustomersTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(customersTitle1, idComparator); - Collections.sort(loadedCustomersTitle1, idComparator); - - Assert.assertEquals(customersTitle1, loadedCustomersTitle1); + assertThat(customersTitle1).as(title1).containsExactlyInAnyOrderElementsOf(loadedCustomersTitle1); List loadedCustomersTitle2 = new ArrayList<>(); pageLink = new PageLink(4, 0, title2); do { - pageData = doGetTypedWithPageLink("/api/customers?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customers?", PAGE_DATA_CUSTOMER_TYPE_REFERENCE, pageLink); loadedCustomersTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(customersTitle2, idComparator); - Collections.sort(loadedCustomersTitle2, idComparator); - - Assert.assertEquals(customersTitle2, loadedCustomersTitle2); + assertThat(customersTitle2).as(title2).containsExactlyInAnyOrderElementsOf(loadedCustomersTitle2); - for (Customer customer : loadedCustomersTitle1) { - doDelete("/api/customer/" + customer.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/customer/", loadedCustomersTitle1, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4, 0, title1); - pageData = doGetTypedWithPageLink("/api/customers?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customers?", PAGE_DATA_CUSTOMER_TYPE_REFERENCE, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - for (Customer customer : loadedCustomersTitle2) { - doDelete("/api/customer/" + customer.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/customer/", loadedCustomersTitle2, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4, 0, title2); - pageData = doGetTypedWithPageLink("/api/customers?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customers?", PAGE_DATA_CUSTOMER_TYPE_REFERENCE, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java index 18fa8bdd5d..170b3ec817 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java index c31f5c7daf..d6e30c644c 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,17 @@ package org.thingsboard.server.controller; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntitySubtype; @@ -41,22 +47,32 @@ import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.model.ModelConstants; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import java.util.concurrent.TimeUnit; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID; +@Slf4j public abstract class BaseDeviceControllerTest extends AbstractControllerTest { + static final TypeReference> PAGE_DATA_DEVICE_TYPE_REF = new TypeReference<>() { + }; - private IdComparator idComparator = new IdComparator<>(); + ListeningExecutorService executor; + + List> futures; + PageData pageData; private Tenant savedTenant; private User tenantAdmin; @Before public void beforeTest() throws Exception { + log.debug("beforeTest"); + executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass())); + loginSysAdmin(); Tenant tenant = new Tenant(); @@ -76,10 +92,14 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { @After public void afterTest() throws Exception { + log.debug("afterTest..."); + executor.shutdownNow(); + loginSysAdmin(); - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + doDelete("/api/tenant/" + savedTenant.getId().getId()) .andExpect(status().isOk()); + log.debug("afterTest done"); } @Test @@ -98,7 +118,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { Assert.assertEquals(device.getName(), savedDevice.getName()); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); Assert.assertNotNull(deviceCredentials); Assert.assertNotNull(deviceCredentials.getId()); @@ -110,7 +130,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { savedDevice.setName("My new device"); doPost("/api/device", savedDevice, Device.class); - Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId().toString(), Device.class); + Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Assert.assertEquals(foundDevice.getName(), savedDevice.getName()); } @@ -145,7 +165,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setName("My device"); device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); - Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId().toString(), Device.class); + Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Assert.assertNotNull(foundDevice); Assert.assertEquals(savedDevice, foundDevice); } @@ -180,6 +200,8 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { Assert.assertEquals("typeA", deviceTypes.get(0).getType()); Assert.assertEquals("typeB", deviceTypes.get(1).getType()); Assert.assertEquals("typeC", deviceTypes.get(2).getType()); + + deleteEntitiesAsync("/api/device/", devices, executor).get(TIMEOUT, TimeUnit.SECONDS); } @Test @@ -189,10 +211,10 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); - doDelete("/api/device/" + savedDevice.getId().getId().toString()) + doDelete("/api/device/" + savedDevice.getId().getId()) .andExpect(status().isOk()); - doGet("/api/device/" + savedDevice.getId().getId().toString()) + doGet("/api/device/" + savedDevice.getId().getId()) .andExpect(status().isNotFound()); } @@ -224,18 +246,18 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { customer.setTitle("My customer"); Customer savedCustomer = doPost("/api/customer", customer, Customer.class); - Device assignedDevice = doPost("/api/customer/" + savedCustomer.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + Device assignedDevice = doPost("/api/customer/" + savedCustomer.getId().getId() + + "/device/" + savedDevice.getId().getId(), Device.class); Assert.assertEquals(savedCustomer.getId(), assignedDevice.getCustomerId()); - Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId().toString(), Device.class); + Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Assert.assertEquals(savedCustomer.getId(), foundDevice.getCustomerId()); Device unassignedDevice = - doDelete("/api/customer/device/" + savedDevice.getId().getId().toString(), Device.class); + doDelete("/api/customer/device/" + savedDevice.getId().getId(), Device.class); Assert.assertEquals(ModelConstants.NULL_UUID, unassignedDevice.getCustomerId().getId()); - foundDevice = doGet("/api/device/" + savedDevice.getId().getId().toString(), Device.class); + foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Assert.assertEquals(ModelConstants.NULL_UUID, foundDevice.getCustomerId().getId()); } @@ -246,7 +268,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); doPost("/api/customer/" + Uuids.timeBased().toString() - + "/device/" + savedDevice.getId().getId().toString()) + + "/device/" + savedDevice.getId().getId()) .andExpect(status().isNotFound()); } @@ -279,13 +301,13 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); - doPost("/api/customer/" + savedCustomer.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString()) + doPost("/api/customer/" + savedCustomer.getId().getId() + + "/device/" + savedDevice.getId().getId()) .andExpect(status().isForbidden()); loginSysAdmin(); - doDelete("/api/tenant/" + savedTenant2.getId().getId().toString()) + doDelete("/api/tenant/" + savedTenant2.getId().getId()) .andExpect(status().isOk()); } @@ -296,7 +318,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); } @@ -307,7 +329,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); deviceCredentials.setCredentialsId("access_token"); @@ -315,7 +337,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { .andExpect(status().isOk()); DeviceCredentials foundDeviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); Assert.assertEquals(deviceCredentials, foundDeviceCredentials); } @@ -334,7 +356,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); deviceCredentials.setCredentialsType(null); doPost("/api/device/credentials", deviceCredentials) .andExpect(status().isBadRequest()) @@ -348,7 +370,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); deviceCredentials.setCredentialsId(null); doPost("/api/device/credentials", deviceCredentials) .andExpect(status().isBadRequest()) @@ -362,7 +384,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); DeviceCredentials newDeviceCredentials = new DeviceCredentials(new DeviceCredentialsId(Uuids.timeBased())); newDeviceCredentials.setCreatedTime(deviceCredentials.getCreatedTime()); newDeviceCredentials.setDeviceId(deviceCredentials.getDeviceId()); @@ -380,7 +402,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); deviceCredentials.setDeviceId(new DeviceId(Uuids.timeBased())); doPost("/api/device/credentials", deviceCredentials) .andExpect(status().isNotFound()); @@ -388,19 +410,24 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { @Test public void testFindTenantDevices() throws Exception { - List devices = new ArrayList<>(); + log.debug("testFindTenantDevices"); + futures = new ArrayList<>(178); for (int i = 0; i < 178; i++) { Device device = new Device(); device.setName("Device" + i); device.setType("default"); - devices.add(doPost("/api/device", device, Device.class)); + futures.add(executor.submit(() -> + doPost("/api/device", device, Device.class))); } - List loadedDevices = new ArrayList<>(); + log.debug("await create devices"); + List devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + + log.debug("start reading"); + List loadedDevices = new ArrayList<>(178); PageLink pageLink = new PageLink(23); - PageData pageData = null; do { pageData = doGetTypedWithPageLink("/api/tenant/devices?", - new TypeReference>(){}, pageLink); + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevices.addAll(pageData.getData()); if (pageData.hasNext()) { @@ -408,16 +435,18 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { } } while (pageData.hasNext()); - Collections.sort(devices, idComparator); - Collections.sort(loadedDevices, idComparator); - - Assert.assertEquals(devices, loadedDevices); + log.debug("asserting"); + assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices); + log.debug("delete devices async"); + deleteEntitiesAsync("/api/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("done"); } @Test public void testFindTenantDevicesByName() throws Exception { String title1 = "Device title 1"; - List devicesTitle1 = new ArrayList<>(); + + futures = new ArrayList<>(143); for (int i = 0; i < 143; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -425,10 +454,13 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); - devicesTitle1.add(doPost("/api/device", device, Device.class)); + futures.add(executor.submit(() -> + doPost("/api/device", device, Device.class))); } + List devicesTitle1 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + String title2 = "Device title 2"; - List devicesTitle2 = new ArrayList<>(); + futures = new ArrayList<>(75); for (int i = 0; i < 75; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -436,59 +468,50 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); - devicesTitle2.add(doPost("/api/device", device, Device.class)); + futures.add(executor.submit(() -> + doPost("/api/device", device, Device.class))); } + List devicesTitle2 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); - List loadedDevicesTitle1 = new ArrayList<>(); + List loadedDevicesTitle1 = new ArrayList<>(143); PageLink pageLink = new PageLink(15, 0, title1); - PageData pageData = null; do { pageData = doGetTypedWithPageLink("/api/tenant/devices?", - new TypeReference>(){}, pageLink); + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevicesTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesTitle1, idComparator); - Collections.sort(loadedDevicesTitle1, idComparator); - - Assert.assertEquals(devicesTitle1, loadedDevicesTitle1); + assertThat(devicesTitle1).as(title1).containsExactlyInAnyOrderElementsOf(loadedDevicesTitle1); - List loadedDevicesTitle2 = new ArrayList<>(); + List loadedDevicesTitle2 = new ArrayList<>(75); pageLink = new PageLink(4, 0, title2); do { pageData = doGetTypedWithPageLink("/api/tenant/devices?", - new TypeReference>(){}, pageLink); + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevicesTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesTitle2, idComparator); - Collections.sort(loadedDevicesTitle2, idComparator); + assertThat(devicesTitle2).as(title2).containsExactlyInAnyOrderElementsOf(loadedDevicesTitle2); - Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); + deleteEntitiesAsync("/api/device/", loadedDevicesTitle1, executor).get(TIMEOUT, TimeUnit.SECONDS); - for (Device device : loadedDevicesTitle1) { - doDelete("/api/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } pageLink = new PageLink(4, 0, title1); pageData = doGetTypedWithPageLink("/api/tenant/devices?", - new TypeReference>(){}, pageLink); + PAGE_DATA_DEVICE_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - for (Device device : loadedDevicesTitle2) { - doDelete("/api/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/device/", loadedDevicesTitle2, executor).get(TIMEOUT, TimeUnit.SECONDS); + pageLink = new PageLink(4, 0, title2); pageData = doGetTypedWithPageLink("/api/tenant/devices?", - new TypeReference>(){}, pageLink); + PAGE_DATA_DEVICE_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @@ -497,7 +520,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { public void testFindTenantDevicesByType() throws Exception { String title1 = "Device title 1"; String type1 = "typeA"; - List devicesType1 = new ArrayList<>(); + futures = new ArrayList<>(143); for (int i = 0; i < 143; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -505,11 +528,17 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type1); - devicesType1.add(doPost("/api/device", device, Device.class)); + futures.add(executor.submit(() -> + doPost("/api/device", device, Device.class))); + if (i == 0) { + futures.get(0).get(TIMEOUT, TimeUnit.SECONDS); // wait for the device profile created first time + } } + List devicesType1 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + String title2 = "Device title 2"; String type2 = "typeB"; - List devicesType2 = new ArrayList<>(); + futures = new ArrayList<>(75); for (int i = 0; i < 75; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -517,61 +546,54 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type2); - devicesType2.add(doPost("/api/device", device, Device.class)); + futures.add(executor.submit(() -> + doPost("/api/device", device, Device.class))); + if (i == 0) { + futures.get(0).get(TIMEOUT, TimeUnit.SECONDS); // wait for the device profile created first time + } } - List loadedDevicesType1 = new ArrayList<>(); + List devicesType2 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + + List loadedDevicesType1 = new ArrayList<>(143); PageLink pageLink = new PageLink(15); - PageData pageData = null; do { pageData = doGetTypedWithPageLink("/api/tenant/devices?type={type}&", - new TypeReference>(){}, pageLink, type1); + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type1); loadedDevicesType1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesType1, idComparator); - Collections.sort(loadedDevicesType1, idComparator); + assertThat(devicesType1).as(title1).containsExactlyInAnyOrderElementsOf(loadedDevicesType1); - Assert.assertEquals(devicesType1, loadedDevicesType1); - - List loadedDevicesType2 = new ArrayList<>(); + List loadedDevicesType2 = new ArrayList<>(75); pageLink = new PageLink(4); do { pageData = doGetTypedWithPageLink("/api/tenant/devices?type={type}&", - new TypeReference>(){}, pageLink, type2); + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type2); loadedDevicesType2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesType2, idComparator); - Collections.sort(loadedDevicesType2, idComparator); - - Assert.assertEquals(devicesType2, loadedDevicesType2); + assertThat(devicesType2).as(title2).containsExactlyInAnyOrderElementsOf(loadedDevicesType2); - for (Device device : loadedDevicesType1) { - doDelete("/api/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/device/", loadedDevicesType1, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4); pageData = doGetTypedWithPageLink("/api/tenant/devices?type={type}&", - new TypeReference>(){}, pageLink, type1); + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type1); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - for (Device device : loadedDevicesType2) { - doDelete("/api/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/device/", loadedDevicesType2, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4); pageData = doGetTypedWithPageLink("/api/tenant/devices?type={type}&", - new TypeReference>(){}, pageLink, type2); + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type2); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @@ -583,32 +605,35 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { customer = doPost("/api/customer", customer, Customer.class); CustomerId customerId = customer.getId(); - List devices = new ArrayList<>(); + futures = new ArrayList<>(128); for (int i = 0; i < 128; i++) { Device device = new Device(); device.setName("Device" + i); device.setType("default"); - device = doPost("/api/device", device, Device.class); - devices.add(doPost("/api/customer/" + customerId.getId().toString() - + "/device/" + device.getId().getId().toString(), Device.class)); + ListenableFuture future = executor.submit(() -> doPost("/api/device", device, Device.class)); + futures.add(Futures.transform(future, (dev) -> + doPost("/api/customer/" + customerId.getId() + + "/device/" + dev.getId().getId(), Device.class), MoreExecutors.directExecutor())); } - List loadedDevices = new ArrayList<>(); + List devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + + List loadedDevices = new ArrayList<>(128); PageLink pageLink = new PageLink(23); - PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?", - new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevices.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devices, idComparator); - Collections.sort(loadedDevices, idComparator); + assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices); - Assert.assertEquals(devices, loadedDevices); + log.debug("delete devices async"); + deleteEntitiesAsync("/api/customer/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("done"); } @Test @@ -619,7 +644,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { CustomerId customerId = customer.getId(); String title1 = "Device title 1"; - List devicesTitle1 = new ArrayList<>(); + futures = new ArrayList<>(125); for (int i = 0; i < 125; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -627,12 +652,15 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); - device = doPost("/api/device", device, Device.class); - devicesTitle1.add(doPost("/api/customer/" + customerId.getId().toString() - + "/device/" + device.getId().getId().toString(), Device.class)); + ListenableFuture future = executor.submit(() -> doPost("/api/device", device, Device.class)); + futures.add(Futures.transform(future, (dev) -> + doPost("/api/customer/" + customerId.getId() + + "/device/" + dev.getId().getId(), Device.class), MoreExecutors.directExecutor())); } + List devicesTitle1 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + String title2 = "Device title 2"; - List devicesTitle2 = new ArrayList<>(); + futures = new ArrayList<>(143); for (int i = 0; i < 143; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -640,61 +668,52 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType("default"); - device = doPost("/api/device", device, Device.class); - devicesTitle2.add(doPost("/api/customer/" + customerId.getId().toString() - + "/device/" + device.getId().getId().toString(), Device.class)); + ListenableFuture future = executor.submit(() -> doPost("/api/device", device, Device.class)); + futures.add(Futures.transform(future, (dev) -> + doPost("/api/customer/" + customerId.getId() + + "/device/" + dev.getId().getId(), Device.class), MoreExecutors.directExecutor())); } + List devicesTitle2 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); - List loadedDevicesTitle1 = new ArrayList<>(); + List loadedDevicesTitle1 = new ArrayList<>(125); PageLink pageLink = new PageLink(15, 0, title1); - PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?", - new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevicesTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesTitle1, idComparator); - Collections.sort(loadedDevicesTitle1, idComparator); + assertThat(devicesTitle1).as(title1).containsExactlyInAnyOrderElementsOf(loadedDevicesTitle1); - Assert.assertEquals(devicesTitle1, loadedDevicesTitle1); - - List loadedDevicesTitle2 = new ArrayList<>(); + List loadedDevicesTitle2 = new ArrayList<>(143); pageLink = new PageLink(4, 0, title2); do { - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?", - new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, pageLink); loadedDevicesTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesTitle2, idComparator); - Collections.sort(loadedDevicesTitle2, idComparator); + assertThat(devicesTitle2).as(title2).containsExactlyInAnyOrderElementsOf(loadedDevicesTitle2); - Assert.assertEquals(devicesTitle2, loadedDevicesTitle2); + deleteEntitiesAsync("/api/customer/device/", loadedDevicesTitle1, executor).get(TIMEOUT, TimeUnit.SECONDS); - for (Device device : loadedDevicesTitle1) { - doDelete("/api/customer/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } pageLink = new PageLink(4, 0, title1); - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?", - new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - for (Device device : loadedDevicesTitle2) { - doDelete("/api/customer/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/customer/device/", loadedDevicesTitle2, executor).get(TIMEOUT, TimeUnit.SECONDS); + pageLink = new PageLink(4, 0, title2); - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?", - new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @@ -708,7 +727,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { String title1 = "Device title 1"; String type1 = "typeC"; - List devicesType1 = new ArrayList<>(); + futures = new ArrayList<>(125); for (int i = 0; i < 125; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -716,13 +735,19 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type1); - device = doPost("/api/device", device, Device.class); - devicesType1.add(doPost("/api/customer/" + customerId.getId().toString() - + "/device/" + device.getId().getId().toString(), Device.class)); + ListenableFuture future = executor.submit(() -> doPost("/api/device", device, Device.class)); + futures.add(Futures.transform(future, (dev) -> + doPost("/api/customer/" + customerId.getId() + + "/device/" + dev.getId().getId(), Device.class), MoreExecutors.directExecutor())); + if (i == 0) { + futures.get(0).get(TIMEOUT, TimeUnit.SECONDS); // wait for the device profile created first time + } } + List devicesType1 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); + String title2 = "Device title 2"; String type2 = "typeD"; - List devicesType2 = new ArrayList<>(); + futures = new ArrayList<>(143); for (int i = 0; i < 143; i++) { Device device = new Device(); String suffix = RandomStringUtils.randomAlphanumeric(15); @@ -730,63 +755,55 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { name = i % 2 == 0 ? name.toLowerCase() : name.toUpperCase(); device.setName(name); device.setType(type2); - device = doPost("/api/device", device, Device.class); - devicesType2.add(doPost("/api/customer/" + customerId.getId().toString() - + "/device/" + device.getId().getId().toString(), Device.class)); + ListenableFuture future = executor.submit(() -> doPost("/api/device", device, Device.class)); + futures.add(Futures.transform(future, (dev) -> + doPost("/api/customer/" + customerId.getId() + + "/device/" + dev.getId().getId(), Device.class), MoreExecutors.directExecutor())); + if (i == 0) { + futures.get(0).get(TIMEOUT, TimeUnit.SECONDS); // wait for the device profile created first time + } } + List devicesType2 = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); - List loadedDevicesType1 = new ArrayList<>(); + List loadedDevicesType1 = new ArrayList<>(125); PageLink pageLink = new PageLink(15); - PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?type={type}&", - new TypeReference>(){}, pageLink, type1); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?type={type}&", + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type1); loadedDevicesType1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesType1, idComparator); - Collections.sort(loadedDevicesType1, idComparator); + assertThat(devicesType1).as(title1).containsExactlyInAnyOrderElementsOf(loadedDevicesType1); - Assert.assertEquals(devicesType1, loadedDevicesType1); - - List loadedDevicesType2 = new ArrayList<>(); + List loadedDevicesType2 = new ArrayList<>(143); pageLink = new PageLink(4); do { - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?type={type}&", - new TypeReference>(){}, pageLink, type2); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?type={type}&", + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type2); loadedDevicesType2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(devicesType2, idComparator); - Collections.sort(loadedDevicesType2, idComparator); - - Assert.assertEquals(devicesType2, loadedDevicesType2); + assertThat(devicesType2).as(title2).containsExactlyInAnyOrderElementsOf(loadedDevicesType2); - for (Device device : loadedDevicesType1) { - doDelete("/api/customer/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/customer/device/", loadedDevicesType1, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4); - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?type={type}&", - new TypeReference>(){}, pageLink, type1); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?type={type}&", + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type1); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - for (Device device : loadedDevicesType2) { - doDelete("/api/customer/device/" + device.getId().getId().toString()) - .andExpect(status().isOk()); - } + deleteEntitiesAsync("/api/customer/device/", loadedDevicesType2, executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(4); - pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/devices?type={type}&", - new TypeReference>(){}, pageLink, type2); + pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?type={type}&", + PAGE_DATA_DEVICE_TYPE_REF, pageLink, type2); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); } @@ -828,17 +845,17 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { login("tenant2@thingsboard.org", "testPassword1"); Device assignedDevice = doPost("/api/tenant/" + savedDifferentTenant.getId().getId() + "/device/" + savedDevice.getId().getId(), Device.class); - doGet("/api/device/" + assignedDevice.getId().getId().toString(), Device.class, status().isNotFound()); + doGet("/api/device/" + assignedDevice.getId().getId(), Device.class, status().isNotFound()); login("tenant9@thingsboard.org", "testPassword1"); - Device foundDevice1 = doGet("/api/device/" + assignedDevice.getId().getId().toString(), Device.class); + Device foundDevice1 = doGet("/api/device/" + assignedDevice.getId().getId(), Device.class); Assert.assertNotNull(foundDevice1); doGet("/api/relation?fromId=" + savedDevice.getId().getId() + "&fromType=DEVICE&relationType=Contains&toId=" + savedAnotherDevice.getId().getId() + "&toType=DEVICE", EntityRelation.class, status().isNotFound()); loginSysAdmin(); - doDelete("/api/tenant/" + savedDifferentTenant.getId().getId().toString()) + doDelete("/api/tenant/" + savedDifferentTenant.getId().getId()) .andExpect(status().isOk()); } @@ -852,19 +869,19 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest { device.setType("default"); Device savedDevice = doPost("/api/device", device, Device.class); - doPost("/api/edge/" + savedEdge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + doPost("/api/edge/" + savedEdge.getId().getId() + + "/device/" + savedDevice.getId().getId(), Device.class); - PageData pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/devices?", - new TypeReference>() {}, new PageLink(100)); + pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100)); Assert.assertEquals(1, pageData.getData().size()); - doDelete("/api/edge/" + savedEdge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + doDelete("/api/edge/" + savedEdge.getId().getId() + + "/device/" + savedDevice.getId().getId(), Device.class); - pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/devices?", - new TypeReference>() {}, new PageLink(100)); + pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?", + PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100)); Assert.assertEquals(0, pageData.getData().size()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseDeviceProfileControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseDeviceProfileControllerTest.java index d33a93cd64..143fdce0f3 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseDeviceProfileControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseDeviceProfileControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ import org.thingsboard.server.common.data.DeviceTransportType; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; +import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; @@ -93,7 +94,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testSaveDeviceProfile() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Assert.assertNotNull(savedDeviceProfile); Assert.assertNotNull(savedDeviceProfile.getId()); @@ -112,13 +113,13 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void saveDeviceProfileWithViolationOfValidation() throws Exception { - doPost("/api/deviceProfile", this.createDeviceProfile(RandomStringUtils.randomAlphabetic(300), null)) + doPost("/api/deviceProfile", this.createDeviceProfile(RandomStringUtils.randomAlphabetic(300))) .andExpect(statusReason(containsString("length of name must be equal or less than 255"))); } @Test public void testFindDeviceProfileById() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/"+savedDeviceProfile.getId().getId().toString(), DeviceProfile.class); Assert.assertNotNull(foundDeviceProfile); @@ -127,7 +128,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testFindDeviceProfileInfoById() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); DeviceProfileInfo foundDeviceProfileInfo = doGet("/api/deviceProfileInfo/"+savedDeviceProfile.getId().getId().toString(), DeviceProfileInfo.class); Assert.assertNotNull(foundDeviceProfileInfo); @@ -149,9 +150,9 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testSetDefaultDeviceProfile() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile 1", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile 1"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); - DeviceProfile defaultDeviceProfile = doPost("/api/deviceProfile/"+savedDeviceProfile.getId().getId().toString()+"/default", null, DeviceProfile.class); + DeviceProfile defaultDeviceProfile = doPost("/api/deviceProfile/"+savedDeviceProfile.getId().getId().toString()+"/default", DeviceProfile.class); Assert.assertNotNull(defaultDeviceProfile); DeviceProfileInfo foundDefaultDeviceProfile = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); Assert.assertNotNull(foundDefaultDeviceProfile); @@ -169,19 +170,19 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testSaveDeviceProfileWithSameName() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); doPost("/api/deviceProfile", deviceProfile).andExpect(status().isOk()); - DeviceProfile deviceProfile2 = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile2 = this.createDeviceProfile("Device Profile"); doPost("/api/deviceProfile", deviceProfile2).andExpect(status().isBadRequest()) .andExpect(statusReason(containsString("Device profile with such name already exists"))); } @Test public void testSaveDeviceProfileWithSameProvisionDeviceKey() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); deviceProfile.setProvisionDeviceKey("testProvisionDeviceKey"); doPost("/api/deviceProfile", deviceProfile).andExpect(status().isOk()); - DeviceProfile deviceProfile2 = this.createDeviceProfile("Device Profile 2", null); + DeviceProfile deviceProfile2 = this.createDeviceProfile("Device Profile 2"); deviceProfile2.setProvisionDeviceKey("testProvisionDeviceKey"); doPost("/api/deviceProfile", deviceProfile2).andExpect(status().isBadRequest()) .andExpect(statusReason(containsString("Device profile with such provision device key already exists"))); @@ -190,7 +191,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Ignore @Test public void testChangeDeviceProfileTypeWithExistingDevices() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Device device = new Device(); device.setName("Test device"); @@ -205,7 +206,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testChangeDeviceProfileTransportTypeWithExistingDevices() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Device device = new Device(); device.setName("Test device"); @@ -219,7 +220,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testDeleteDeviceProfileWithExistingDevice() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Device device = new Device(); @@ -236,7 +237,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController @Test public void testDeleteDeviceProfile() throws Exception { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); doDelete("/api/deviceProfile/" + savedDeviceProfile.getId().getId().toString()) @@ -257,7 +258,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController deviceProfiles.addAll(pageData.getData()); for (int i=0;i<28;i++) { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"+i, null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"+i); deviceProfiles.add(doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class)); } @@ -302,7 +303,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController deviceProfiles.addAll(deviceProfilePageData.getData()); for (int i=0;i<28;i++) { - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"+i, null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"+i); deviceProfiles.add(doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class)); } @@ -835,19 +836,35 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController "}", "[Transport Configuration] invalid rpc request proto schema provided! Failed to get field descriptor for field: params!"); } + @Test + public void testSaveDeviceProfileWithSendAckOnValidationException() throws Exception { + JsonTransportPayloadConfiguration jsonTransportPayloadConfiguration = new JsonTransportPayloadConfiguration(); + MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(jsonTransportPayloadConfiguration, true); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", mqttDeviceProfileTransportConfiguration); + DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); + Assert.assertNotNull(savedDeviceProfile); + Assert.assertEquals(savedDeviceProfile.getTransportType(), DeviceTransportType.MQTT); + Assert.assertTrue(savedDeviceProfile.getProfileData().getTransportConfiguration() instanceof MqttDeviceProfileTransportConfiguration); + MqttDeviceProfileTransportConfiguration transportConfiguration = (MqttDeviceProfileTransportConfiguration) savedDeviceProfile.getProfileData().getTransportConfiguration(); + Assert.assertTrue(transportConfiguration.isSendAckOnValidationException()); + DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/"+ savedDeviceProfile.getId().getId().toString(), DeviceProfile.class); + Assert.assertEquals(savedDeviceProfile, foundDeviceProfile); + } + private DeviceProfile testSaveDeviceProfileWithProtoPayloadType(String schema) throws Exception { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = this.createProtoTransportPayloadConfiguration(schema, schema, null, null); - MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration); + MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration, false); DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", mqttDeviceProfileTransportConfiguration); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); - DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/"+savedDeviceProfile.getId().getId().toString(), DeviceProfile.class); - Assert.assertEquals(savedDeviceProfile.getName(), foundDeviceProfile.getName()); + Assert.assertNotNull(savedDeviceProfile); + DeviceProfile foundDeviceProfile = doGet("/api/deviceProfile/"+ savedDeviceProfile.getId().getId().toString(), DeviceProfile.class); + Assert.assertEquals(savedDeviceProfile, foundDeviceProfile); return savedDeviceProfile; } private void testSaveDeviceProfileWithInvalidProtoSchema(String schema, String errorMsg) throws Exception { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = this.createProtoTransportPayloadConfiguration(schema, schema, null, null); - MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration); + MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration, false); DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", mqttDeviceProfileTransportConfiguration); doPost("/api/deviceProfile", deviceProfile).andExpect(status().isBadRequest()) .andExpect(statusReason(containsString(errorMsg))); @@ -855,7 +872,7 @@ public abstract class BaseDeviceProfileControllerTest extends AbstractController private void testSaveDeviceProfileWithInvalidRpcRequestProtoSchema(String schema, String errorMsg) throws Exception { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = this.createProtoTransportPayloadConfiguration(schema, schema, schema, null); - MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration); + MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = this.createMqttDeviceProfileTransportConfiguration(protoTransportPayloadConfiguration, false); DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", mqttDeviceProfileTransportConfiguration); doPost("/api/deviceProfile", deviceProfile).andExpect(status().isBadRequest()) .andExpect(statusReason(containsString(errorMsg))); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseEdgeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseEdgeControllerTest.java index 326d1465c1..24b2053c67 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseEdgeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseEdgeControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntitySubtype; @@ -54,6 +55,9 @@ import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID; +@TestPropertySource(properties = { + "edges.enabled=true", +}) public abstract class BaseEdgeControllerTest extends AbstractControllerTest { public static final String EDGE_HOST = "localhost"; @@ -105,8 +109,6 @@ public abstract class BaseEdgeControllerTest extends AbstractControllerTest { Assert.assertNotNull(savedEdge.getCustomerId()); Assert.assertEquals(NULL_UUID, savedEdge.getCustomerId().getId()); Assert.assertEquals(edge.getName(), savedEdge.getName()); - Assert.assertTrue(StringUtils.isNoneBlank(savedEdge.getEdgeLicenseKey())); - Assert.assertTrue(StringUtils.isNoneBlank(savedEdge.getCloudEndpoint())); savedEdge.setName("My new edge"); doPost("/api/edge", savedEdge, Edge.class); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseEdgeEventControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseEdgeEventControllerTest.java index e462b041b2..ef66270130 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseEdgeEventControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseEdgeEventControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; @@ -40,6 +41,9 @@ import java.util.concurrent.TimeUnit; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@TestPropertySource(properties = { + "edges.enabled=true", +}) @Slf4j public abstract class BaseEdgeEventControllerTest extends AbstractControllerTest { diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseEntityQueryControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseEntityQueryControllerTest.java index b2fe4a563b..8c692ef8a2 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseEntityQueryControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseEntityQueryControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,13 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityType; @@ -29,6 +32,8 @@ import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.query.DeviceTypeFilter; +import org.thingsboard.server.common.data.query.DynamicValue; +import org.thingsboard.server.common.data.query.DynamicValueSourceType; import org.thingsboard.server.common.data.query.EntityCountQuery; import org.thingsboard.server.common.data.query.EntityData; import org.thingsboard.server.common.data.query.EntityDataPageLink; @@ -41,11 +46,13 @@ import org.thingsboard.server.common.data.query.EntityTypeFilter; import org.thingsboard.server.common.data.query.FilterPredicateValue; import org.thingsboard.server.common.data.query.KeyFilter; import org.thingsboard.server.common.data.query.NumericFilterPredicate; +import org.thingsboard.server.common.data.query.TsValue; import org.thingsboard.server.common.data.security.Authority; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -299,6 +306,79 @@ public abstract class BaseEntityQueryControllerTest extends AbstractControllerTe List deviceHighTemperatures = highTemperatures.stream().map(aLong -> Long.toString(aLong)).collect(Collectors.toList()); Assert.assertEquals(deviceHighTemperatures, loadedHighTemperatures); + } + + @Test + public void testFindEntityDataByQueryWithDynamicValue() throws Exception { + int numOfDevices = 2; + + for (int i = 0; i < numOfDevices; i++) { + Device device = new Device(); + String name = "Device" + i; + device.setName(name); + device.setType("default"); + device.setLabel("testLabel" + (int) (Math.random() * 1000)); + + Device savedDevice1 = doPost("/api/device?accessToken=" + name, device, Device.class); + JsonNode content = JacksonUtil.toJsonNode("{\"alarmActiveTime\": 1" + i + "}"); + doPost("/api/plugins/telemetry/" + EntityType.DEVICE.name() + "/" + savedDevice1.getUuidId() + "/SERVER_SCOPE", content) + .andExpect(status().isOk()); + } + JsonNode content = JacksonUtil.toJsonNode("{\"dynamicValue\": 0}"); + doPost("/api/plugins/telemetry/" + EntityType.TENANT.name() + "/" + tenantId.getId() + "/SERVER_SCOPE", content) + .andExpect(status().isOk()); + + + DeviceTypeFilter filter = new DeviceTypeFilter(); + filter.setDeviceType("default"); + filter.setDeviceNameFilter(""); + + KeyFilter highTemperatureFilter = new KeyFilter(); + highTemperatureFilter.setKey(new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "alarmActiveTime")); + NumericFilterPredicate predicate = new NumericFilterPredicate(); + + DynamicValue dynamicValue = + new DynamicValue<>(DynamicValueSourceType.CURRENT_TENANT, "dynamicValue"); + FilterPredicateValue predicateValue = new FilterPredicateValue<>(0.0, null, dynamicValue); + predicate.setValue(predicateValue); + predicate.setOperation(NumericFilterPredicate.NumericOperation.GREATER); + highTemperatureFilter.setPredicate(predicate); + + List keyFilters = Collections.singletonList(highTemperatureFilter); + + + EntityDataSortOrder sortOrder = new EntityDataSortOrder( + new EntityKey(EntityKeyType.ENTITY_FIELD, "createdTime"), EntityDataSortOrder.Direction.ASC + ); + EntityDataPageLink pageLink = new EntityDataPageLink(10, 0, null, sortOrder); + + List entityFields = Collections.singletonList(new EntityKey(EntityKeyType.ENTITY_FIELD, "name")); + List latestValues = Collections.singletonList(new EntityKey(EntityKeyType.ATTRIBUTE, "alarmActiveTime")); + + EntityDataQuery query = new EntityDataQuery(filter, pageLink, entityFields, latestValues, keyFilters); + + Awaitility.await() + .alias("data by query") + .atMost(30, TimeUnit.SECONDS) + .until(() -> { + var data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference>() {}); + var loadedEntities = new ArrayList<>(data.getData()); + return loadedEntities.size() == numOfDevices; + }); + + var data = doPostWithTypedResponse("/api/entitiesQuery/find", query, new TypeReference>() {}); + var loadedEntities = new ArrayList<>(data.getData()); + + Assert.assertEquals(numOfDevices, loadedEntities.size()); + + for (int i = 0; i < numOfDevices; i++) { + var entity = loadedEntities.get(i); + String name = entity.getLatest().get(EntityKeyType.ENTITY_FIELD).getOrDefault("name", new TsValue(0, "Invalid")).getValue(); + String alarmActiveTime = entity.getLatest().get(EntityKeyType.ATTRIBUTE).getOrDefault("alarmActiveTime", new TsValue(0, "-1")).getValue(); + + Assert.assertEquals("Device" + i, name); + Assert.assertEquals("1" + i, alarmActiveTime); + } } } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseEntityViewControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseEntityViewControllerTest.java index 304964dfa8..615914c6d7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseEntityViewControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseEntityViewControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,13 @@ package org.thingsboard.server.controller; import com.datastax.oss.driver.api.core.uuid.Uuids; import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttMessage; @@ -27,6 +32,9 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.web.servlet.ResultActions; +import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.EntityView; @@ -39,70 +47,72 @@ import org.thingsboard.server.common.data.objects.AttributesEntityView; import org.thingsboard.server.common.data.objects.TelemetryEntityView; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.query.DeviceTypeFilter; +import org.thingsboard.server.common.data.query.EntityKey; +import org.thingsboard.server.common.data.query.EntityKeyType; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.dao.model.ModelConstants; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import static java.util.concurrent.TimeUnit.HOURS; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID; +@TestPropertySource(properties = { + "transport.mqtt.enabled=true", + "js.evaluator=mock", +}) @Slf4j public abstract class BaseEntityViewControllerTest extends AbstractControllerTest { + static final TypeReference> PAGE_DATA_ENTITY_VIEW_TYPE_REF = new TypeReference<>() { + }; + static final TypeReference> PAGE_DATA_ENTITY_VIEW_INFO_TYPE_REF = new TypeReference<>() { + }; - private IdComparator idComparator; - private Tenant savedTenant; - private User tenantAdmin; private Device testDevice; private TelemetryEntityView telemetry; + List> deleteFutures = new ArrayList<>(); + ListeningExecutorService executor; + @Before public void beforeTest() throws Exception { - loginSysAdmin(); - idComparator = new IdComparator<>(); + log.debug("beforeTest"); + executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass())); - savedTenant = doPost("/api/tenant", getNewTenant("My tenant"), Tenant.class); - Assert.assertNotNull(savedTenant); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant2@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); - tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); + loginTenantAdmin(); Device device = new Device(); - device.setName("Test device"); + device.setName("Test device 4view"); device.setType("default"); testDevice = doPost("/api/device", device, Device.class); telemetry = new TelemetryEntityView( - Arrays.asList("tsKey1", "tsKey2", "tsKey3"), + List.of("tsKey1", "tsKey2", "tsKey3"), new AttributesEntityView( - Arrays.asList("caKey1", "caKey2", "caKey3", "caKey4"), - Arrays.asList("saKey1", "saKey2", "saKey3", "saKey4"), - Arrays.asList("shKey1", "shKey2", "shKey3", "shKey4"))); + List.of("caKey1", "caKey2", "caKey3", "caKey4"), + List.of("saKey1", "saKey2", "saKey3", "saKey4"), + List.of("shKey1", "shKey2", "shKey3", "shKey4"))); } @After public void afterTest() throws Exception { - loginSysAdmin(); - - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) - .andExpect(status().isOk()); + executor.shutdownNow(); } @Test @@ -115,22 +125,29 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes @Test public void testSaveEntityView() throws Exception { - EntityView savedView = getNewSavedEntityView("Test entity view"); + String name = "Test entity view"; + EntityView savedView = getNewSavedEntityView(name); Assert.assertNotNull(savedView); Assert.assertNotNull(savedView.getId()); Assert.assertTrue(savedView.getCreatedTime() > 0); - assertEquals(savedTenant.getId(), savedView.getTenantId()); + assertEquals(tenantId, savedView.getTenantId()); Assert.assertNotNull(savedView.getCustomerId()); assertEquals(NULL_UUID, savedView.getCustomerId().getId()); - assertEquals(savedView.getName(), savedView.getName()); + assertEquals(name, savedView.getName()); + + EntityView foundEntityView = doGet("/api/entityView/" + savedView.getId().getId().toString(), EntityView.class); + + assertEquals(savedView, foundEntityView); savedView.setName("New test entity view"); + doPost("/api/entityView", savedView, EntityView.class); - EntityView foundEntityView = doGet("/api/entityView/" + savedView.getId().getId().toString(), EntityView.class); + foundEntityView = doGet("/api/entityView/" + savedView.getId().getId().toString(), EntityView.class); - assertEquals(foundEntityView.getName(), savedView.getName()); - assertEquals(foundEntityView.getKeys(), telemetry); + assertEquals(savedView, foundEntityView); + + doGet("/api/tenant/entityViews?entityViewName=" + name, EntityView.class, status().isNotFound()); } @Test @@ -221,7 +238,7 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes Customer customer = getNewCustomer("Different customer"); Customer savedCustomer = doPost("/api/customer", customer, Customer.class); - login(tenantAdmin.getEmail(), "testPassword1"); + login(TENANT_ADMIN_EMAIL, TENANT_ADMIN_PASSWORD); EntityView savedView = getNewSavedEntityView("Test entity view"); @@ -240,21 +257,18 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes CustomerId customerId = customer.getId(); String urlTemplate = "/api/customer/" + customerId.getId().toString() + "/entityViewInfos?"; - List views = new ArrayList<>(); + List> viewFutures = new ArrayList<>(128); for (int i = 0; i < 128; i++) { - views.add( + String entityName = "Test entity view " + i; + viewFutures.add(executor.submit(() -> new EntityViewInfo(doPost("/api/customer/" + customerId.getId().toString() + "/entityView/" - + getNewSavedEntityView("Test entity view " + i).getId().getId().toString(), EntityView.class), - customer.getTitle(), customer.isPublic()) - ); + + getNewSavedEntityView(entityName).getId().getId().toString(), EntityView.class), + customer.getTitle(), customer.isPublic()))); } - + List entityViewInfos = Futures.allAsList(viewFutures).get(TIMEOUT, SECONDS); List loadedViews = loadListOfInfo(new PageLink(23), urlTemplate); - Collections.sort(views, idComparator); - Collections.sort(loadedViews, idComparator); - - assertEquals(views, loadedViews); + assertThat(entityViewInfos).containsExactlyInAnyOrderElementsOf(loadedViews); } @Test @@ -263,35 +277,37 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes String urlTemplate = "/api/customer/" + customerId.getId().toString() + "/entityViews?"; String name1 = "Entity view name1"; - List namesOfView1 = fillListOf(125, name1, "/api/customer/" + customerId.getId().toString() - + "/entityView/"); + List namesOfView1 = Futures.allAsList(fillListByTemplate(125, name1, "/api/customer/" + customerId.getId().toString() + + "/entityView/")).get(TIMEOUT, SECONDS); List loadedNamesOfView1 = loadListOf(new PageLink(15, 0, name1), urlTemplate); - Collections.sort(namesOfView1, idComparator); - Collections.sort(loadedNamesOfView1, idComparator); - assertEquals(namesOfView1, loadedNamesOfView1); + assertThat(namesOfView1).as(name1).containsExactlyInAnyOrderElementsOf(loadedNamesOfView1); String name2 = "Entity view name2"; - List NamesOfView2 = fillListOf(143, name2, "/api/customer/" + customerId.getId().toString() - + "/entityView/"); + List namesOfView2 = Futures.allAsList(fillListByTemplate(143, name2, "/api/customer/" + customerId.getId().toString() + + "/entityView/")).get(TIMEOUT, SECONDS); List loadedNamesOfView2 = loadListOf(new PageLink(4, 0, name2), urlTemplate); - Collections.sort(NamesOfView2, idComparator); - Collections.sort(loadedNamesOfView2, idComparator); - assertEquals(NamesOfView2, loadedNamesOfView2); + assertThat(namesOfView2).as(name2).containsExactlyInAnyOrderElementsOf(loadedNamesOfView2); + deleteFutures.clear(); for (EntityView view : loadedNamesOfView1) { - doDelete("/api/customer/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()); + deleteFutures.add(executor.submit(() -> + doDelete("/api/customer/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()))); } - PageData pageData = doGetTypedWithPageLink(urlTemplate, - new TypeReference>() { - }, new PageLink(4, 0, name1)); + Futures.allAsList(deleteFutures).get(TIMEOUT, SECONDS); + + PageData pageData = doGetTypedWithPageLink(urlTemplate, PAGE_DATA_ENTITY_VIEW_TYPE_REF, + new PageLink(4, 0, name1)); Assert.assertFalse(pageData.hasNext()); assertEquals(0, pageData.getData().size()); + deleteFutures.clear(); for (EntityView view : loadedNamesOfView2) { - doDelete("/api/customer/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()); + deleteFutures.add(executor.submit(() -> + doDelete("/api/customer/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()))); } - pageData = doGetTypedWithPageLink(urlTemplate, new TypeReference>() { - }, + Futures.allAsList(deleteFutures).get(TIMEOUT, SECONDS); + + pageData = doGetTypedWithPageLink(urlTemplate, PAGE_DATA_ENTITY_VIEW_TYPE_REF, new PageLink(4, 0, name2)); Assert.assertFalse(pageData.hasNext()); assertEquals(0, pageData.getData().size()); @@ -299,49 +315,51 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes @Test public void testGetTenantEntityViews() throws Exception { - - List views = new ArrayList<>(); + List> entityViewInfoFutures = new ArrayList<>(178); for (int i = 0; i < 178; i++) { - views.add(new EntityViewInfo(getNewSavedEntityView("Test entity view" + i), null, false)); + ListenableFuture entityViewFuture = getNewSavedEntityViewAsync("Test entity view" + i); + entityViewInfoFutures.add(Futures.transform(entityViewFuture, + view -> new EntityViewInfo(view, null, false), + MoreExecutors.directExecutor())); } + List entityViewInfos = Futures.allAsList(entityViewInfoFutures).get(TIMEOUT, SECONDS); List loadedViews = loadListOfInfo(new PageLink(23), "/api/tenant/entityViewInfos?"); - - Collections.sort(views, idComparator); - Collections.sort(loadedViews, idComparator); - - assertEquals(views, loadedViews); + assertThat(entityViewInfos).containsExactlyInAnyOrderElementsOf(loadedViews); } @Test public void testGetTenantEntityViewsByName() throws Exception { String name1 = "Entity view name1"; - List namesOfView1 = fillListOf(143, name1); - List loadedNamesOfView1 = loadListOf(new PageLink(15, 0, name1), "/api/tenant/entityViews?"); - Collections.sort(namesOfView1, idComparator); - Collections.sort(loadedNamesOfView1, idComparator); - assertEquals(namesOfView1, loadedNamesOfView1); + List namesOfView1 = Futures.allAsList(fillListOf(17, name1)).get(TIMEOUT, SECONDS); + List loadedNamesOfView1 = loadListOf(new PageLink(5, 0, name1), "/api/tenant/entityViews?"); + assertThat(namesOfView1).as(name1).containsExactlyInAnyOrderElementsOf(loadedNamesOfView1); String name2 = "Entity view name2"; - List NamesOfView2 = fillListOf(75, name2); + List namesOfView2 = Futures.allAsList(fillListOf(15, name2)).get(TIMEOUT, SECONDS); + ; List loadedNamesOfView2 = loadListOf(new PageLink(4, 0, name2), "/api/tenant/entityViews?"); - Collections.sort(NamesOfView2, idComparator); - Collections.sort(loadedNamesOfView2, idComparator); - assertEquals(NamesOfView2, loadedNamesOfView2); + assertThat(namesOfView2).as(name2).containsExactlyInAnyOrderElementsOf(loadedNamesOfView2); + deleteFutures.clear(); for (EntityView view : loadedNamesOfView1) { - doDelete("/api/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()); + deleteFutures.add(executor.submit(() -> + doDelete("/api/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()))); } - PageData pageData = doGetTypedWithPageLink("/api/tenant/entityViews?", - new TypeReference>() { - }, new PageLink(4, 0, name1)); + Futures.allAsList(deleteFutures).get(TIMEOUT, SECONDS); + + PageData pageData = doGetTypedWithPageLink("/api/tenant/entityViews?", PAGE_DATA_ENTITY_VIEW_TYPE_REF, + new PageLink(4, 0, name1)); Assert.assertFalse(pageData.hasNext()); assertEquals(0, pageData.getData().size()); + deleteFutures.clear(); for (EntityView view : loadedNamesOfView2) { - doDelete("/api/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()); + deleteFutures.add(executor.submit(() -> + doDelete("/api/entityView/" + view.getId().getId().toString()).andExpect(status().isOk()))); } - pageData = doGetTypedWithPageLink("/api/tenant/entityViews?", new TypeReference>() { - }, + Futures.allAsList(deleteFutures).get(TIMEOUT, SECONDS); + + pageData = doGetTypedWithPageLink("/api/tenant/entityViews?", PAGE_DATA_ENTITY_VIEW_TYPE_REF, new PageLink(4, 0, name2)); Assert.assertFalse(pageData.hasNext()); assertEquals(0, pageData.getData().size()); @@ -349,20 +367,21 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes @Test public void testTheCopyOfAttrsIntoTSForTheView() throws Exception { + Set expectedActualAttributesSet = Set.of("caKey1", "caKey2", "caKey3", "caKey4"); Set actualAttributesSet = - getAttributesByKeys("{\"caKey1\":\"value1\", \"caKey2\":true, \"caKey3\":42.0, \"caKey4\":73}"); - - Set expectedActualAttributesSet = - new HashSet<>(Arrays.asList("caKey1", "caKey2", "caKey3", "caKey4")); - assertTrue(actualAttributesSet.containsAll(expectedActualAttributesSet)); - + putAttributesAndWait("{\"caKey1\":\"value1\", \"caKey2\":true, \"caKey3\":42.0, \"caKey4\":73}", expectedActualAttributesSet); + log.debug("got correct actualAttributesSet, saving new entity view..."); EntityView savedView = getNewSavedEntityView("Test entity view"); - Thread.sleep(1000); - - List> values = doGetAsyncTyped("/api/plugins/telemetry/ENTITY_VIEW/" + savedView.getId().getId().toString() + - "/values/attributes?keys=" + String.join(",", actualAttributesSet), new TypeReference<>() {}); + log.debug("fetching entity view telemetry..."); + List> values = await("telemetry/ENTITY_VIEW") + .atMost(TIMEOUT, SECONDS) + .until(() -> doGetAsyncTyped("/api/plugins/telemetry/ENTITY_VIEW/" + savedView.getId().getId().toString() + + "/values/attributes?keys=" + String.join(",", actualAttributesSet), new TypeReference<>() { + }), + x -> x.size() >= expectedActualAttributesSet.size()); + log.debug("asserting..."); assertEquals("value1", getValue(values, "caKey1")); assertEquals(true, getValue(values, "caKey2")); assertEquals(42.0, getValue(values, "caKey3")); @@ -371,71 +390,97 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes @Test public void testTheCopyOfAttrsOutOfTSForTheView() throws Exception { + long now = System.currentTimeMillis(); + Set expectedActualAttributesSet = Set.of("caKey1", "caKey2", "caKey3", "caKey4"); Set actualAttributesSet = - getAttributesByKeys("{\"caKey1\":\"value1\", \"caKey2\":true, \"caKey3\":42.0, \"caKey4\":73}"); - - Set expectedActualAttributesSet = new HashSet<>(Arrays.asList("caKey1", "caKey2", "caKey3", "caKey4")); - assertTrue(actualAttributesSet.containsAll(expectedActualAttributesSet)); + putAttributesAndWait("{\"caKey1\":\"value1\", \"caKey2\":true, \"caKey3\":42.0, \"caKey4\":73}", expectedActualAttributesSet); - List> valueTelemetryOfDevices = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + testDevice.getId().getId().toString() + - "/values/attributes?keys=" + String.join(",", actualAttributesSet), new TypeReference<>() {}); + List> values = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + testDevice.getId() + + "/values/attributes?keys=" + String.join(",", expectedActualAttributesSet), new TypeReference<>() { + }); + assertEquals(expectedActualAttributesSet.size(), values.size()); EntityView view = new EntityView(); view.setEntityId(testDevice.getId()); - view.setTenantId(savedTenant.getId()); + view.setTenantId(tenantId); view.setName("Test entity view"); view.setType("default"); view.setKeys(telemetry); - view.setStartTimeMs((long) getValue(valueTelemetryOfDevices, "lastActivityTime") * 10); - view.setEndTimeMs((long) getValue(valueTelemetryOfDevices, "lastActivityTime") / 10); + view.setStartTimeMs(now - HOURS.toMillis(1)); + view.setEndTimeMs(now - 1); EntityView savedView = doPost("/api/entityView", view, EntityView.class); - Thread.sleep(1000); - - List> values = doGetAsyncTyped("/api/plugins/telemetry/ENTITY_VIEW/" + savedView.getId().getId().toString() + - "/values/attributes?keys=" + String.join(",", actualAttributesSet), new TypeReference<>() {}); + values = doGetAsyncTyped("/api/plugins/telemetry/ENTITY_VIEW/" + savedView.getId().getId().toString() + + "/values/attributes?keys=" + String.join(",", expectedActualAttributesSet), new TypeReference<>() { + }); assertEquals(0, values.size()); } @Test public void testGetTelemetryWhenEntityViewTimeRangeInsideTimestampRange() throws Exception { - uploadTelemetry("{\"tsKey1\":\"value1\", \"tsKey2\":true, \"tsKey3\":40.0}"); - Thread.sleep(1000); - long startTimeMs = System.currentTimeMillis(); - uploadTelemetry("{\"tsKey1\":\"value2\", \"tsKey2\":false, \"tsKey3\":80.0}"); - Thread.sleep(1000); - uploadTelemetry("{\"tsKey1\":\"value3\", \"tsKey2\":false, \"tsKey3\":120.0}"); - long endTimeMs = System.currentTimeMillis(); - uploadTelemetry("{\"tsKey1\":\"value4\", \"tsKey2\":true, \"tsKey3\":160.0}"); + DeviceTypeFilter dtf = new DeviceTypeFilter(testDevice.getType(), testDevice.getName()); + List tsKeys = List.of("tsKey1", "tsKey2", "tsKey3"); + + DeviceCredentials deviceCredentials = doGet("/api/device/" + testDevice.getId().getId() + "/credentials", DeviceCredentials.class); + assertEquals(testDevice.getId(), deviceCredentials.getDeviceId()); + String accessToken = deviceCredentials.getCredentialsId(); + assertNotNull(accessToken); + + long now = System.currentTimeMillis(); + getWsClient().subscribeTsUpdate(tsKeys, now, TimeUnit.HOURS.toMillis(1), dtf); + + getWsClient().registerWaitForUpdate(); + uploadTelemetry("{\"tsKey1\":\"value1\", \"tsKey2\":true, \"tsKey3\":40.0}", accessToken); + getWsClient().waitForUpdate(); + + long startTimeMs = getCurTsButNotPrevTs(now); + + getWsClient().registerWaitForUpdate(); + uploadTelemetry("{\"tsKey1\":\"value2\", \"tsKey2\":false, \"tsKey3\":80.0}", accessToken); + getWsClient().waitForUpdate(); + + long middleOfTestMs = getCurTsButNotPrevTs(startTimeMs); + + getWsClient().registerWaitForUpdate(); + uploadTelemetry("{\"tsKey1\":\"value3\", \"tsKey2\":false, \"tsKey3\":120.0}", accessToken); + getWsClient().waitForUpdate(); + + long endTimeMs = getCurTsButNotPrevTs(middleOfTestMs); + getWsClient().registerWaitForUpdate(); + uploadTelemetry("{\"tsKey1\":\"value4\", \"tsKey2\":true, \"tsKey3\":160.0}", accessToken); + getWsClient().waitForUpdate(); String deviceId = testDevice.getId().getId().toString(); Set keys = getTelemetryKeys("DEVICE", deviceId); - Thread.sleep(1000); EntityView view = createEntityView("Test entity view", startTimeMs, endTimeMs); EntityView savedView = doPost("/api/entityView", view, EntityView.class); String entityViewId = savedView.getId().getId().toString(); - Map>> expectedValues = getTelemetryValues("DEVICE", deviceId, keys, 0L, (startTimeMs + endTimeMs) / 2); - Assert.assertEquals(2, expectedValues.get("tsKey1").size()); - Assert.assertEquals(2, expectedValues.get("tsKey2").size()); - Assert.assertEquals(2, expectedValues.get("tsKey3").size()); + Map>> actualDeviceValues = getTelemetryValues("DEVICE", deviceId, keys, 0L, middleOfTestMs); + Assert.assertEquals(2, actualDeviceValues.get("tsKey1").size()); + Assert.assertEquals(2, actualDeviceValues.get("tsKey2").size()); + Assert.assertEquals(2, actualDeviceValues.get("tsKey3").size()); - Map>> actualValues = getTelemetryValues("ENTITY_VIEW", entityViewId, keys, 0L, (startTimeMs + endTimeMs) / 2); - Assert.assertEquals(1, actualValues.get("tsKey1").size()); - Assert.assertEquals(1, actualValues.get("tsKey2").size()); - Assert.assertEquals(1, actualValues.get("tsKey3").size()); + Map>> actualEntityViewValues = getTelemetryValues("ENTITY_VIEW", entityViewId, keys, 0L, middleOfTestMs); + Assert.assertEquals(1, actualEntityViewValues.get("tsKey1").size()); + Assert.assertEquals(1, actualEntityViewValues.get("tsKey2").size()); + Assert.assertEquals(1, actualEntityViewValues.get("tsKey3").size()); } - private void uploadTelemetry(String strKvs) throws Exception { - String viewDeviceId = testDevice.getId().getId().toString(); - DeviceCredentials deviceCredentials = - doGet("/api/device/" + viewDeviceId + "/credentials", DeviceCredentials.class); - assertEquals(testDevice.getId(), deviceCredentials.getDeviceId()); + private static long getCurTsButNotPrevTs(long prevTs) throws InterruptedException { + long result = System.currentTimeMillis(); + if (prevTs == result) { + Thread.sleep(1); + return getCurTsButNotPrevTs(prevTs); + } else { + return result; + } + } - String accessToken = deviceCredentials.getCredentialsId(); - assertNotNull(accessToken); + private void uploadTelemetry(String strKvs, String accessToken) throws Exception { + String viewDeviceId = testDevice.getId().getId().toString(); String clientId = MqttAsyncClient.generateClientId(); MqttAsyncClient client = new MqttAsyncClient("tcp://localhost:1883", clientId, new MemoryPersistence()); @@ -443,35 +488,45 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(accessToken); client.connect(options); - awaitConnected(client, TimeUnit.SECONDS.toMillis(30)); + awaitConnected(client, SECONDS.toMillis(30)); MqttMessage message = new MqttMessage(); message.setPayload(strKvs.getBytes()); - client.publish("v1/devices/me/telemetry", message); - Thread.sleep(1000); + IMqttDeliveryToken token = client.publish("v1/devices/me/telemetry", message); + await("mqtt ack").pollInterval(5, MILLISECONDS).atMost(TIMEOUT, SECONDS).until(() -> token.getMessage() == null); client.disconnect(); } private void awaitConnected(MqttAsyncClient client, long ms) throws InterruptedException { - long start = System.currentTimeMillis(); - while (!client.isConnected()) { - Thread.sleep(100); - if (start + ms < System.currentTimeMillis()) { - throw new RuntimeException("Client is not connected!"); - } - } + await("awaitConnected").pollInterval(5, MILLISECONDS).atMost(TIMEOUT, SECONDS) + .until(client::isConnected); } private Set getTelemetryKeys(String type, String id) throws Exception { - return new HashSet<>(doGetAsyncTyped("/api/plugins/telemetry/" + type + "/" + id + "/keys/timeseries", new TypeReference<>() {})); + return new HashSet<>(doGetAsyncTyped("/api/plugins/telemetry/" + type + "/" + id + "/keys/timeseries", new TypeReference<>() { + })); + } + + private Set getAttributeKeys(String type, String id) throws Exception { + return new HashSet<>(doGetAsyncTyped("/api/plugins/telemetry/" + type + "/" + id + "/keys/attributes", new TypeReference<>() { + })); } private Map>> getTelemetryValues(String type, String id, Set keys, Long startTs, Long endTs) throws Exception { return doGetAsyncTyped("/api/plugins/telemetry/" + type + "/" + id + - "/values/timeseries?keys=" + String.join(",", keys) + "&startTs=" + startTs + "&endTs=" + endTs, new TypeReference<>() {}); + "/values/timeseries?keys=" + String.join(",", keys) + "&startTs=" + startTs + "&endTs=" + endTs, new TypeReference<>() { + }); } - private Set getAttributesByKeys(String stringKV) throws Exception { + private Set putAttributesAndWait(String stringKV, Set expectedKeySet) throws Exception { + DeviceTypeFilter dtf = new DeviceTypeFilter(testDevice.getType(), testDevice.getName()); + List keysToSubscribe = expectedKeySet.stream() + .map(key -> new EntityKey(EntityKeyType.CLIENT_ATTRIBUTE, key)) + .collect(Collectors.toList()); + + getWsClient().subscribeLatestUpdate(keysToSubscribe, dtf); + String viewDeviceId = testDevice.getId().getId().toString(); + log.debug("deviceid {}", viewDeviceId); DeviceCredentials deviceCredentials = doGet("/api/device/" + viewDeviceId + "/credentials", DeviceCredentials.class); assertEquals(testDevice.getId(), deviceCredentials.getDeviceId()); @@ -479,20 +534,24 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes String accessToken = deviceCredentials.getCredentialsId(); assertNotNull(accessToken); + log.debug("creating mqtt client..."); String clientId = MqttAsyncClient.generateClientId(); MqttAsyncClient client = new MqttAsyncClient("tcp://localhost:1883", clientId, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(accessToken); client.connect(options); - awaitConnected(client, TimeUnit.SECONDS.toMillis(30)); - + awaitConnected(client, SECONDS.toMillis(30)); + log.debug("mqtt connected..."); MqttMessage message = new MqttMessage(); message.setPayload((stringKV).getBytes()); - client.publish("v1/devices/me/attributes", message); - Thread.sleep(1000); - client.disconnect(); - return new HashSet<>(doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + viewDeviceId + "/keys/attributes", new TypeReference<>() {})); + getWsClient().registerWaitForUpdate(); + IMqttDeliveryToken token = client.publish("v1/devices/me/attributes", message); + log.debug("publish token.message {}", token.getMessage()); + await("mqtt ack").pollInterval(5, MILLISECONDS).atMost(TIMEOUT, SECONDS).until(() -> token.getMessage() == null); + log.debug("token.message delivered {}", token.getMessage()); + assertThat(getWsClient().waitForUpdate()).as("ws update received").isNotBlank(); + return getAttributeKeys("DEVICE", viewDeviceId); } private Object getValue(List> values, String stringValue) { @@ -502,15 +561,19 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes .findFirst().get().get("value"); } - private EntityView getNewSavedEntityView(String name) throws Exception { + private EntityView getNewSavedEntityView(String name) { EntityView view = createEntityView(name, 0, 0); return doPost("/api/entityView", view, EntityView.class); } + private ListenableFuture getNewSavedEntityViewAsync(String name) { + return executor.submit(() -> getNewSavedEntityView(name)); + } + private EntityView createEntityView(String name, long startTimeMs, long endTimeMs) { EntityView view = new EntityView(); view.setEntityId(testDevice.getId()); - view.setTenantId(savedTenant.getId()); + view.setTenantId(tenantId); view.setName(name); view.setType("default"); view.setKeys(telemetry); @@ -531,33 +594,41 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes return tenant; } - private List fillListOf(int limit, String partOfName, String urlTemplate) throws Exception { - List views = new ArrayList<>(); - for (EntityView view : fillListOf(limit, partOfName)) { - views.add(doPost(urlTemplate + view.getId().getId().toString(), EntityView.class)); + private List> fillListByTemplate(int limit, String partOfName, String urlTemplate) { + List> futures = new ArrayList<>(limit); + for (ListenableFuture viewFuture : fillListOf(limit, partOfName)) { + futures.add(Futures.transform(viewFuture, view -> + doPost(urlTemplate + view.getId().getId().toString(), EntityView.class), + MoreExecutors.directExecutor())); } - return views; + return futures; } - private List fillListOf(int limit, String partOfName) throws Exception { - List viewNames = new ArrayList<>(); + private List> fillListOf(int limit, String partOfName) { + List> viewNameFutures = new ArrayList<>(limit); for (int i = 0; i < limit; i++) { - String fullName = partOfName + ' ' + RandomStringUtils.randomAlphanumeric(15); - fullName = i % 2 == 0 ? fullName.toLowerCase() : fullName.toUpperCase(); - EntityView view = getNewSavedEntityView(fullName); - Customer customer = getNewCustomer("Test customer " + String.valueOf(Math.random())); - view.setCustomerId(doPost("/api/customer", customer, Customer.class).getId()); - viewNames.add(doPost("/api/entityView", view, EntityView.class)); + boolean even = i % 2 == 0; + ListenableFuture customerFuture = executor.submit(() -> { + Customer customer = getNewCustomer("Test customer " + Math.random()); + return doPost("/api/customer", customer, Customer.class).getId(); + }); + + viewNameFutures.add(Futures.transform(customerFuture, customerId -> { + String fullName = partOfName + ' ' + RandomStringUtils.randomAlphanumeric(15); + fullName = even ? fullName.toLowerCase() : fullName.toUpperCase(); + EntityView view = getNewSavedEntityView(fullName); + view.setCustomerId(customerId); + return doPost("/api/entityView", view, EntityView.class); + }, MoreExecutors.directExecutor())); } - return viewNames; + return viewNameFutures; } private List loadListOf(PageLink pageLink, String urlTemplate) throws Exception { List loadedItems = new ArrayList<>(); PageData pageData; do { - pageData = doGetTypedWithPageLink(urlTemplate, new TypeReference>() { - }, pageLink); + pageData = doGetTypedWithPageLink(urlTemplate, PAGE_DATA_ENTITY_VIEW_TYPE_REF, pageLink); loadedItems.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); @@ -571,8 +642,7 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes List loadedItems = new ArrayList<>(); PageData pageData; do { - pageData = doGetTypedWithPageLink(urlTemplate, new TypeReference>() { - }, pageLink); + pageData = doGetTypedWithPageLink(urlTemplate, PAGE_DATA_ENTITY_VIEW_INFO_TYPE_REF, pageLink); loadedItems.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); @@ -596,7 +666,7 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes + "/entityView/" + savedEntityView.getId().getId().toString(), EntityView.class); PageData pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/entityViews?", - new TypeReference>() {}, new PageLink(100)); + PAGE_DATA_ENTITY_VIEW_TYPE_REF, new PageLink(100)); Assert.assertEquals(1, pageData.getData().size()); @@ -604,7 +674,7 @@ public abstract class BaseEntityViewControllerTest extends AbstractControllerTes + "/entityView/" + savedEntityView.getId().getId().toString(), EntityView.class); pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/entityViews?", - new TypeReference>() {}, new PageLink(100)); + PAGE_DATA_ENTITY_VIEW_TYPE_REF, new PageLink(100)); Assert.assertEquals(0, pageData.getData().size()); } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseOtaPackageControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseOtaPackageControllerTest.java index 065fc4bab3..cbc00b0987 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseOtaPackageControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseOtaPackageControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,7 +79,7 @@ public abstract class BaseOtaPackageControllerTest extends AbstractControllerTes tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); - DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile", null); + DeviceProfile deviceProfile = this.createDeviceProfile("Device Profile"); DeviceProfile savedDeviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Assert.assertNotNull(savedDeviceProfile); deviceProfileId = savedDeviceProfile.getId(); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseRpcControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseRpcControllerTest.java index 2881a5194a..81ac7c406c 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseRpcControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseRpcControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseRuleChainControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseRuleChainControllerTest.java index 6363ca3a67..9395f99366 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseRuleChainControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseRuleChainControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseTbResourceControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseTbResourceControllerTest.java index 11a8ff7718..4088e78563 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseTbResourceControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseTbResourceControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseTenantControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseTenantControllerTest.java index 51a7d81df8..2cc8bccc42 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseTenantControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseTenantControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,70 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.web.servlet.ResultActions; +import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TenantInfo; +import org.thingsboard.server.common.data.TenantProfile; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.queue.ProcessingStrategy; +import org.thingsboard.server.common.data.queue.ProcessingStrategyType; +import org.thingsboard.server.common.data.queue.Queue; +import org.thingsboard.server.common.data.queue.SubmitStrategy; +import org.thingsboard.server.common.data.queue.SubmitStrategyType; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; +import org.thingsboard.server.common.data.tenant.profile.TenantProfileData; +import org.thingsboard.server.common.data.tenant.profile.TenantProfileQueueConfiguration; import java.util.ArrayList; -import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@TestPropertySource(properties = { + "js.evaluator=mock", +}) +@Slf4j public abstract class BaseTenantControllerTest extends AbstractControllerTest { - - private IdComparator idComparator = new IdComparator<>(); + + static final TypeReference> PAGE_DATA_TENANT_TYPE_REF = new TypeReference<>() { + }; + static final TypeReference> PAGE_DATA_TENANT_INFO_TYPE_REF = new TypeReference<>() { + }; + + ListeningExecutorService executor; + + @Before + public void setUp() throws Exception { + executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass())); + } + + @After + public void tearDown() throws Exception { + executor.shutdownNow(); + } @Test public void testSaveTenant() throws Exception { @@ -47,10 +93,10 @@ public abstract class BaseTenantControllerTest extends AbstractControllerTest { Assert.assertEquals(tenant.getTitle(), savedTenant.getTitle()); savedTenant.setTitle("My new tenant"); doPost("/api/tenant", savedTenant, Tenant.class); - Tenant foundTenant = doGet("/api/tenant/"+savedTenant.getId().getId().toString(), Tenant.class); + Tenant foundTenant = doGet("/api/tenant/" + savedTenant.getId().getId().toString(), Tenant.class); Assert.assertEquals(foundTenant.getTitle(), savedTenant.getTitle()); - doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) - .andExpect(status().isOk()); + doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + .andExpect(status().isOk()); } @Test @@ -60,18 +106,18 @@ public abstract class BaseTenantControllerTest extends AbstractControllerTest { tenant.setTitle(RandomStringUtils.randomAlphanumeric(300)); doPost("/api/tenant", tenant).andExpect(statusReason(containsString("length of title must be equal or less than 255"))); } - + @Test public void testFindTenantById() throws Exception { loginSysAdmin(); Tenant tenant = new Tenant(); tenant.setTitle("My tenant"); Tenant savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Tenant foundTenant = doGet("/api/tenant/"+savedTenant.getId().getId().toString(), Tenant.class); + Tenant foundTenant = doGet("/api/tenant/" + savedTenant.getId().getId().toString(), Tenant.class); Assert.assertNotNull(foundTenant); Assert.assertEquals(savedTenant, foundTenant); - doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) - .andExpect(status().isOk()); + doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + .andExpect(status().isOk()); } @Test @@ -80,22 +126,22 @@ public abstract class BaseTenantControllerTest extends AbstractControllerTest { Tenant tenant = new Tenant(); tenant.setTitle("My tenant"); Tenant savedTenant = doPost("/api/tenant", tenant, Tenant.class); - TenantInfo foundTenant = doGet("/api/tenant/info/"+savedTenant.getId().getId().toString(), TenantInfo.class); + TenantInfo foundTenant = doGet("/api/tenant/info/" + savedTenant.getId().getId().toString(), TenantInfo.class); Assert.assertNotNull(foundTenant); Assert.assertEquals(new TenantInfo(savedTenant, "Default"), foundTenant); - doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) + doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) .andExpect(status().isOk()); } - + @Test public void testSaveTenantWithEmptyTitle() throws Exception { loginSysAdmin(); Tenant tenant = new Tenant(); doPost("/api/tenant", tenant) - .andExpect(status().isBadRequest()) - .andExpect(statusReason(containsString("Tenant title should be specified"))); + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Tenant title should be specified"))); } - + @Test public void testSaveTenantWithInvalidEmail() throws Exception { loginSysAdmin(); @@ -103,140 +149,147 @@ public abstract class BaseTenantControllerTest extends AbstractControllerTest { tenant.setTitle("My tenant"); tenant.setEmail("invalid@mail"); doPost("/api/tenant", tenant) - .andExpect(status().isBadRequest()) - .andExpect(statusReason(containsString("Invalid email address format"))); + .andExpect(status().isBadRequest()) + .andExpect(statusReason(containsString("Invalid email address format"))); } - + @Test public void testDeleteTenant() throws Exception { loginSysAdmin(); Tenant tenant = new Tenant(); tenant.setTitle("My tenant"); Tenant savedTenant = doPost("/api/tenant", tenant, Tenant.class); - doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) - .andExpect(status().isOk()); - doGet("/api/tenant/"+savedTenant.getId().getId().toString()) - .andExpect(status().isNotFound()); + doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + .andExpect(status().isOk()); + doGet("/api/tenant/" + savedTenant.getId().getId().toString()) + .andExpect(status().isNotFound()); } - + @Test public void testFindTenants() throws Exception { loginSysAdmin(); List tenants = new ArrayList<>(); PageLink pageLink = new PageLink(17); - PageData pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + PageData pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(1, pageData.getData().size()); tenants.addAll(pageData.getData()); - for (int i=0;i<56;i++) { + List> createFutures = new ArrayList<>(56); + for (int i = 0; i < 56; i++) { Tenant tenant = new Tenant(); - tenant.setTitle("Tenant"+i); - tenants.add(doPost("/api/tenant", tenant, Tenant.class)); + tenant.setTitle("Tenant" + i); + createFutures.add(executor.submit(() -> + doPost("/api/tenant", tenant, Tenant.class))); } - + tenants.addAll(Futures.allAsList(createFutures).get(TIMEOUT, TimeUnit.SECONDS)); + List loadedTenants = new ArrayList<>(); pageLink = new PageLink(17); do { - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); loadedTenants.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - - Collections.sort(tenants, idComparator); - Collections.sort(loadedTenants, idComparator); - - Assert.assertEquals(tenants, loadedTenants); - - for (Tenant tenant : loadedTenants) { - if (!tenant.getTitle().equals(TEST_TENANT_NAME)) { - doDelete("/api/tenant/"+tenant.getId().getId().toString()) - .andExpect(status().isOk()); - } - } - + + assertThat(tenants).containsExactlyInAnyOrderElementsOf(loadedTenants); + + deleteEntitiesAsync("/api/tenant/", loadedTenants.stream() + .filter((t) -> !TEST_TENANT_NAME.equals(t.getTitle())) + .collect(Collectors.toList()), executor).get(TIMEOUT, TimeUnit.SECONDS); + pageLink = new PageLink(17); - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(1, pageData.getData().size()); } - + @Test public void testFindTenantsByTitle() throws Exception { + log.debug("login sys admin"); loginSysAdmin(); + log.debug("test started"); String title1 = "Tenant title 1"; - List tenantsTitle1 = new ArrayList<>(); - for (int i=0;i<134;i++) { + List> createFutures = new ArrayList<>(134); + for (int i = 0; i < 134; i++) { Tenant tenant = new Tenant(); - String suffix = RandomStringUtils.randomAlphanumeric((int)(5 + Math.random()*10)); - String title = title1+suffix; + String suffix = RandomStringUtils.randomAlphanumeric((int) (5 + Math.random() * 10)); + String title = title1 + suffix; title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); tenant.setTitle(title); - tenantsTitle1.add(doPost("/api/tenant", tenant, Tenant.class)); + createFutures.add(executor.submit(() -> + doPost("/api/tenant", tenant, Tenant.class))); } + + List tenantsTitle1 = Futures.allAsList(createFutures).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("saved '{}', qty {}", title1, tenantsTitle1.size()); + String title2 = "Tenant title 2"; - List tenantsTitle2 = new ArrayList<>(); - for (int i=0;i<127;i++) { + createFutures = new ArrayList<>(127); + for (int i = 0; i < 127; i++) { Tenant tenant = new Tenant(); - String suffix = RandomStringUtils.randomAlphanumeric((int)(5 + Math.random()*10)); - String title = title2+suffix; + String suffix = RandomStringUtils.randomAlphanumeric((int) (5 + Math.random() * 10)); + String title = title2 + suffix; title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); tenant.setTitle(title); - tenantsTitle2.add(doPost("/api/tenant", tenant, Tenant.class)); + createFutures.add(executor.submit(() -> + doPost("/api/tenant", tenant, Tenant.class))); } - - List loadedTenantsTitle1 = new ArrayList<>(); + + List tenantsTitle2 = Futures.allAsList(createFutures).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("saved '{}', qty {}", title2, tenantsTitle2.size()); + + List loadedTenantsTitle1 = new ArrayList<>(134); PageLink pageLink = new PageLink(15, 0, title1); PageData pageData = null; do { - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); loadedTenantsTitle1.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - - Collections.sort(tenantsTitle1, idComparator); - Collections.sort(loadedTenantsTitle1, idComparator); - - Assert.assertEquals(tenantsTitle1, loadedTenantsTitle1); - - List loadedTenantsTitle2 = new ArrayList<>(); + + log.debug("found by name '{}', step 15 {}", title1, loadedTenantsTitle1.size()); + + assertThat(tenantsTitle1).as(title1).containsExactlyInAnyOrderElementsOf(loadedTenantsTitle1); + log.debug("asserted"); + + List loadedTenantsTitle2 = new ArrayList<>(127); pageLink = new PageLink(4, 0, title2); do { - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); loadedTenantsTitle2.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(tenantsTitle2, idComparator); - Collections.sort(loadedTenantsTitle2, idComparator); - - Assert.assertEquals(tenantsTitle2, loadedTenantsTitle2); + log.debug("found by name '{}', step 4 {}", title1, loadedTenantsTitle2.size()); + assertThat(tenantsTitle2).as(title2).containsExactlyInAnyOrderElementsOf(loadedTenantsTitle2); + log.debug("asserted"); + + + deleteEntitiesAsync("/api/tenant/", loadedTenantsTitle1, executor).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("deleted '{}', size {}", title1, loadedTenantsTitle1.size()); - for (Tenant tenant : loadedTenantsTitle1) { - doDelete("/api/tenant/"+tenant.getId().getId().toString()) - .andExpect(status().isOk()); - } - pageLink = new PageLink(4, 0, title1); - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); - - for (Tenant tenant : loadedTenantsTitle2) { - doDelete("/api/tenant/"+tenant.getId().getId().toString()) - .andExpect(status().isOk()); - } - + + log.debug("tried to search another '{}', step 4", title1); + + deleteEntitiesAsync("/api/tenant/", loadedTenantsTitle2, executor).get(TIMEOUT, TimeUnit.SECONDS); + log.debug("deleted '{}', size {}", title2, loadedTenantsTitle2.size()); + pageLink = new PageLink(4, 0, title2); - pageData = doGetTypedWithPageLink("/api/tenants?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenants?", PAGE_DATA_TENANT_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(0, pageData.getData().size()); + log.debug("tried to search another '{}', step 4", title2); } @Test @@ -244,42 +297,226 @@ public abstract class BaseTenantControllerTest extends AbstractControllerTest { loginSysAdmin(); List tenants = new ArrayList<>(); PageLink pageLink = new PageLink(17); - PageData pageData = doGetTypedWithPageLink("/api/tenantInfos?", new TypeReference>(){}, pageLink); + PageData pageData = doGetTypedWithPageLink("/api/tenantInfos?", PAGE_DATA_TENANT_INFO_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(1, pageData.getData().size()); tenants.addAll(pageData.getData()); - for (int i=0;i<56;i++) { + List> createFutures = new ArrayList<>(56); + for (int i = 0; i < 56; i++) { Tenant tenant = new Tenant(); - tenant.setTitle("Tenant"+i); - tenants.add(new TenantInfo(doPost("/api/tenant", tenant, Tenant.class), "Default")); + tenant.setTitle("Tenant" + i); + createFutures.add(executor.submit(() -> + new TenantInfo(doPost("/api/tenant", tenant, Tenant.class), "Default"))); } + tenants.addAll(Futures.allAsList(createFutures).get(TIMEOUT, TimeUnit.SECONDS)); List loadedTenants = new ArrayList<>(); pageLink = new PageLink(17); do { - pageData = doGetTypedWithPageLink("/api/tenantInfos?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenantInfos?", PAGE_DATA_TENANT_INFO_TYPE_REF, pageLink); loadedTenants.addAll(pageData.getData()); if (pageData.hasNext()) { pageLink = pageLink.nextPageLink(); } } while (pageData.hasNext()); - Collections.sort(tenants, idComparator); - Collections.sort(loadedTenants, idComparator); - - Assert.assertEquals(tenants, loadedTenants); + assertThat(tenants).containsExactlyInAnyOrderElementsOf(loadedTenants); - for (TenantInfo tenant : loadedTenants) { - if (!tenant.getTitle().equals(TEST_TENANT_NAME)) { - doDelete("/api/tenant/"+tenant.getId().getId().toString()) - .andExpect(status().isOk()); - } - } + deleteEntitiesAsync("/api/tenant/", loadedTenants.stream() + .filter((t) -> !TEST_TENANT_NAME.equals(t.getTitle())) + .collect(Collectors.toList()), executor).get(TIMEOUT, TimeUnit.SECONDS); pageLink = new PageLink(17); - pageData = doGetTypedWithPageLink("/api/tenantInfos?", new TypeReference>(){}, pageLink); + pageData = doGetTypedWithPageLink("/api/tenantInfos?", PAGE_DATA_TENANT_INFO_TYPE_REF, pageLink); Assert.assertFalse(pageData.hasNext()); Assert.assertEquals(1, pageData.getData().size()); } + + ListenableFuture> deleteTenantsAsync(String urlTemplate, List tenants) { + List> futures = new ArrayList<>(tenants.size()); + for (Tenant device : tenants) { + futures.add(executor.submit(() -> + doDelete(urlTemplate + device.getId().getId()) + .andExpect(status().isOk()))); + } + return Futures.allAsList(futures); + } + + @Test + public void testUpdateQueueConfigForIsolatedTenant() throws Exception { + Comparator queueComparator = Comparator.comparing(Queue::getName); + final String username = "isolatedtenant@thingsboard.org"; + final String password = "123456"; + loginSysAdmin(); + + List sysAdminQueues; + PageLink pageLink = new PageLink(10); + PageData pageData; + pageData = doGetTypedWithPageLink("/api/queues?serviceType=TB_RULE_ENGINE&", new TypeReference<>() { + }, pageLink); + sysAdminQueues = pageData.getData(); + + Tenant tenant = new Tenant(); + tenant.setTitle("Isolated tenant"); + tenant = doPost("/api/tenant", tenant, Tenant.class); + + User tenantUser = new User(); + tenantUser.setAuthority(Authority.TENANT_ADMIN); + tenantUser.setTenantId(tenant.getId()); + tenantUser.setEmail(username); + createUserAndLogin(tenantUser, password); + + List foundTenantQueues; + + pageLink = new PageLink(10); + pageData = doGetTypedWithPageLink("/api/queues?serviceType=TB_RULE_ENGINE&", new TypeReference<>() {}, pageLink); + foundTenantQueues = pageData.getData(); + + Assert.assertEquals(sysAdminQueues, foundTenantQueues); + + loginSysAdmin(); + + TenantProfile tenantProfile = new TenantProfile(); + tenantProfile.setName("isolated-tb-rule-engine"); + TenantProfileData tenantProfileData = new TenantProfileData(); + tenantProfileData.setConfiguration(new DefaultTenantProfileConfiguration()); + tenantProfile.setProfileData(tenantProfileData); + tenantProfile.setIsolatedTbRuleEngine(true); + addQueueConfig(tenantProfile, "Main"); + addQueueConfig(tenantProfile, "Test"); + tenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.class); + + tenant.setTenantProfileId(tenantProfile.getId()); + doPost("/api/tenant", tenant, Tenant.class); + + login(username, password); + + pageLink = new PageLink(10); + pageData = doGetTypedWithPageLink("/api/queues?serviceType=TB_RULE_ENGINE&", new TypeReference<>() {}, pageLink); + foundTenantQueues = pageData.getData(); + + Assert.assertEquals(2, foundTenantQueues.size()); + + List queuesFromConfig = getQueuesFromConfig(tenantProfile.getProfileData().getQueueConfiguration(), foundTenantQueues); + queuesFromConfig.sort(queueComparator); + foundTenantQueues.sort(queueComparator); + + Assert.assertEquals(queuesFromConfig, foundTenantQueues); + + loginSysAdmin(); + + TenantProfile tenantProfile2 = new TenantProfile(); + tenantProfile2.setName("isolated-tb-rule-engine2"); + TenantProfileData tenantProfileData2 = new TenantProfileData(); + tenantProfileData2.setConfiguration(new DefaultTenantProfileConfiguration()); + tenantProfile2.setProfileData(tenantProfileData2); + tenantProfile2.setIsolatedTbRuleEngine(true); + addQueueConfig(tenantProfile2, "Main"); + addQueueConfig(tenantProfile2, "Test"); + addQueueConfig(tenantProfile2, "Test2"); + tenantProfile2 = doPost("/api/tenantProfile", tenantProfile2, TenantProfile.class); + + tenant.setTenantProfileId(tenantProfile2.getId()); + doPost("/api/tenant", tenant, Tenant.class); + + login(username, password); + + pageLink = new PageLink(10); + pageData = doGetTypedWithPageLink("/api/queues?serviceType=TB_RULE_ENGINE&", new TypeReference<>() {}, pageLink); + foundTenantQueues = pageData.getData(); + + Assert.assertEquals(3, foundTenantQueues.size()); + + queuesFromConfig = getQueuesFromConfig(tenantProfile2.getProfileData().getQueueConfiguration(), foundTenantQueues); + queuesFromConfig.sort(queueComparator); + foundTenantQueues.sort(queueComparator); + + Assert.assertEquals(queuesFromConfig, foundTenantQueues); + + loginSysAdmin(); + + tenantProfile2.getProfileData().getQueueConfiguration().removeIf(q -> q.getName().equals("Test")); + tenantProfile2.getProfileData().getQueueConfiguration().removeIf(q -> q.getName().equals("Test2")); + addQueueConfig(tenantProfile2, "Test2"); + addQueueConfig(tenantProfile2, "Test3"); + + tenantProfile2 = doPost("/api/tenantProfile", tenantProfile2, TenantProfile.class); + + login(username, password); + + pageLink = new PageLink(10); + pageData = doGetTypedWithPageLink("/api/queues?serviceType=TB_RULE_ENGINE&", new TypeReference<>() {}, pageLink); + foundTenantQueues = pageData.getData(); + + Assert.assertEquals(3, foundTenantQueues.size()); + + queuesFromConfig = getQueuesFromConfig(tenantProfile2.getProfileData().getQueueConfiguration(), foundTenantQueues); + queuesFromConfig.sort(queueComparator); + foundTenantQueues.sort(queueComparator); + + Assert.assertEquals(queuesFromConfig, foundTenantQueues); + + loginSysAdmin(); + + tenant.setTenantProfileId(null); + doPost("/api/tenant", tenant, Tenant.class); + + login(username, password); + for (Queue queue : foundTenantQueues) { + doGet("/api/queues/" + queue.getId()).andExpect(status().isNotFound()); + } + + loginSysAdmin(); + doDelete("/api/tenant/" + tenant.getId().getId().toString()).andExpect(status().isOk()); + } + + private void addQueueConfig(TenantProfile tenantProfile, String queueName) { + TenantProfileQueueConfiguration queueConfiguration = new TenantProfileQueueConfiguration(); + queueConfiguration.setName(queueName); + queueConfiguration.setTopic("tb_rule_engine." + queueName.toLowerCase()); + queueConfiguration.setPollInterval(25); + queueConfiguration.setPartitions(new Random().nextInt(100)); + queueConfiguration.setConsumerPerPartition(true); + queueConfiguration.setPackProcessingTimeout(2000); + SubmitStrategy submitStrategy = new SubmitStrategy(); + submitStrategy.setType(SubmitStrategyType.BURST); + submitStrategy.setBatchSize(1000); + queueConfiguration.setSubmitStrategy(submitStrategy); + ProcessingStrategy processingStrategy = new ProcessingStrategy(); + processingStrategy.setType(ProcessingStrategyType.SKIP_ALL_FAILURES); + processingStrategy.setRetries(3); + processingStrategy.setFailurePercentage(0); + processingStrategy.setPauseBetweenRetries(3); + processingStrategy.setMaxPauseBetweenRetries(3); + queueConfiguration.setProcessingStrategy(processingStrategy); + TenantProfileData profileData = tenantProfile.getProfileData(); + + List configs = profileData.getQueueConfiguration(); + if (configs == null) { + configs = new ArrayList<>(); + } + configs.add(queueConfiguration); + profileData.setQueueConfiguration(configs); + tenantProfile.setProfileData(profileData); + } + + private List getQueuesFromConfig(List queueConfiguration, List queues) { + List result = new ArrayList<>(); + Map queueMap = new HashMap<>(); + for (Queue queue : queues) { + queueMap.put(queue.getName(), queue); + } + + for (TenantProfileQueueConfiguration config : queueConfiguration) { + Queue queue = queueMap.get(config.getName()); + if (queue != null) { + Queue expectedQueue = new Queue(queue.getTenantId(), config); + expectedQueue.setId(queue.getId()); + expectedQueue.setCreatedTime(queue.getCreatedTime()); + result.add(queue); + } + } + return result; + } } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseTenantProfileControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseTenantProfileControllerTest.java index c33b8a3f29..1867577c23 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseTenantProfileControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseTenantProfileControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.EntityInfo; import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TenantProfile; +import org.thingsboard.server.common.data.queue.ProcessingStrategy; +import org.thingsboard.server.common.data.queue.ProcessingStrategyType; +import org.thingsboard.server.common.data.queue.SubmitStrategy; +import org.thingsboard.server.common.data.queue.SubmitStrategyType; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.data.tenant.profile.TenantProfileData; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.tenant.profile.TenantProfileQueueConfiguration; import org.thingsboard.server.dao.tenant.TenantProfileService; import java.util.ArrayList; @@ -44,9 +49,6 @@ public abstract class BaseTenantProfileControllerTest extends AbstractController private IdComparator idComparator = new IdComparator<>(); private IdComparator tenantProfileInfoIdComparator = new IdComparator<>(); - @Autowired - private TenantProfileService tenantProfileService; - @Test public void testSaveTenantProfile() throws Exception { loginSysAdmin(); @@ -109,7 +111,7 @@ public abstract class BaseTenantProfileControllerTest extends AbstractController loginSysAdmin(); TenantProfile tenantProfile = this.createTenantProfile("Tenant Profile 1"); TenantProfile savedTenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.class); - TenantProfile defaultTenantProfile = doPost("/api/tenantProfile/"+savedTenantProfile.getId().getId().toString()+"/default", null, TenantProfile.class); + TenantProfile defaultTenantProfile = doPost("/api/tenantProfile/"+savedTenantProfile.getId().getId().toString()+"/default", TenantProfile.class); Assert.assertNotNull(defaultTenantProfile); EntityInfo foundDefaultTenantProfile = doGet("/api/tenantProfileInfo/default", EntityInfo.class); Assert.assertNotNull(foundDefaultTenantProfile); @@ -141,6 +143,7 @@ public abstract class BaseTenantProfileControllerTest extends AbstractController TenantProfile tenantProfile = this.createTenantProfile("Tenant Profile"); TenantProfile savedTenantProfile = doPost("/api/tenantProfile", tenantProfile, TenantProfile.class); savedTenantProfile.setIsolatedTbRuleEngine(true); + addMainQueueConfig(savedTenantProfile); doPost("/api/tenantProfile", savedTenantProfile).andExpect(status().isBadRequest()) .andExpect(statusReason(containsString("Can't update isolatedTbRuleEngine property"))); } @@ -295,4 +298,28 @@ public abstract class BaseTenantProfileControllerTest extends AbstractController tenantProfile.setIsolatedTbRuleEngine(false); return tenantProfile; } + + private void addMainQueueConfig(TenantProfile tenantProfile) { + TenantProfileQueueConfiguration mainQueueConfiguration = new TenantProfileQueueConfiguration(); + mainQueueConfiguration.setName("Main"); + mainQueueConfiguration.setTopic("tb_rule_engine.main"); + mainQueueConfiguration.setPollInterval(25); + mainQueueConfiguration.setPartitions(10); + mainQueueConfiguration.setConsumerPerPartition(true); + mainQueueConfiguration.setPackProcessingTimeout(2000); + SubmitStrategy mainQueueSubmitStrategy = new SubmitStrategy(); + mainQueueSubmitStrategy.setType(SubmitStrategyType.BURST); + mainQueueSubmitStrategy.setBatchSize(1000); + mainQueueConfiguration.setSubmitStrategy(mainQueueSubmitStrategy); + ProcessingStrategy mainQueueProcessingStrategy = new ProcessingStrategy(); + mainQueueProcessingStrategy.setType(ProcessingStrategyType.SKIP_ALL_FAILURES); + mainQueueProcessingStrategy.setRetries(3); + mainQueueProcessingStrategy.setFailurePercentage(0); + mainQueueProcessingStrategy.setPauseBetweenRetries(3); + mainQueueProcessingStrategy.setMaxPauseBetweenRetries(3); + mainQueueConfiguration.setProcessingStrategy(mainQueueProcessingStrategy); + TenantProfileData profileData = tenantProfile.getProfileData(); + profileData.setQueueConfiguration(Collections.singletonList(mainQueueConfiguration)); + tenantProfile.setProfileData(profileData); + } } diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseUserControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseUserControllerTest.java index 652089daeb..5b917ea8fa 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseUserControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseUserControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseWebsocketApiTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseWebsocketApiTest.java index 16894a9523..f7838d9689 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseWebsocketApiTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseWebsocketApiTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,6 @@ import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.id.CustomerId; -import org.thingsboard.server.common.data.kv.Aggregation; import org.thingsboard.server.common.data.kv.AttributeKvEntry; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.common.data.kv.BasicTsKvEntry; @@ -46,19 +42,12 @@ import org.thingsboard.server.common.data.query.FilterPredicateValue; import org.thingsboard.server.common.data.query.KeyFilter; import org.thingsboard.server.common.data.query.NumericFilterPredicate; import org.thingsboard.server.common.data.query.TsValue; -import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.service.subscription.TbAttributeSubscriptionScope; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; -import org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper; import org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd; import org.thingsboard.server.service.telemetry.cmd.v2.EntityCountUpdate; -import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd; import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate; -import org.thingsboard.server.service.telemetry.cmd.v2.EntityHistoryCmd; -import org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd; -import org.thingsboard.server.service.telemetry.cmd.v2.TimeSeriesCmd; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -68,77 +57,38 @@ import java.util.concurrent.TimeUnit; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { - - private Tenant savedTenant; - private User tenantAdmin; - private TbTestWebSocketClient wsClient; - +public abstract class BaseWebsocketApiTest extends AbstractControllerTest { @Autowired private TelemetrySubscriptionService tsService; - @Before - public void beforeTest() throws Exception { - loginSysAdmin(); - - Tenant tenant = new Tenant(); - tenant.setTitle("My tenant"); - savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedTenant); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant2@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); + Device device; + DeviceTypeFilter dtf; - tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); + @Before + public void setUp() throws Exception { + loginTenantAdmin(); - wsClient = buildAndConnectWebSocketClient(); + device = new Device(); + device.setName("Device"); + device.setType("default"); + device.setLabel("testLabel" + (int) (Math.random() * 1000)); + device = doPost("/api/device", device, Device.class); + dtf = new DeviceTypeFilter(device.getType(), device.getName()); } @After - public void afterTest() throws Exception { - wsClient.close(); - - loginSysAdmin(); - - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + public void tearDown() throws Exception { + doDelete("/api/device/" + device.getId().getId()) .andExpect(status().isOk()); } @Test public void testEntityDataHistoryWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - + List keys = List.of("temperature"); long now = System.currentTimeMillis(); - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, - new EntityDataPageLink(1, 0, null, null), - Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - - EntityHistoryCmd historyCmd = new EntityHistoryCmd(); - historyCmd.setKeys(Arrays.asList("temperature")); - historyCmd.setAgg(Aggregation.NONE); - historyCmd.setLimit(1000); - historyCmd.setStartTs(now - TimeUnit.HOURS.toMillis(1)); - historyCmd.setEndTs(now); - EntityDataCmd cmd = new EntityDataCmd(1, edq, historyCmd, null, null); - - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); + EntityDataUpdate update = getWsClient().sendHistoryCmd(keys, now, TimeUnit.HOURS.toMillis(1), dtf); + Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); @@ -152,11 +102,9 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { List tsData = Arrays.asList(dataPoint1, dataPoint2, dataPoint3); sendTelemetry(device, tsData); - Thread.sleep(100); - wsClient.send(mapper.writeValueAsString(wrapper)); - msg = wsClient.waitForReply(); - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().sendHistoryCmd(keys, now, TimeUnit.HOURS.toMillis(1), dtf); + Assert.assertEquals(1, update.getCmdId()); List dataList = update.getUpdate(); Assert.assertNotNull(dataList); @@ -171,55 +119,24 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { @Test public void testEntityDataTimeSeriesWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - long now = System.currentTimeMillis(); - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), - Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - - EntityDataCmd cmd = new EntityDataCmd(1, edq, null, null, null); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(dtf); - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); Assert.assertEquals(1, pageData.getData().size()); Assert.assertEquals(device.getId(), pageData.getData().get(0).getEntityId()); - TimeSeriesCmd tsCmd = new TimeSeriesCmd(); - tsCmd.setKeys(Arrays.asList("temperature")); - tsCmd.setAgg(Aggregation.NONE); - tsCmd.setLimit(1000); - tsCmd.setStartTs(now - TimeUnit.HOURS.toMillis(1)); - tsCmd.setTimeWindow(TimeUnit.HOURS.toMillis(1)); - TsKvEntry dataPoint1 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("temperature", 42L)); TsKvEntry dataPoint2 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(2), new LongDataEntry("temperature", 43L)); TsKvEntry dataPoint3 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(3), new LongDataEntry("temperature", 44L)); List tsData = Arrays.asList(dataPoint1, dataPoint2, dataPoint3); sendTelemetry(device, tsData); - Thread.sleep(100); - cmd = new EntityDataCmd(1, null, null, null, tsCmd); - wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - wsClient.send(mapper.writeValueAsString(wrapper)); - msg = wsClient.waitForReply(); - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().subscribeTsUpdate(List.of("temperature"), now, TimeUnit.HOURS.toMillis(1)); Assert.assertEquals(1, update.getCmdId()); List listData = update.getUpdate(); Assert.assertNotNull(listData); @@ -233,10 +150,9 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { now = System.currentTimeMillis(); TsKvEntry dataPoint4 = new BasicTsKvEntry(now, new LongDataEntry("temperature", 45L)); - wsClient.registerWaitForUpdate(); - Thread.sleep(100); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint4)); - msg = wsClient.waitForUpdate(); + String msg = getWsClient().waitForUpdate(); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); @@ -252,44 +168,26 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { @Test public void testEntityCountWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - AttributeKvEntry dataPoint1 = new BaseAttributeKvEntry(System.currentTimeMillis(), new LongDataEntry("temperature", 42L)); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Collections.singletonList(dataPoint1)); - DeviceTypeFilter dtf1 = new DeviceTypeFilter(); - dtf1.setDeviceNameFilter("D"); - dtf1.setDeviceType("default"); - EntityCountQuery edq1 = new EntityCountQuery(dtf1, Collections.emptyList()); - + EntityCountQuery edq1 = new EntityCountQuery(dtf, Collections.emptyList()); EntityCountCmd cmd1 = new EntityCountCmd(1, edq1); - TelemetryPluginCmdsWrapper wrapper1 = new TelemetryPluginCmdsWrapper(); - wrapper1.setEntityCountCmds(Collections.singletonList(cmd1)); + getWsClient().send(cmd1); - wsClient.send(mapper.writeValueAsString(wrapper1)); - String msg1 = wsClient.waitForReply(); - EntityCountUpdate update1 = mapper.readValue(msg1, EntityCountUpdate.class); + EntityCountUpdate update1 = getWsClient().parseCountReply(getWsClient().waitForReply()); Assert.assertEquals(1, update1.getCmdId()); Assert.assertEquals(1, update1.getCount()); - DeviceTypeFilter dtf2 = new DeviceTypeFilter(); - dtf2.setDeviceNameFilter("D"); - dtf2.setDeviceType("non-existing-device-type"); + DeviceTypeFilter dtf2 = new DeviceTypeFilter("non-existing-device-type", "D"); EntityCountQuery edq2 = new EntityCountQuery(dtf2, Collections.emptyList()); - EntityCountCmd cmd2 = new EntityCountCmd(2, edq2); - TelemetryPluginCmdsWrapper wrapper2 = new TelemetryPluginCmdsWrapper(); - wrapper2.setEntityCountCmds(Collections.singletonList(cmd2)); - wsClient.send(mapper.writeValueAsString(wrapper2)); + getWsClient().send(cmd2); - String msg2 = wsClient.waitForReply(); - EntityCountUpdate update2 = mapper.readValue(msg2, EntityCountUpdate.class); + String msg2 = getWsClient().waitForReply(); + EntityCountUpdate update2 = getWsClient().parseCountReply(getWsClient().waitForReply()); Assert.assertEquals(2, update2.getCmdId()); Assert.assertEquals(0, update2.getCount()); @@ -301,19 +199,12 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { highTemperatureFilter.setPredicate(predicate); highTemperatureFilter.setValueType(EntityKeyValueType.NUMERIC); - DeviceTypeFilter dtf3 = new DeviceTypeFilter(); - dtf3.setDeviceNameFilter("D"); - dtf3.setDeviceType("default"); + DeviceTypeFilter dtf3 = new DeviceTypeFilter("default", "D"); EntityCountQuery edq3 = new EntityCountQuery(dtf3, Collections.singletonList(highTemperatureFilter)); - EntityCountCmd cmd3 = new EntityCountCmd(3, edq3); + getWsClient().send(cmd3); - TelemetryPluginCmdsWrapper wrapper3 = new TelemetryPluginCmdsWrapper(); - wrapper3.setEntityCountCmds(Collections.singletonList(cmd3)); - wsClient.send(mapper.writeValueAsString(wrapper3)); - - String msg3 = wsClient.waitForReply(); - EntityCountUpdate update3 = mapper.readValue(msg3, EntityCountUpdate.class); + EntityCountUpdate update3 = getWsClient().parseCountReply(getWsClient().waitForReply()); Assert.assertEquals(3, update3.getCmdId()); Assert.assertEquals(1, update3.getCount()); @@ -325,47 +216,26 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { highTemperatureFilter2.setPredicate(predicate2); highTemperatureFilter2.setValueType(EntityKeyValueType.NUMERIC); - DeviceTypeFilter dtf4 = new DeviceTypeFilter(); - dtf4.setDeviceNameFilter("D"); - dtf4.setDeviceType("default"); + DeviceTypeFilter dtf4 = new DeviceTypeFilter("default", "D"); EntityCountQuery edq4 = new EntityCountQuery(dtf4, Collections.singletonList(highTemperatureFilter2)); - EntityCountCmd cmd4 = new EntityCountCmd(4, edq4); - TelemetryPluginCmdsWrapper wrapper4 = new TelemetryPluginCmdsWrapper(); - wrapper4.setEntityCountCmds(Collections.singletonList(cmd4)); - wsClient.send(mapper.writeValueAsString(wrapper4)); + getWsClient().send(cmd4); - String msg4 = wsClient.waitForReply(); - EntityCountUpdate update4 = mapper.readValue(msg4, EntityCountUpdate.class); + EntityCountUpdate update4 = getWsClient().parseCountReply(getWsClient().waitForReply()); Assert.assertEquals(4, update4.getCmdId()); Assert.assertEquals(0, update4.getCount()); } @Test public void testEntityDataLatestWidgetFlow() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - - long now = System.currentTimeMillis(); - - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), Collections.emptyList(), - Collections.singletonList(new EntityKey(EntityKeyType.TIME_SERIES, "temperature")), Collections.emptyList()); - - EntityDataCmd cmd = new EntityDataCmd(1, edq, null, null, null); + List keys = List.of(new EntityKey(EntityKeyType.TIME_SERIES, "temperature")); + long now = System.currentTimeMillis() - 100; - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); + EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), + Collections.emptyList(), keys, Collections.emptyList()); - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); + EntityDataUpdate update = getWsClient().sendEntityDataQuery(edq); Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); @@ -379,17 +249,7 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { List tsData = Arrays.asList(dataPoint1); sendTelemetry(device, tsData); - Thread.sleep(100); - - LatestValueCmd latestCmd = new LatestValueCmd(); - latestCmd.setKeys(Collections.singletonList(new EntityKey(EntityKeyType.TIME_SERIES, "temperature"))); - cmd = new EntityDataCmd(1, null, null, latestCmd, null); - wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - msg = wsClient.waitForReply(); - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().subscribeLatestUpdate(keys); Assert.assertEquals(1, update.getCmdId()); @@ -404,11 +264,10 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { now = System.currentTimeMillis(); TsKvEntry dataPoint2 = new BasicTsKvEntry(now, new LongDataEntry("temperature", 52L)); - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(); - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().parseDataReply(getWsClient().waitForUpdate()); Assert.assertEquals(1, update.getCmdId()); List eData = update.getUpdate(); Assert.assertNotNull(eData); @@ -419,43 +278,25 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(new TsValue(dataPoint2.getTs(), dataPoint2.getValueAsString()), tsValue); //Sending update from the past, while latest value has new timestamp; - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint1)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + String msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); //Sending duplicate update again - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); } @Test public void testEntityDataLatestTsWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - long now = System.currentTimeMillis(); + List keys = List.of(new EntityKey(EntityKeyType.TIME_SERIES, "temperature")); - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + EntityDataUpdate update = getWsClient().subscribeLatestUpdate(keys, dtf); - LatestValueCmd latestCmd = new LatestValueCmd(); - latestCmd.setKeys(Collections.singletonList(new EntityKey(EntityKeyType.TIME_SERIES, "temperature"))); - EntityDataCmd cmd = new EntityDataCmd(1, edq, null, latestCmd, null); - - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); @@ -465,19 +306,12 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(0, pageData.getData().get(0).getLatest().get(EntityKeyType.TIME_SERIES).get("temperature").getTs()); Assert.assertEquals("", pageData.getData().get(0).getLatest().get(EntityKeyType.TIME_SERIES).get("temperature").getValue()); + getWsClient().registerWaitForUpdate(); TsKvEntry dataPoint1 = new BasicTsKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("temperature", 42L)); List tsData = Arrays.asList(dataPoint1); sendTelemetry(device, tsData); - Thread.sleep(100); - - cmd = new EntityDataCmd(1, edq, null, latestCmd, null); - wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - msg = wsClient.waitForReply(); - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().parseDataReply(getWsClient().waitForUpdate()); Assert.assertEquals(1, update.getCmdId()); @@ -491,12 +325,9 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { now = System.currentTimeMillis(); TsKvEntry dataPoint2 = new BasicTsKvEntry(now, new LongDataEntry("temperature", 52L)); - - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(); - - update = mapper.readValue(msg, EntityDataUpdate.class); + update = getWsClient().parseDataReply(getWsClient().waitForUpdate()); Assert.assertEquals(1, update.getCmdId()); List eData = update.getUpdate(); Assert.assertNotNull(eData); @@ -507,45 +338,24 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(new TsValue(dataPoint2.getTs(), dataPoint2.getValueAsString()), tsValue); //Sending update from the past, while latest value has new timestamp; - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint1)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + String msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); //Sending duplicate update again - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendTelemetry(device, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); } @Test public void testEntityDataLatestAttrWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - long now = System.currentTimeMillis(); + List keys = List.of(new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "serverAttributeKey")); - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), - Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - - LatestValueCmd latestCmd = new LatestValueCmd(); - latestCmd.setKeys(Collections.singletonList(new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "serverAttributeKey"))); - EntityDataCmd cmd = new EntityDataCmd(1, edq, null, latestCmd, null); - - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - Assert.assertNotNull(msg); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); + EntityDataUpdate update = getWsClient().subscribeLatestUpdate(keys, dtf); Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); @@ -555,15 +365,13 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(0, pageData.getData().get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey").getTs()); Assert.assertEquals("", pageData.getData().get(0).getLatest().get(EntityKeyType.SERVER_ATTRIBUTE).get("serverAttributeKey").getValue()); - - wsClient.registerWaitForUpdate(); - Thread.sleep(500); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint1 = new BaseAttributeKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("serverAttributeKey", 42L)); List tsData = Arrays.asList(dataPoint1); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, tsData); - msg = wsClient.waitForUpdate(); + String msg = getWsClient().waitForUpdate(); Assert.assertNotNull(msg); update = mapper.readValue(msg, EntityDataUpdate.class); @@ -579,10 +387,9 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { now = System.currentTimeMillis(); AttributeKvEntry dataPoint2 = new BaseAttributeKvEntry(now, new LongDataEntry("serverAttributeKey", 52L)); - wsClient.registerWaitForUpdate(); - Thread.sleep(500); + getWsClient().registerWaitForUpdate(); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(); + msg = getWsClient().waitForUpdate(); Assert.assertNotNull(msg); update = mapper.readValue(msg, EntityDataUpdate.class); @@ -596,51 +403,29 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(new TsValue(dataPoint2.getLastUpdateTs(), dataPoint2.getValueAsString()), tsValue); //Sending update from the past, while latest value has new timestamp; - wsClient.registerWaitForUpdate(); - Thread.sleep(500); + getWsClient().registerWaitForUpdate(); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint1)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); //Sending duplicate update again - wsClient.registerWaitForUpdate(); - Thread.sleep(500); + getWsClient().registerWaitForUpdate(); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); } @Test public void testEntityDataLatestAttrTypesWsCmd() throws Exception { - Device device = new Device(); - device.setName("Device"); - device.setType("default"); - device.setLabel("testLabel" + (int) (Math.random() * 1000)); - device = doPost("/api/device", device, Device.class); - long now = System.currentTimeMillis(); + List keys = List.of( + new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "serverAttributeKey"), + new EntityKey(EntityKeyType.CLIENT_ATTRIBUTE, "clientAttributeKey"), + new EntityKey(EntityKeyType.SHARED_ATTRIBUTE, "sharedAttributeKey"), + new EntityKey(EntityKeyType.ATTRIBUTE, "anyAttributeKey")); + + EntityDataUpdate update = getWsClient().subscribeLatestUpdate(keys, dtf); - DeviceTypeFilter dtf = new DeviceTypeFilter(); - dtf.setDeviceNameFilter("D"); - dtf.setDeviceType("default"); - EntityDataQuery edq = new EntityDataQuery(dtf, new EntityDataPageLink(1, 0, null, null), - Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - - LatestValueCmd latestCmd = new LatestValueCmd(); - List keys = new ArrayList<>(); - keys.add(new EntityKey(EntityKeyType.SERVER_ATTRIBUTE, "serverAttributeKey")); - keys.add(new EntityKey(EntityKeyType.CLIENT_ATTRIBUTE, "clientAttributeKey")); - keys.add(new EntityKey(EntityKeyType.SHARED_ATTRIBUTE, "sharedAttributeKey")); - keys.add(new EntityKey(EntityKeyType.ATTRIBUTE, "anyAttributeKey")); - latestCmd.setKeys(keys); - EntityDataCmd cmd = new EntityDataCmd(1, edq, null, latestCmd, null); - - TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); - wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - - wsClient.send(mapper.writeValueAsString(wrapper)); - String msg = wsClient.waitForReply(); - EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); PageData pageData = update.getData(); Assert.assertNotNull(pageData); @@ -659,14 +444,13 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(0, pageData.getData().get(0).getLatest().get(EntityKeyType.ATTRIBUTE).get("anyAttributeKey").getTs()); Assert.assertEquals("", pageData.getData().get(0).getLatest().get(EntityKeyType.ATTRIBUTE).get("anyAttributeKey").getValue()); - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint1 = new BaseAttributeKvEntry(now - TimeUnit.MINUTES.toMillis(1), new LongDataEntry("serverAttributeKey", 42L)); List tsData = Arrays.asList(dataPoint1); - Thread.sleep(100); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, tsData); - msg = wsClient.waitForUpdate(); + String msg = getWsClient().waitForUpdate(); Assert.assertNotNull(msg); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); @@ -679,22 +463,22 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { Assert.assertEquals(new TsValue(dataPoint1.getLastUpdateTs(), dataPoint1.getValueAsString()), attrValue); //Sending update from the past, while latest value has new timestamp; - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendAttributes(device, TbAttributeSubscriptionScope.SHARED_SCOPE, Arrays.asList(dataPoint1)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); //Sending duplicate update again - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); sendAttributes(device, TbAttributeSubscriptionScope.CLIENT_SCOPE, Arrays.asList(dataPoint1)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); Assert.assertNull(msg); //Sending update from the past, while latest value has new timestamp; - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint2 = new BaseAttributeKvEntry(now, new LongDataEntry("sharedAttributeKey", 42L)); sendAttributes(device, TbAttributeSubscriptionScope.SHARED_SCOPE, Arrays.asList(dataPoint2)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); eData = update.getUpdate(); @@ -705,10 +489,10 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { attrValue = eData.get(0).getLatest().get(EntityKeyType.SHARED_ATTRIBUTE).get("sharedAttributeKey"); Assert.assertEquals(new TsValue(dataPoint2.getLastUpdateTs(), dataPoint2.getValueAsString()), attrValue); - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint3 = new BaseAttributeKvEntry(now, new LongDataEntry("clientAttributeKey", 42L)); sendAttributes(device, TbAttributeSubscriptionScope.CLIENT_SCOPE, Arrays.asList(dataPoint3)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); eData = update.getUpdate(); @@ -719,10 +503,10 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { attrValue = eData.get(0).getLatest().get(EntityKeyType.CLIENT_ATTRIBUTE).get("clientAttributeKey"); Assert.assertEquals(new TsValue(dataPoint3.getLastUpdateTs(), dataPoint3.getValueAsString()), attrValue); - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint4 = new BaseAttributeKvEntry(now, new LongDataEntry("anyAttributeKey", 42L)); sendAttributes(device, TbAttributeSubscriptionScope.CLIENT_SCOPE, Arrays.asList(dataPoint4)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); eData = update.getUpdate(); @@ -733,10 +517,10 @@ public abstract class BaseWebsocketApiTest extends AbstractWebsocketTest { attrValue = eData.get(0).getLatest().get(EntityKeyType.ATTRIBUTE).get("anyAttributeKey"); Assert.assertEquals(new TsValue(dataPoint4.getLastUpdateTs(), dataPoint4.getValueAsString()), attrValue); - wsClient.registerWaitForUpdate(); + getWsClient().registerWaitForUpdate(); AttributeKvEntry dataPoint5 = new BaseAttributeKvEntry(now, new LongDataEntry("anyAttributeKey", 43L)); sendAttributes(device, TbAttributeSubscriptionScope.SERVER_SCOPE, Arrays.asList(dataPoint5)); - msg = wsClient.waitForUpdate(TimeUnit.SECONDS.toMillis(1)); + msg = getWsClient().waitForUpdate(TimeUnit.SECONDS.toMillis(1)); update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); eData = update.getUpdate(); diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseWidgetTypeControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseWidgetTypeControllerTest.java index bcb1a1abd4..c8ce3fa888 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseWidgetTypeControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseWidgetTypeControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/BaseWidgetsBundleControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/BaseWidgetsBundleControllerTest.java index 3167466d93..21acf5ee81 100644 --- a/application/src/test/java/org/thingsboard/server/controller/BaseWidgetsBundleControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/BaseWidgetsBundleControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/ControllerSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/controller/ControllerSqlTestSuite.java deleted file mode 100644 index 413955ca22..0000000000 --- a/application/src/test/java/org/thingsboard/server/controller/ControllerSqlTestSuite.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.controller; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ -// "org.thingsboard.server.controller.sql.WebsocketApiSqlTest", -// "org.thingsboard.server.controller.sql.EntityQueryControllerSqlTest", -// "org.thingsboard.server.controller.sql.TbResourceControllerSqlTest", -// "org.thingsboard.server.controller.sql.DeviceProfileControllerSqlTest", - "org.thingsboard.server.controller.sql.*Test", -}) -public class ControllerSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java b/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java index ff6b004405..be7973d517 100644 --- a/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java +++ b/application/src/test/java/org/thingsboard/server/controller/TbTestWebSocketClient.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,25 @@ package org.thingsboard.server.controller; import lombok.extern.slf4j.Slf4j; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.kv.Aggregation; +import org.thingsboard.server.common.data.query.EntityDataPageLink; +import org.thingsboard.server.common.data.query.EntityDataQuery; +import org.thingsboard.server.common.data.query.EntityFilter; +import org.thingsboard.server.common.data.query.EntityKey; +import org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityCountCmd; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityCountUpdate; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityHistoryCmd; +import org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd; +import org.thingsboard.server.service.telemetry.cmd.v2.TimeSeriesCmd; import java.net.URI; import java.nio.channels.NotYetConnectedException; +import java.util.Collections; +import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -28,8 +44,8 @@ import java.util.concurrent.TimeUnit; public class TbTestWebSocketClient extends WebSocketClient { private volatile String lastMsg; - private CountDownLatch reply; - private CountDownLatch update; + private volatile CountDownLatch reply; + private volatile CountDownLatch update; public TbTestWebSocketClient(URI serverUri) { super(serverUri); @@ -44,17 +60,17 @@ public class TbTestWebSocketClient extends WebSocketClient { public void onMessage(String s) { log.info("RECEIVED: {}", s); lastMsg = s; - if (reply != null) { - reply.countDown(); - } if (update != null) { update.countDown(); } + if (reply != null) { + reply.countDown(); + } } @Override public void onClose(int i, String s, boolean b) { - log.error("CLOSED:"); + log.info("CLOSED."); } @Override @@ -63,8 +79,12 @@ public class TbTestWebSocketClient extends WebSocketClient { } public void registerWaitForUpdate() { + registerWaitForUpdate(1); + } + + public void registerWaitForUpdate(int count) { lastMsg = null; - update = new CountDownLatch(1); + update = new CountDownLatch(count); } @Override @@ -73,6 +93,18 @@ public class TbTestWebSocketClient extends WebSocketClient { super.send(text); } + public void send(EntityDataCmd cmd) throws NotYetConnectedException { + TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); + wrapper.setEntityDataCmds(Collections.singletonList(cmd)); + this.send(JacksonUtil.toString(wrapper)); + } + + public void send(EntityCountCmd cmd) throws NotYetConnectedException { + TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); + wrapper.setEntityCountCmds(Collections.singletonList(cmd)); + this.send(JacksonUtil.toString(wrapper)); + } + public String waitForUpdate() { return waitForUpdate(TimeUnit.SECONDS.toMillis(3)); } @@ -94,4 +126,95 @@ public class TbTestWebSocketClient extends WebSocketClient { } return lastMsg; } + + public EntityDataUpdate parseDataReply(String msg) { + return JacksonUtil.fromString(msg, EntityDataUpdate.class); + } + + public EntityCountUpdate parseCountReply(String msg) { + return JacksonUtil.fromString(msg, EntityCountUpdate.class); + } + + public EntityDataUpdate subscribeLatestUpdate(List keys, EntityFilter entityFilter) { + EntityDataQuery edq = new EntityDataQuery(entityFilter, new EntityDataPageLink(1, 0, null, null), + Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + return subscribeLatestUpdate(keys, edq); + } + + public EntityDataUpdate subscribeLatestUpdate(List keys) { + return subscribeLatestUpdate(keys, (EntityDataQuery) null); + } + + public EntityDataUpdate subscribeLatestUpdate(List keys, EntityDataQuery edq) { + LatestValueCmd latestCmd = new LatestValueCmd(); + latestCmd.setKeys(keys); + EntityDataCmd cmd = new EntityDataCmd(1, edq, null, latestCmd, null); + send(cmd); + return parseDataReply(waitForReply()); + } + + public EntityDataUpdate subscribeTsUpdate(List keys, long startTs, long timeWindow) { + return subscribeTsUpdate(keys, startTs, timeWindow, (EntityDataQuery) null); + } + + public EntityDataUpdate subscribeTsUpdate(List keys, long startTs, long timeWindow, EntityFilter entityFilter) { + EntityDataQuery edq = new EntityDataQuery(entityFilter, new EntityDataPageLink(1, 0, null, null), + Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + return subscribeTsUpdate(keys, startTs, timeWindow, edq); + } + + public EntityDataUpdate subscribeTsUpdate(List keys, long startTs, long timeWindow, EntityDataQuery edq) { + TimeSeriesCmd tsCmd = new TimeSeriesCmd(); + tsCmd.setKeys(keys); + tsCmd.setAgg(Aggregation.NONE); + tsCmd.setLimit(1000); + tsCmd.setStartTs(startTs - timeWindow); + tsCmd.setTimeWindow(timeWindow); + + EntityDataCmd cmd = new EntityDataCmd(1, edq, null, null, tsCmd); + + send(cmd); + return parseDataReply(waitForReply()); + } + + public EntityDataUpdate sendHistoryCmd(List keys, long startTs, long timeWindow) { + return sendHistoryCmd(keys, startTs, timeWindow, (EntityDataQuery) null); + } + + public EntityDataUpdate sendHistoryCmd(List keys, long startTs, long timeWindow, EntityFilter entityFilter) { + EntityDataQuery edq = new EntityDataQuery(entityFilter, + new EntityDataPageLink(1, 0, null, null), + Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + return sendHistoryCmd(keys, startTs, timeWindow, edq); + } + + public EntityDataUpdate sendHistoryCmd(List keys, long startTs, long timeWindow, EntityDataQuery edq) { + EntityHistoryCmd historyCmd = new EntityHistoryCmd(); + historyCmd.setKeys(keys); + historyCmd.setAgg(Aggregation.NONE); + historyCmd.setLimit(1000); + historyCmd.setStartTs(startTs - timeWindow); + historyCmd.setEndTs(startTs); + + EntityDataCmd cmd = new EntityDataCmd(1, edq, historyCmd, null, null); + + send(cmd); + return parseDataReply(this.waitForReply()); + } + + public EntityDataUpdate sendEntityDataQuery(EntityDataQuery edq) { + log.warn("sendEntityDataQuery {}", edq); + EntityDataCmd cmd = new EntityDataCmd(1, edq, null, null, null); + send(cmd); + String msg = this.waitForReply(); + return parseDataReply(msg); + } + + public EntityDataUpdate sendEntityDataQuery(EntityFilter entityFilter) { + log.warn("sendEntityDataQuery {}", entityFilter); + EntityDataQuery edq = new EntityDataQuery(entityFilter, new EntityDataPageLink(1, 0, null, null), + Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); + return sendEntityDataQuery(edq); + } + } diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthConfigTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthConfigTest.java new file mode 100644 index 0000000000..db15e6fd82 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthConfigTest.java @@ -0,0 +1,475 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.controller; + +import org.jboss.aerogear.security.otp.Totp; +import org.jboss.aerogear.security.otp.api.Base32; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.cache.CacheManager; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.CacheConstants; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; +import org.thingsboard.server.common.data.security.model.mfa.account.AccountTwoFaSettings; +import org.thingsboard.server.common.data.security.model.mfa.account.SmsTwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.account.TotpTwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.account.TwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.SmsTwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TotpTwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; +import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; +import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; +import org.thingsboard.server.service.security.auth.mfa.provider.impl.OtpBasedTwoFaProvider; +import org.thingsboard.server.service.security.auth.mfa.provider.impl.TotpTwoFaProvider; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +public abstract class TwoFactorAuthConfigTest extends AbstractControllerTest { + + @SpyBean + private TotpTwoFaProvider totpTwoFactorAuthProvider; + @MockBean + private SmsService smsService; + @Autowired + private CacheManager cacheManager; + @Autowired + private TwoFaConfigManager twoFaConfigManager; + @SpyBean + private TwoFactorAuthService twoFactorAuthService; + + @Before + public void beforeEach() throws Exception { + doNothing().when(twoFactorAuthService).checkProvider(any(), any()); + loginSysAdmin(); + } + + @After + public void afterEach() { + twoFaConfigManager.deletePlatformTwoFaSettings(TenantId.SYS_TENANT_ID); + twoFaConfigManager.deletePlatformTwoFaSettings(tenantId); + } + + + @Test + public void testSavePlatformTwoFaSettings() throws Exception { + loginSysAdmin(); + + TotpTwoFaProviderConfig totpTwoFaProviderConfig = new TotpTwoFaProviderConfig(); + totpTwoFaProviderConfig.setIssuerName("tb"); + SmsTwoFaProviderConfig smsTwoFaProviderConfig = new SmsTwoFaProviderConfig(); + smsTwoFaProviderConfig.setSmsVerificationMessageTemplate("${code}"); + smsTwoFaProviderConfig.setVerificationCodeLifetime(60); + + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(List.of(totpTwoFaProviderConfig, smsTwoFaProviderConfig)); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + twoFaSettings.setVerificationCodeCheckRateLimit("3:900"); + twoFaSettings.setMaxVerificationFailuresBeforeUserLockout(10); + twoFaSettings.setTotalAllowedTimeForVerification(3600); + + doPost("/api/2fa/settings", twoFaSettings).andExpect(status().isOk()); + + PlatformTwoFaSettings savedTwoFaSettings = readResponse(doGet("/api/2fa/settings").andExpect(status().isOk()), PlatformTwoFaSettings.class); + + assertThat(savedTwoFaSettings.getProviders()).hasSize(2); + assertThat(savedTwoFaSettings.getProviders()).contains(totpTwoFaProviderConfig, smsTwoFaProviderConfig); + } + + @Test + public void testSavePlatformTwoFaSettings_validationError() throws Exception { + loginSysAdmin(); + + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(Collections.emptyList()); + twoFaSettings.setVerificationCodeCheckRateLimit("0:12"); + twoFaSettings.setMaxVerificationFailuresBeforeUserLockout(-1); + twoFaSettings.setTotalAllowedTimeForVerification(0); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + + String errorMessage = getErrorMessage(doPost("/api/2fa/settings", twoFaSettings) + .andExpect(status().isBadRequest())); + + assertThat(errorMessage).contains( + "verification code check rate limit configuration is invalid", + "maximum number of verification failure before user lockout must be positive", + "total amount of time allotted for verification must be greater than or equal 60" + ); + } + + @Test + public void testSaveTotpTwoFaProviderConfig_validationError() throws Exception { + TotpTwoFaProviderConfig invalidTotpTwoFaProviderConfig = new TotpTwoFaProviderConfig(); + invalidTotpTwoFaProviderConfig.setIssuerName(" "); + + String errorResponse = savePlatformTwoFaSettingsAndGetError(invalidTotpTwoFaProviderConfig); + assertThat(errorResponse).containsIgnoringCase("issuer name must not be blank"); + } + + @Test + public void testSaveSmsTwoFaProviderConfig_validationError() throws Exception { + SmsTwoFaProviderConfig invalidSmsTwoFaProviderConfig = new SmsTwoFaProviderConfig(); + invalidSmsTwoFaProviderConfig.setSmsVerificationMessageTemplate("does not contain verification code"); + invalidSmsTwoFaProviderConfig.setVerificationCodeLifetime(60); + + String errorResponse = savePlatformTwoFaSettingsAndGetError(invalidSmsTwoFaProviderConfig); + assertThat(errorResponse).containsIgnoringCase("must contain verification code"); + + invalidSmsTwoFaProviderConfig.setSmsVerificationMessageTemplate(null); + invalidSmsTwoFaProviderConfig.setVerificationCodeLifetime(0); + errorResponse = savePlatformTwoFaSettingsAndGetError(invalidSmsTwoFaProviderConfig); + assertThat(errorResponse).containsIgnoringCase("verification message template is required"); + assertThat(errorResponse).containsIgnoringCase("verification code lifetime is required"); + } + + private String savePlatformTwoFaSettingsAndGetError(TwoFaProviderConfig invalidTwoFaProviderConfig) throws Exception { + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(Collections.singletonList(invalidTwoFaProviderConfig)); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + twoFaSettings.setTotalAllowedTimeForVerification(100); + + return getErrorMessage(doPost("/api/2fa/settings", twoFaSettings) + .andExpect(status().isBadRequest())); + } + + + @Test + public void testSaveTwoFaAccountConfig_providerNotConfigured() throws Exception { + configureSmsTwoFaProvider("${code}"); + + loginTenantAdmin(); + + TwoFaProviderType notConfiguredProviderType = TwoFaProviderType.TOTP; + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config/generate?providerType=" + notConfiguredProviderType) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("provider is not configured"); + + TotpTwoFaAccountConfig notConfiguredProviderAccountConfig = new TotpTwoFaAccountConfig(); + notConfiguredProviderAccountConfig.setAuthUrl("otpauth://totp/aba:aba?issuer=aba&secret=ABA"); + errorMessage = getErrorMessage(doPost("/api/2fa/account/config/submit", notConfiguredProviderAccountConfig)); + assertThat(errorMessage).containsIgnoringCase("provider is not configured"); + } + + @Test + public void testGenerateTotpTwoFaAccountConfig() throws Exception { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = configureTotpTwoFaProvider(); + + loginTenantAdmin(); + + assertThat(readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), String.class)).isNullOrEmpty(); + generateTotpTwoFaAccountConfig(totpTwoFaProviderConfig); + } + + @Test + public void testSubmitTotpTwoFaAccountConfig() throws Exception { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = configureTotpTwoFaProvider(); + + loginTenantAdmin(); + + TotpTwoFaAccountConfig generatedTotpTwoFaAccountConfig = generateTotpTwoFaAccountConfig(totpTwoFaProviderConfig); + doPost("/api/2fa/account/config/submit", generatedTotpTwoFaAccountConfig).andExpect(status().isOk()); + verify(totpTwoFactorAuthProvider).prepareVerificationCode(argThat(user -> user.getEmail().equals(TENANT_ADMIN_EMAIL)), + eq(totpTwoFaProviderConfig), eq(generatedTotpTwoFaAccountConfig)); + } + + @Test + public void testSubmitTotpTwoFaAccountConfig_validationError() throws Exception { + configureTotpTwoFaProvider(); + + loginTenantAdmin(); + + TotpTwoFaAccountConfig totpTwoFaAccountConfig = new TotpTwoFaAccountConfig(); + totpTwoFaAccountConfig.setAuthUrl(null); + + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config/submit", totpTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("otp auth url cannot be blank"); + + totpTwoFaAccountConfig.setAuthUrl("otpauth://totp/T B: aba"); + errorMessage = getErrorMessage(doPost("/api/2fa/account/config/submit", totpTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("otp auth url is invalid"); + + totpTwoFaAccountConfig.setAuthUrl("otpauth://totp/ThingsBoard%20(Tenant):tenant@thingsboard.org?issuer=ThingsBoard+%28Tenant%29&secret=FUNBIM3CXFNNGQR6ZIPVWHP65PPFWDII"); + doPost("/api/2fa/account/config/submit", totpTwoFaAccountConfig) + .andExpect(status().isOk()); + } + + @Test + public void testVerifyAndSaveTotpTwoFaAccountConfig() throws Exception { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = configureTotpTwoFaProvider(); + + loginTenantAdmin(); + + TotpTwoFaAccountConfig generatedTotpTwoFaAccountConfig = generateTotpTwoFaAccountConfig(totpTwoFaProviderConfig); + generatedTotpTwoFaAccountConfig.setUseByDefault(true); + + String secret = UriComponentsBuilder.fromUriString(generatedTotpTwoFaAccountConfig.getAuthUrl()).build() + .getQueryParams().getFirst("secret"); + String correctVerificationCode = new Totp(secret).now(); + + doPost("/api/2fa/account/config?verificationCode=" + correctVerificationCode, generatedTotpTwoFaAccountConfig) + .andExpect(status().isOk()); + + AccountTwoFaSettings accountTwoFaSettings = readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class); + assertThat(accountTwoFaSettings.getConfigs()).size().isOne(); + + TwoFaAccountConfig twoFaAccountConfig = accountTwoFaSettings.getConfigs().get(TwoFaProviderType.TOTP); + assertThat(twoFaAccountConfig).isEqualTo(generatedTotpTwoFaAccountConfig); + } + + @Test + public void testVerifyAndSaveTotpTwoFaAccountConfig_incorrectVerificationCode() throws Exception { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = configureTotpTwoFaProvider(); + + loginTenantAdmin(); + + TotpTwoFaAccountConfig generatedTotpTwoFaAccountConfig = generateTotpTwoFaAccountConfig(totpTwoFaProviderConfig); + + String incorrectVerificationCode = "100000"; + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config?verificationCode=" + incorrectVerificationCode, generatedTotpTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + + assertThat(errorMessage).containsIgnoringCase("verification code is incorrect"); + } + + private TotpTwoFaAccountConfig generateTotpTwoFaAccountConfig(TotpTwoFaProviderConfig totpTwoFaProviderConfig) throws Exception { + TwoFaAccountConfig generatedTwoFaAccountConfig = readResponse(doPost("/api/2fa/account/config/generate?providerType=TOTP") + .andExpect(status().isOk()), TwoFaAccountConfig.class); + assertThat(generatedTwoFaAccountConfig).isInstanceOf(TotpTwoFaAccountConfig.class); + + assertThat(((TotpTwoFaAccountConfig) generatedTwoFaAccountConfig)).satisfies(accountConfig -> { + UriComponents otpAuthUrl = UriComponentsBuilder.fromUriString(accountConfig.getAuthUrl()).build(); + assertThat(otpAuthUrl.getScheme()).isEqualTo("otpauth"); + assertThat(otpAuthUrl.getHost()).isEqualTo("totp"); + assertThat(otpAuthUrl.getQueryParams().getFirst("issuer")).isEqualTo(totpTwoFaProviderConfig.getIssuerName()); + assertThat(otpAuthUrl.getPath()).isEqualTo("/%s:%s", totpTwoFaProviderConfig.getIssuerName(), TENANT_ADMIN_EMAIL); + assertThat(otpAuthUrl.getQueryParams().getFirst("secret")).satisfies(secretKey -> { + assertDoesNotThrow(() -> Base32.decode(secretKey)); + }); + }); + return (TotpTwoFaAccountConfig) generatedTwoFaAccountConfig; + } + + @Test + public void testGetTwoFaAccountConfig_whenProviderNotConfigured() throws Exception { + testVerifyAndSaveTotpTwoFaAccountConfig(); + assertThat(readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), + AccountTwoFaSettings.class).getConfigs()).isNotEmpty(); + + loginSysAdmin(); + saveProvidersConfigs(); + + loginTenantAdmin(); + + assertThat(readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class).getConfigs()) + .isEmpty(); + } + + @Test + public void testGenerateSmsTwoFaAccountConfig() throws Exception { + configureSmsTwoFaProvider("${code}"); + doPost("/api/2fa/account/config/generate?providerType=SMS") + .andExpect(status().isOk()); + } + + @Test + public void testSubmitSmsTwoFaAccountConfig() throws Exception { + String verificationMessageTemplate = "Here is your verification code: ${code}"; + configureSmsTwoFaProvider(verificationMessageTemplate); + + loginTenantAdmin(); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + smsTwoFaAccountConfig.setPhoneNumber("+38054159785"); + + doPost("/api/2fa/account/config/submit", smsTwoFaAccountConfig).andExpect(status().isOk()); + + String verificationCode = cacheManager.getCache(CacheConstants.TWO_FA_VERIFICATION_CODES_CACHE) + .get(tenantAdminUserId, OtpBasedTwoFaProvider.Otp.class).getValue(); + + verify(smsService).sendSms(eq(tenantId), any(), argThat(phoneNumbers -> { + return phoneNumbers[0].equals(smsTwoFaAccountConfig.getPhoneNumber()); + }), eq("Here is your verification code: " + verificationCode)); + } + + @Test + public void testSubmitSmsTwoFaAccountConfig_validationError() throws Exception { + configureSmsTwoFaProvider("${code}"); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + String blankPhoneNumber = ""; + smsTwoFaAccountConfig.setPhoneNumber(blankPhoneNumber); + + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config/submit", smsTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("phone number cannot be blank"); + + String nonE164PhoneNumber = "8754868"; + smsTwoFaAccountConfig.setPhoneNumber(nonE164PhoneNumber); + + errorMessage = getErrorMessage(doPost("/api/2fa/account/config/submit", smsTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("phone number is not of E.164 format"); + } + + @Test + public void testVerifyAndSaveSmsTwoFaAccountConfig() throws Exception { + configureSmsTwoFaProvider("${code}"); + + loginTenantAdmin(); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + smsTwoFaAccountConfig.setPhoneNumber("+38051889445"); + smsTwoFaAccountConfig.setUseByDefault(true); + + ArgumentCaptor verificationCodeCaptor = ArgumentCaptor.forClass(String.class); + doPost("/api/2fa/account/config/submit", smsTwoFaAccountConfig).andExpect(status().isOk()); + + verify(smsService).sendSms(eq(tenantId), any(), argThat(phoneNumbers -> { + return phoneNumbers[0].equals(smsTwoFaAccountConfig.getPhoneNumber()); + }), verificationCodeCaptor.capture()); + + String correctVerificationCode = verificationCodeCaptor.getValue(); + doPost("/api/2fa/account/config?verificationCode=" + correctVerificationCode, smsTwoFaAccountConfig) + .andExpect(status().isOk()); + + AccountTwoFaSettings accountTwoFaSettings = readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class); + TwoFaAccountConfig accountConfig = accountTwoFaSettings.getConfigs().get(TwoFaProviderType.SMS); + assertThat(accountConfig).isEqualTo(smsTwoFaAccountConfig); + } + + @Test + public void testVerifyAndSaveSmsTwoFaAccountConfig_incorrectVerificationCode() throws Exception { + configureSmsTwoFaProvider("${code}"); + + loginTenantAdmin(); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + smsTwoFaAccountConfig.setPhoneNumber("+38051889445"); + + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config?verificationCode=100000", smsTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("verification code is incorrect"); + } + + @Test + public void testVerifyAndSaveSmsTwoFaAccountConfig_differentAccountConfigs() throws Exception { + configureSmsTwoFaProvider("${code}"); + loginTenantAdmin(); + + SmsTwoFaAccountConfig initialSmsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + initialSmsTwoFaAccountConfig.setPhoneNumber("+38051889445"); + initialSmsTwoFaAccountConfig.setUseByDefault(true); + + ArgumentCaptor verificationCodeCaptor = ArgumentCaptor.forClass(String.class); + doPost("/api/2fa/account/config/submit", initialSmsTwoFaAccountConfig).andExpect(status().isOk()); + + verify(smsService).sendSms(eq(tenantId), any(), argThat(phoneNumbers -> { + return phoneNumbers[0].equals(initialSmsTwoFaAccountConfig.getPhoneNumber()); + }), verificationCodeCaptor.capture()); + + String correctVerificationCode = verificationCodeCaptor.getValue(); + + SmsTwoFaAccountConfig anotherSmsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + anotherSmsTwoFaAccountConfig.setPhoneNumber("+38111111111"); + String errorMessage = getErrorMessage(doPost("/api/2fa/account/config?verificationCode=" + correctVerificationCode, anotherSmsTwoFaAccountConfig) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("verification code is incorrect"); + + doPost("/api/2fa/account/config?verificationCode=" + correctVerificationCode, initialSmsTwoFaAccountConfig) + .andExpect(status().isOk()); + AccountTwoFaSettings accountTwoFaSettings = readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class); + TwoFaAccountConfig accountConfig = accountTwoFaSettings.getConfigs().get(TwoFaProviderType.SMS); + assertThat(accountConfig).isEqualTo(initialSmsTwoFaAccountConfig); + } + + private TotpTwoFaProviderConfig configureTotpTwoFaProvider() throws Exception { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = new TotpTwoFaProviderConfig(); + totpTwoFaProviderConfig.setIssuerName("tb"); + + saveProvidersConfigs(totpTwoFaProviderConfig); + return totpTwoFaProviderConfig; + } + + private SmsTwoFaProviderConfig configureSmsTwoFaProvider(String verificationMessageTemplate) throws Exception { + SmsTwoFaProviderConfig smsTwoFaProviderConfig = new SmsTwoFaProviderConfig(); + smsTwoFaProviderConfig.setSmsVerificationMessageTemplate(verificationMessageTemplate); + smsTwoFaProviderConfig.setVerificationCodeLifetime(60); + + saveProvidersConfigs(smsTwoFaProviderConfig); + return smsTwoFaProviderConfig; + } + + private void saveProvidersConfigs(TwoFaProviderConfig... providerConfigs) throws Exception { + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(Arrays.stream(providerConfigs).collect(Collectors.toList())); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + twoFaSettings.setTotalAllowedTimeForVerification(100); + doPost("/api/2fa/settings", twoFaSettings).andExpect(status().isOk()); + } + + @Test + public void testIsTwoFaEnabled() throws Exception { + configureSmsTwoFaProvider("${code}"); + SmsTwoFaAccountConfig accountConfig = new SmsTwoFaAccountConfig(); + accountConfig.setPhoneNumber("+38050505050"); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, tenantAdminUserId, accountConfig); + + assertThat(twoFactorAuthService.isTwoFaEnabled(tenantId, tenantAdminUserId)).isTrue(); + } + + @Test + public void testDeleteTwoFaAccountConfig() throws Exception { + configureSmsTwoFaProvider("${code}"); + SmsTwoFaAccountConfig accountConfig = new SmsTwoFaAccountConfig(); + accountConfig.setPhoneNumber("+38050505050"); + + loginTenantAdmin(); + + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, tenantAdminUserId, accountConfig); + + AccountTwoFaSettings accountTwoFaSettings = readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class); + TwoFaAccountConfig savedAccountConfig = accountTwoFaSettings.getConfigs().get(TwoFaProviderType.SMS); + assertThat(savedAccountConfig).isEqualTo(accountConfig); + + doDelete("/api/2fa/account/config?providerType=SMS").andExpect(status().isOk()); + + assertThat(readResponse(doGet("/api/2fa/account/settings").andExpect(status().isOk()), AccountTwoFaSettings.class).getConfigs()) + .doesNotContainKey(TwoFaProviderType.SMS); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java new file mode 100644 index 0000000000..9c30ebbbd0 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/TwoFactorAuthTest.java @@ -0,0 +1,447 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.controller; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.jboss.aerogear.security.otp.Totp; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.thingsboard.rule.engine.api.SmsService; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.audit.ActionStatus; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.audit.AuditLog; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.page.SortOrder; +import org.thingsboard.server.common.data.page.TimePageLink; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.data.security.model.mfa.PlatformTwoFaSettings; +import org.thingsboard.server.common.data.security.model.mfa.account.EmailTwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.account.SmsTwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.account.TotpTwoFaAccountConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.EmailTwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.SmsTwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TotpTwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderConfig; +import org.thingsboard.server.common.data.security.model.mfa.provider.TwoFaProviderType; +import org.thingsboard.server.dao.audit.AuditLogService; +import org.thingsboard.server.dao.user.UserService; +import org.thingsboard.server.service.security.auth.mfa.TwoFactorAuthService; +import org.thingsboard.server.service.security.auth.mfa.config.TwoFaConfigManager; +import org.thingsboard.server.service.security.auth.rest.LoginRequest; +import org.thingsboard.server.service.security.model.JwtTokenPair; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.verify; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +public abstract class TwoFactorAuthTest extends AbstractControllerTest { + + @Autowired + private TwoFaConfigManager twoFaConfigManager; + @SpyBean + private TwoFactorAuthService twoFactorAuthService; + @MockBean + private SmsService smsService; + @Autowired + private AuditLogService auditLogService; + @Autowired + private UserService userService; + + private User user; + private String username; + private String password; + + @Before + public void beforeEach() throws Exception { + username = "mfa@tb.io"; + password = "psswrd"; + + user = new User(); + user.setAuthority(Authority.TENANT_ADMIN); + user.setEmail(username); + user.setTenantId(tenantId); + + loginSysAdmin(); + user = createUser(user, password); + doNothing().when(twoFactorAuthService).checkProvider(any(), any()); + } + + @After + public void afterEach() { + twoFaConfigManager.deletePlatformTwoFaSettings(tenantId); + twoFaConfigManager.deletePlatformTwoFaSettings(TenantId.SYS_TENANT_ID); + } + + @Test + public void testTwoFa_totp() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + + logInWithPreVerificationToken(username, password); + + doPost("/api/auth/2fa/verification/send?providerType=TOTP") + .andExpect(status().isOk()); + + String correctVerificationCode = getCorrectTotp(totpTwoFaAccountConfig); + + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + correctVerificationCode) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + + User currentUser = readResponse(doGet("/api/auth/user") + .andExpect(status().isOk()), User.class); + assertThat(currentUser.getId()).isEqualTo(user.getId()); + } + + @Test + public void testTwoFa_sms() throws Exception { + configureSmsTwoFa(); + + logInWithPreVerificationToken(username, password); + + doPost("/api/auth/2fa/verification/send?providerType=SMS") + .andExpect(status().isOk()); + + ArgumentCaptor verificationCodeCaptor = ArgumentCaptor.forClass(String.class); + verify(smsService).sendSms(eq(tenantId), any(), any(), verificationCodeCaptor.capture()); + String correctVerificationCode = verificationCodeCaptor.getValue(); + + JsonNode tokenPair = readResponse(doPost("/api/auth/2fa/verification/check?providerType=SMS&verificationCode=" + correctVerificationCode) + .andExpect(status().isOk()), JsonNode.class); + validateAndSetJwtToken(tokenPair, username); + + User currentUser = readResponse(doGet("/api/auth/user") + .andExpect(status().isOk()), User.class); + assertThat(currentUser.getId()).isEqualTo(user.getId()); + } + + @Test + public void testTwoFaPreVerificationTokenLifetime() throws Exception { + configureTotpTwoFa(twoFaSettings -> { + twoFaSettings.setTotalAllowedTimeForVerification(65); + }); + + logInWithPreVerificationToken(username, password); + + await("expiration of the pre-verification token") + .atLeast(Duration.ofSeconds(30).plusMillis(500)) + .atMost(Duration.ofSeconds(70)) + .untilAsserted(() -> { + doPost("/api/auth/2fa/verification/send?providerType=TOTP") + .andExpect(status().isUnauthorized()); + }); + } + + @Test + public void testCheckVerificationCode_userBlocked() throws Exception { + configureTotpTwoFa(twoFaSettings -> { + twoFaSettings.setMaxVerificationFailuresBeforeUserLockout(10); + }); + + logInWithPreVerificationToken(username, password); + + Stream.generate(() -> RandomStringUtils.randomNumeric(6)) + .limit(9) + .forEach(incorrectVerificationCode -> { + try { + String errorMessage = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + incorrectVerificationCode) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("verification code is incorrect"); + } catch (Exception e) { + fail(); + } + }); + + String errorMessage = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + RandomStringUtils.randomNumeric(6)) + .andExpect(status().isUnauthorized())); + assertThat(errorMessage).containsIgnoringCase("account was locked due to exceeded 2fa verification attempts"); + + errorMessage = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + RandomStringUtils.randomNumeric(6)) + .andExpect(status().isUnauthorized())); + assertThat(errorMessage).containsIgnoringCase("user is disabled"); + } + + @Test + public void testSendVerificationCode_rateLimit() throws Exception { + configureTotpTwoFa(twoFaSettings -> { + twoFaSettings.setMinVerificationCodeSendPeriod(10); + }); + + logInWithPreVerificationToken(username, password); + + doPost("/api/auth/2fa/verification/send?providerType=TOTP") + .andExpect(status().isOk()); + + String rateLimitExceededError = getErrorMessage(doPost("/api/auth/2fa/verification/send?providerType=TOTP") + .andExpect(status().isTooManyRequests())); + assertThat(rateLimitExceededError).containsIgnoringCase("too many requests"); + + await("verification code sending rate limit resetting") + .atLeast(Duration.ofSeconds(8)) + .atMost(Duration.ofSeconds(12)) + .untilAsserted(() -> { + doPost("/api/auth/2fa/verification/send?providerType=TOTP") + .andExpect(status().isOk()); + }); + } + + @Test + public void testCheckVerificationCode_rateLimit() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(twoFaSettings -> { + twoFaSettings.setVerificationCodeCheckRateLimit("3:10"); + }); + + logInWithPreVerificationToken(username, password); + + for (int i = 0; i < 3; i++) { + String incorrectVerificationCodeError = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=incorrect") + .andExpect(status().isBadRequest())); + assertThat(incorrectVerificationCodeError).containsIgnoringCase("verification code is incorrect"); + } + + String rateLimitExceededError = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=incorrect") + .andExpect(status().isTooManyRequests())); + assertThat(rateLimitExceededError).containsIgnoringCase("too many requests"); + + await("verification code checking rate limit resetting") + .atLeast(Duration.ofSeconds(8)) + .atMost(Duration.ofSeconds(12)) + .untilAsserted(() -> { + String incorrectVerificationCodeError = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=incorrect") + .andExpect(status().isBadRequest())); + assertThat(incorrectVerificationCodeError).containsIgnoringCase("verification code is incorrect"); + }); + + doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()); + } + + @Test + public void testCheckVerificationCode_invalidVerificationCode() throws Exception { + configureTotpTwoFa(); + logInWithPreVerificationToken(username, password); + + for (String invalidVerificationCode : new String[]{"1234567", "ab1212", "12311 ", "oewkriwejqf"}) { + String errorMessage = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + invalidVerificationCode) + .andExpect(status().isBadRequest())); + assertThat(errorMessage).containsIgnoringCase("verification code is incorrect"); + } + } + + @Test + public void testCheckVerificationCode_codeExpiration() throws Exception { + configureSmsTwoFa(smsTwoFaProviderConfig -> { + smsTwoFaProviderConfig.setVerificationCodeLifetime(10); + }); + + logInWithPreVerificationToken(username, password); + + ArgumentCaptor verificationCodeCaptor = ArgumentCaptor.forClass(String.class); + doPost("/api/auth/2fa/verification/send?providerType=SMS").andExpect(status().isOk()); + verify(smsService).sendSms(eq(tenantId), any(), any(), verificationCodeCaptor.capture()); + + String correctVerificationCode = verificationCodeCaptor.getValue(); + + await("verification code expiration") + .pollDelay(10, TimeUnit.SECONDS) + .atLeast(10, TimeUnit.SECONDS) + .atMost(12, TimeUnit.SECONDS) + .untilAsserted(() -> { + String incorrectVerificationCodeError = getErrorMessage(doPost("/api/auth/2fa/verification/check?providerType=SMS&verificationCode=" + correctVerificationCode) + .andExpect(status().isBadRequest())); + assertThat(incorrectVerificationCodeError).containsIgnoringCase("verification code is incorrect"); + }); + } + + @Test + public void testTwoFa_logLoginAction() throws Exception { + TotpTwoFaAccountConfig totpTwoFaAccountConfig = configureTotpTwoFa(); + + logInWithPreVerificationToken(username, password); + await("async audit log saving").during(1, TimeUnit.SECONDS); + assertThat(getLogInAuditLogs()).isEmpty(); + assertThat(userService.findUserById(tenantId, user.getId()).getAdditionalInfo() + .get("lastLoginTs")).isNull(); + + doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=incorrect") + .andExpect(status().isBadRequest()); + + await("async audit log saving").atMost(1, TimeUnit.SECONDS) + .until(() -> getLogInAuditLogs().size() == 1); + assertThat(getLogInAuditLogs().get(0)).satisfies(failedLogInAuditLog -> { + assertThat(failedLogInAuditLog.getActionStatus()).isEqualTo(ActionStatus.FAILURE); + assertThat(failedLogInAuditLog.getActionFailureDetails()).containsIgnoringCase("verification code is incorrect"); + assertThat(failedLogInAuditLog.getUserName()).isEqualTo(username); + }); + + doPost("/api/auth/2fa/verification/check?providerType=TOTP&verificationCode=" + getCorrectTotp(totpTwoFaAccountConfig)) + .andExpect(status().isOk()); + await("async audit log saving").atMost(1, TimeUnit.SECONDS) + .until(() -> getLogInAuditLogs().size() == 2); + assertThat(getLogInAuditLogs().get(0)).satisfies(successfulLogInAuditLog -> { + assertThat(successfulLogInAuditLog.getActionStatus()).isEqualTo(ActionStatus.SUCCESS); + assertThat(successfulLogInAuditLog.getUserName()).isEqualTo(username); + }); + assertThat(userService.findUserById(tenantId, user.getId()).getAdditionalInfo() + .get("lastLoginTs").asLong()) + .isGreaterThan(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(3)); + } + + private List getLogInAuditLogs() { + return auditLogService.findAuditLogsByTenantIdAndUserId(tenantId, user.getId(), List.of(ActionType.LOGIN), + new TimePageLink(new PageLink(10, 0, null, new SortOrder("createdTime", SortOrder.Direction.DESC)), 0L, System.currentTimeMillis())).getData(); + } + + @Test + public void testAuthWithoutTwoFaAccountConfig() throws ThingsboardException { + configureTotpTwoFa(); + twoFaConfigManager.deleteTwoFaAccountConfig(tenantId, user.getId(), TwoFaProviderType.TOTP); + + assertDoesNotThrow(() -> { + login(username, password); + }); + } + + @Test + public void testTwoFa_multipleProviders() throws Exception { + PlatformTwoFaSettings platformTwoFaSettings = new PlatformTwoFaSettings(); + + TotpTwoFaProviderConfig totpTwoFaProviderConfig = new TotpTwoFaProviderConfig(); + totpTwoFaProviderConfig.setIssuerName("TB"); + + SmsTwoFaProviderConfig smsTwoFaProviderConfig = new SmsTwoFaProviderConfig(); + smsTwoFaProviderConfig.setVerificationCodeLifetime(60); + smsTwoFaProviderConfig.setSmsVerificationMessageTemplate("${code}"); + + EmailTwoFaProviderConfig emailTwoFaProviderConfig = new EmailTwoFaProviderConfig(); + emailTwoFaProviderConfig.setVerificationCodeLifetime(60); + + platformTwoFaSettings.setProviders(List.of(totpTwoFaProviderConfig, smsTwoFaProviderConfig, emailTwoFaProviderConfig)); + platformTwoFaSettings.setMinVerificationCodeSendPeriod(5); + platformTwoFaSettings.setTotalAllowedTimeForVerification(100); + twoFaConfigManager.savePlatformTwoFaSettings(TenantId.SYS_TENANT_ID, platformTwoFaSettings); + + User twoFaUser = new User(); + twoFaUser.setAuthority(Authority.TENANT_ADMIN); + twoFaUser.setTenantId(tenantId); + twoFaUser.setEmail("2fa@thingsboard.org"); + twoFaUser = createUserAndLogin(twoFaUser, "12345678"); + + TotpTwoFaAccountConfig totpTwoFaAccountConfig = (TotpTwoFaAccountConfig) twoFactorAuthService.generateNewAccountConfig(twoFaUser, TwoFaProviderType.TOTP); + totpTwoFaAccountConfig.setUseByDefault(true); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, twoFaUser.getId(), totpTwoFaAccountConfig); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + smsTwoFaAccountConfig.setPhoneNumber("+38012312322"); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, twoFaUser.getId(), smsTwoFaAccountConfig); + + EmailTwoFaAccountConfig emailTwoFaAccountConfig = new EmailTwoFaAccountConfig(); + emailTwoFaAccountConfig.setEmail(twoFaUser.getEmail()); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, twoFaUser.getId(), emailTwoFaAccountConfig); + + logInWithPreVerificationToken(twoFaUser.getEmail(), "12345678"); + + Map providersInfos = readResponse(doGet("/api/auth/2fa/providers").andExpect(status().isOk()), new TypeReference>() {}).stream() + .collect(Collectors.toMap(TwoFactorAuthController.TwoFaProviderInfo::getType, v -> v)); + + assertThat(providersInfos).size().isEqualTo(3); + + assertThat(providersInfos).containsKey(TwoFaProviderType.TOTP); + assertThat(providersInfos.get(TwoFaProviderType.TOTP).isDefault()).isTrue(); + + assertThat(providersInfos).containsKey(TwoFaProviderType.SMS); + assertThat(providersInfos.get(TwoFaProviderType.SMS).isDefault()).isFalse(); + + assertThat(providersInfos).containsKey(TwoFaProviderType.EMAIL); + assertThat(providersInfos.get(TwoFaProviderType.EMAIL).isDefault()).isFalse(); + } + + private void logInWithPreVerificationToken(String username, String password) throws Exception { + LoginRequest loginRequest = new LoginRequest(username, password); + + JwtTokenPair response = readResponse(doPost("/api/auth/login", loginRequest).andExpect(status().isOk()), JwtTokenPair.class); + assertThat(response.getToken()).isNotNull(); + assertThat(response.getRefreshToken()).isNull(); + assertThat(response.getScope()).isEqualTo(Authority.PRE_VERIFICATION_TOKEN); + + this.token = response.getToken(); + } + + private TotpTwoFaAccountConfig configureTotpTwoFa(Consumer... customizer) throws ThingsboardException { + TotpTwoFaProviderConfig totpTwoFaProviderConfig = new TotpTwoFaProviderConfig(); + totpTwoFaProviderConfig.setIssuerName("tb"); + + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(Arrays.stream(new TwoFaProviderConfig[]{totpTwoFaProviderConfig}).collect(Collectors.toList())); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + twoFaSettings.setTotalAllowedTimeForVerification(100); + Arrays.stream(customizer).forEach(c -> c.accept(twoFaSettings)); + twoFaConfigManager.savePlatformTwoFaSettings(TenantId.SYS_TENANT_ID, twoFaSettings); + + TotpTwoFaAccountConfig totpTwoFaAccountConfig = (TotpTwoFaAccountConfig) twoFactorAuthService.generateNewAccountConfig(user, TwoFaProviderType.TOTP); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, user.getId(), totpTwoFaAccountConfig); + return totpTwoFaAccountConfig; + } + + private SmsTwoFaAccountConfig configureSmsTwoFa(Consumer... customizer) throws ThingsboardException { + SmsTwoFaProviderConfig smsTwoFaProviderConfig = new SmsTwoFaProviderConfig(); + smsTwoFaProviderConfig.setVerificationCodeLifetime(60); + smsTwoFaProviderConfig.setSmsVerificationMessageTemplate("${code}"); + Arrays.stream(customizer).forEach(c -> c.accept(smsTwoFaProviderConfig)); + + PlatformTwoFaSettings twoFaSettings = new PlatformTwoFaSettings(); + twoFaSettings.setProviders(Arrays.stream(new TwoFaProviderConfig[]{smsTwoFaProviderConfig}).collect(Collectors.toList())); + twoFaSettings.setMinVerificationCodeSendPeriod(5); + twoFaSettings.setTotalAllowedTimeForVerification(100); + twoFaConfigManager.savePlatformTwoFaSettings(TenantId.SYS_TENANT_ID, twoFaSettings); + + SmsTwoFaAccountConfig smsTwoFaAccountConfig = new SmsTwoFaAccountConfig(); + smsTwoFaAccountConfig.setPhoneNumber("+38050505050"); + twoFaConfigManager.saveTwoFaAccountConfig(tenantId, user.getId(), smsTwoFaAccountConfig); + return smsTwoFaAccountConfig; + } + + private String getCorrectTotp(TotpTwoFaAccountConfig totpTwoFaAccountConfig) { + String secret = StringUtils.substringAfterLast(totpTwoFaAccountConfig.getAuthUrl(), "secret="); + return new Totp(secret).now(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/AdminControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/AdminControllerSqlTest.java index c9485ac254..7716312664 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/AdminControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/AdminControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/AlarmControllerSqlTest.java similarity index 71% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceTest.java rename to application/src/test/java/org/thingsboard/server/controller/sql/AlarmControllerSqlTest.java index 3ab5c72f43..bba390448c 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/AlarmControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.mqtt.claim.sql; +package org.thingsboard.server.controller.sql; +import org.thingsboard.server.controller.BaseAlarmControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.claim.AbstractMqttClaimDeviceTest; @DaoSqlTest -public class MqttClaimDeviceTest extends AbstractMqttClaimDeviceTest { +public class AlarmControllerSqlTest extends BaseAlarmControllerTest { } diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/AssetControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/AssetControllerSqlTest.java index 47b07d5984..a92577ff09 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/AssetControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/AssetControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/AuditLogControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/AuditLogControllerSqlTest.java index 27b4fe9184..b5451ff579 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/AuditLogControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/AuditLogControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/AuthControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/AuthControllerSqlTest.java index 8dcb8c9175..fc607f1b02 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/AuthControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/AuthControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/ComponentDescriptorControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/ComponentDescriptorControllerSqlTest.java index 8ebf01f48a..bb739f593c 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/ComponentDescriptorControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/ComponentDescriptorControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/CustomerControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/CustomerControllerSqlTest.java index 5889ede938..21cbb95df6 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/CustomerControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/CustomerControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/DashboardControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/DashboardControllerSqlTest.java index 3b783d3304..6bbb20e492 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/DashboardControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/DashboardControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/DeviceControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/DeviceControllerSqlTest.java index 9b536c44bb..361ee31cfd 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/DeviceControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/DeviceControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/DeviceProfileControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/DeviceProfileControllerSqlTest.java index 746f2fc871..01fcca2569 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/DeviceProfileControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/DeviceProfileControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/EdgeControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/EdgeControllerSqlTest.java index 0d1fa48f7e..07b644ded7 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/EdgeControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/EdgeControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/EdgeEventControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/EdgeEventControllerSqlTest.java index b38e00982f..e2778a4d2d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/EdgeEventControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/EdgeEventControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/EntityQueryControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/EntityQueryControllerSqlTest.java index 30841e3e0d..0065d9e807 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/EntityQueryControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/EntityQueryControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/EntityViewControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/EntityViewControllerSqlTest.java index 8e067946bf..206af6de7d 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/EntityViewControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/EntityViewControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/OtaPackageControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/OtaPackageControllerSqlTest.java index 92bd9ba9c6..0208a866da 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/OtaPackageControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/OtaPackageControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/RpcControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/RpcControllerTest.java index 2d2b58e41d..3ef18939b2 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/RpcControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/RpcControllerTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/RuleChainControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/RuleChainControllerSqlTest.java index bdc3e01de6..362209bc8e 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/RuleChainControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/RuleChainControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/TbResourceControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/TbResourceControllerSqlTest.java index dd2441e8f2..8eeb4fab1c 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/TbResourceControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/TbResourceControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/TenantControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/TenantControllerSqlTest.java index e0f5b98dc5..711d4cbb51 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/TenantControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/TenantControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/TenantProfileControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/TenantProfileControllerSqlTest.java index 2dedc8fab0..a36cb81776 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/TenantProfileControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/TenantProfileControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/claim/sql/CoapClaimDeviceSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthConfigSqlTest.java similarity index 70% rename from application/src/test/java/org/thingsboard/server/transport/coap/claim/sql/CoapClaimDeviceSqlTest.java rename to application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthConfigSqlTest.java index 9548009ec7..591f995e9d 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/claim/sql/CoapClaimDeviceSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthConfigSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.coap.claim.sql; +package org.thingsboard.server.controller.sql; -import org.thingsboard.server.transport.coap.claim.AbstractCoapClaimDeviceTest; import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.controller.TwoFactorAuthConfigTest; @DaoSqlTest -public class CoapClaimDeviceSqlTest extends AbstractCoapClaimDeviceTest { +public class TwoFactorAuthConfigSqlTest extends TwoFactorAuthConfigTest { } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceJsonTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthSqlTest.java similarity index 70% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceJsonTest.java rename to application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthSqlTest.java index 6206f9dc2b..62024fc64e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceJsonTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/TwoFactorAuthSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.mqtt.claim.sql; +package org.thingsboard.server.controller.sql; +import org.thingsboard.server.controller.TwoFactorAuthTest; import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.claim.AbstractMqttClaimJsonDeviceTest; @DaoSqlTest -public class MqttClaimDeviceJsonTest extends AbstractMqttClaimJsonDeviceTest { +public class TwoFactorAuthSqlTest extends TwoFactorAuthTest { } diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/UserControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/UserControllerSqlTest.java index 218c7b1cc3..a8f2073a9a 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/UserControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/UserControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/WebsocketApiSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/WebsocketApiSqlTest.java index 67edb99367..1e5e2a5804 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/WebsocketApiSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/WebsocketApiSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/WidgetTypeControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/WidgetTypeControllerSqlTest.java index eecc0f04d6..bc1e48dba2 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/WidgetTypeControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/WidgetTypeControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/controller/sql/WidgetsBundleControllerSqlTest.java b/application/src/test/java/org/thingsboard/server/controller/sql/WidgetsBundleControllerSqlTest.java index 1b882ead6a..e911f0392f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/sql/WidgetsBundleControllerSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/sql/WidgetsBundleControllerSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/edge/BaseEdgeTest.java b/application/src/test/java/org/thingsboard/server/edge/BaseEdgeTest.java index c412e86ec6..61bb53b060 100644 --- a/application/src/test/java/org/thingsboard/server/edge/BaseEdgeTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/BaseEdgeTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import com.google.gson.JsonObject; import com.google.protobuf.AbstractMessage; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageLite; -import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.awaitility.Awaitility; import org.junit.After; @@ -33,7 +32,9 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.DataConstants; @@ -42,6 +43,7 @@ import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityView; import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.TenantProfile; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.alarm.Alarm; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -56,6 +58,8 @@ import org.thingsboard.server.common.data.device.profile.AlarmRule; import org.thingsboard.server.common.data.device.profile.AllowCreateNewDevicesDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.DeviceProfileAlarm; import org.thingsboard.server.common.data.device.profile.DeviceProfileData; +import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadConfiguration; +import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.SimpleAlarmConditionSpec; import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.EdgeEvent; @@ -80,6 +84,7 @@ import org.thingsboard.server.common.data.rule.RuleNode; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; +import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.data.widget.WidgetType; import org.thingsboard.server.common.data.widget.WidgetsBundle; import org.thingsboard.server.common.transport.adaptor.JsonConverter; @@ -110,13 +115,13 @@ import org.thingsboard.server.gen.edge.v1.RuleChainMetadataUpdateMsg; import org.thingsboard.server.gen.edge.v1.RuleChainUpdateMsg; import org.thingsboard.server.gen.edge.v1.UpdateMsgType; import org.thingsboard.server.gen.edge.v1.UplinkMsg; +import org.thingsboard.server.gen.edge.v1.UplinkResponseMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsRequestMsg; import org.thingsboard.server.gen.edge.v1.UserCredentialsUpdateMsg; import org.thingsboard.server.gen.edge.v1.UserUpdateMsg; import org.thingsboard.server.gen.edge.v1.WidgetTypeUpdateMsg; import org.thingsboard.server.gen.edge.v1.WidgetsBundleUpdateMsg; import org.thingsboard.server.gen.transport.TransportProtos; -import org.thingsboard.server.cluster.TbClusterService; import java.util.ArrayList; import java.util.List; @@ -129,7 +134,9 @@ import java.util.concurrent.TimeUnit; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -@Slf4j +@TestPropertySource(properties = { + "edges.enabled=true", +}) abstract public class BaseEdgeTest extends AbstractControllerTest { private static final String CUSTOM_DEVICE_PROFILE_NAME = "Thermostat"; @@ -165,7 +172,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { tenantAdmin.setLastName("Downs"); tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); - // sleep 1 seconds to avoid CREDENTIALS updated message for the user + // sleep 0.5 second to avoid CREDENTIALS updated message for the user // user credentials is going to be stored and updated event pushed to edge notification service // while service will be processing this event edge could be already added and additional message will be pushed Thread.sleep(500); @@ -176,7 +183,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { edgeImitator.expectMessageAmount(13); edgeImitator.connect(); - testReceivedInitialData(); + verifyEdgeConnectionAndInitialData(); } @After @@ -187,55 +194,28 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { loginSysAdmin(); - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()) + doDelete("/api/tenant/" + savedTenant.getUuidId()) .andExpect(status().isOk()); } - @Test - public void test() throws Exception { - testDevices(); - - testAssets(); - - testRuleChains(); - - testDashboards(); - - testRelations(); - - testAlarms(); - - testEntityView(); - - testCustomerAndNewUser(); - - testWidgetsBundleAndWidgetType(); - - testTimeseries(); - - testAttributes(); - - testRpcCall(); - - testTimeseriesWithFailures(); - - testSendMessagesToCloud(); - } - private void installation() throws Exception { edge = doPost("/api/edge", constructEdge("Test Edge", "test"), Edge.class); - DeviceProfile deviceProfile = this.createDeviceProfile(CUSTOM_DEVICE_PROFILE_NAME, null); + MqttDeviceProfileTransportConfiguration transportConfiguration = new MqttDeviceProfileTransportConfiguration(); + transportConfiguration.setTransportPayloadTypeConfiguration(new JsonTransportPayloadConfiguration()); + + DeviceProfile deviceProfile = this.createDeviceProfile(CUSTOM_DEVICE_PROFILE_NAME, transportConfiguration); + extendDeviceProfileData(deviceProfile); doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Device savedDevice = saveDevice("Edge Device 1", CUSTOM_DEVICE_PROFILE_NAME); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + doPost("/api/edge/" + edge.getUuidId() + + "/device/" + savedDevice.getUuidId(), Device.class); Asset savedAsset = saveAsset("Edge Asset 1"); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/asset/" + savedAsset.getId().getId().toString(), Asset.class); + doPost("/api/edge/" + edge.getUuidId() + + "/asset/" + savedAsset.getUuidId(), Asset.class); } private void extendDeviceProfileData(DeviceProfile deviceProfile) { @@ -267,8 +247,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { profileData.setProvisionConfiguration(new AllowCreateNewDevicesDeviceProfileProvisionConfiguration("123")); } - private void testReceivedInitialData() throws Exception { - log.info("Checking received data"); + private void verifyEdgeConnectionAndInitialData() throws Exception { Assert.assertTrue(edgeImitator.waitForMessages()); EdgeConfiguration configuration = edgeImitator.getConfiguration(); @@ -283,7 +262,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { UUID deviceUUID = new UUID(deviceUpdateMsg.getIdMSB(), deviceUpdateMsg.getIdLSB()); Device device = doGet("/api/device/" + deviceUUID.toString(), Device.class); Assert.assertNotNull(device); - List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/devices?", + List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/devices?", new TypeReference>() {}, new PageLink(100)).getData(); Assert.assertTrue(edgeDevices.contains(device)); @@ -310,7 +289,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { UUID assetUUID = new UUID(assetUpdateMsg.getIdMSB(), assetUpdateMsg.getIdLSB()); Asset asset = doGet("/api/asset/" + assetUUID.toString(), Asset.class); Assert.assertNotNull(asset); - List edgeAssets = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/assets?", + List edgeAssets = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/assets?", new TypeReference>() {}, new PageLink(100)).getData(); Assert.assertTrue(edgeAssets.contains(asset)); @@ -323,15 +302,13 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { UUID ruleChainUUID = new UUID(ruleChainUpdateMsg.getIdMSB(), ruleChainUpdateMsg.getIdLSB()); RuleChain ruleChain = doGet("/api/ruleChain/" + ruleChainUUID.toString(), RuleChain.class); Assert.assertNotNull(ruleChain); - List edgeRuleChains = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/ruleChains?", + List edgeRuleChains = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/ruleChains?", new TypeReference>() {}, new PageLink(100)).getData(); Assert.assertTrue(edgeRuleChains.contains(ruleChain)); testAutoGeneratedCodeByProtobuf(ruleChainUpdateMsg); validateAdminSettings(); - - log.info("Received data checked"); } private void validateAdminSettings() throws JsonProcessingException { @@ -367,39 +344,54 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertNotNull(jsonNode.get("test")); } - private void testDevices() throws Exception { - log.info("Testing devices"); - + @Test + public void testDeviceProfiles() throws Exception { // 1 + DeviceProfile deviceProfile = this.createDeviceProfile("ONE_MORE_DEVICE_PROFILE", null); + extendDeviceProfileData(deviceProfile); edgeImitator.expectMessageAmount(1); - Device savedDevice = saveDevice("Edge Device 2", "Default"); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + deviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Assert.assertTrue(edgeImitator.waitForMessages()); AbstractMessage latestMessage = edgeImitator.getLatestMessage(); - Assert.assertTrue(latestMessage instanceof DeviceUpdateMsg); - DeviceUpdateMsg deviceUpdateMsg = (DeviceUpdateMsg) latestMessage; - Assert.assertEquals(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, deviceUpdateMsg.getMsgType()); - Assert.assertEquals(deviceUpdateMsg.getIdMSB(), savedDevice.getUuidId().getMostSignificantBits()); - Assert.assertEquals(deviceUpdateMsg.getIdLSB(), savedDevice.getUuidId().getLeastSignificantBits()); - Assert.assertEquals(deviceUpdateMsg.getName(), savedDevice.getName()); - Assert.assertEquals(deviceUpdateMsg.getType(), savedDevice.getType()); + Assert.assertTrue(latestMessage instanceof DeviceProfileUpdateMsg); + DeviceProfileUpdateMsg deviceProfileUpdateMsg = (DeviceProfileUpdateMsg) latestMessage; + Assert.assertEquals(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, deviceProfileUpdateMsg.getMsgType()); + Assert.assertEquals(deviceProfileUpdateMsg.getIdMSB(), deviceProfile.getUuidId().getMostSignificantBits()); + Assert.assertEquals(deviceProfileUpdateMsg.getIdLSB(), deviceProfile.getUuidId().getLeastSignificantBits()); // 2 edgeImitator.expectMessageAmount(1); - doDelete("/api/edge/" + edge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + doDelete("/api/deviceProfile/" + deviceProfile.getUuidId()) + .andExpect(status().isOk()); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); + Assert.assertTrue(latestMessage instanceof DeviceProfileUpdateMsg); + deviceProfileUpdateMsg = (DeviceProfileUpdateMsg) latestMessage; + Assert.assertEquals(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, deviceProfileUpdateMsg.getMsgType()); + Assert.assertEquals(deviceProfileUpdateMsg.getIdMSB(), deviceProfile.getUuidId().getMostSignificantBits()); + Assert.assertEquals(deviceProfileUpdateMsg.getIdLSB(), deviceProfile.getUuidId().getLeastSignificantBits()); + } + + @Test + public void testDevices() throws Exception { + // 1 + Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + + // 2 + edgeImitator.expectMessageAmount(1); + doDelete("/api/edge/" + edge.getUuidId() + + "/device/" + savedDevice.getUuidId(), Device.class); + Assert.assertTrue(edgeImitator.waitForMessages()); + AbstractMessage latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof DeviceUpdateMsg); - deviceUpdateMsg = (DeviceUpdateMsg) latestMessage; + DeviceUpdateMsg deviceUpdateMsg = (DeviceUpdateMsg) latestMessage; Assert.assertEquals(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, deviceUpdateMsg.getMsgType()); Assert.assertEquals(deviceUpdateMsg.getIdMSB(), savedDevice.getUuidId().getMostSignificantBits()); Assert.assertEquals(deviceUpdateMsg.getIdLSB(), savedDevice.getUuidId().getLeastSignificantBits()); // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/device/" + savedDevice.getId().getId().toString()) + doDelete("/api/device/" + savedDevice.getUuidId()) .andExpect(status().isOk()); // we should not get any message because device is not assigned to edge any more Assert.assertFalse(edgeImitator.waitForMessages(1)); @@ -407,8 +399,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 4 edgeImitator.expectMessageAmount(1); savedDevice = saveDevice("Edge Device 3", "Default"); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/device/" + savedDevice.getId().getId().toString(), Device.class); + doPost("/api/edge/" + edge.getUuidId() + + "/device/" + savedDevice.getUuidId(), Device.class); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof DeviceUpdateMsg); @@ -421,7 +413,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 5 edgeImitator.expectMessageAmount(1); - doDelete("/api/device/" + savedDevice.getId().getId().toString()) + doDelete("/api/device/" + savedDevice.getUuidId()) .andExpect(status().isOk()); // in this case we should get messages because device was assigned to edge Assert.assertTrue(edgeImitator.waitForMessages()); @@ -432,17 +424,49 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(deviceUpdateMsg.getIdMSB(), savedDevice.getUuidId().getMostSignificantBits()); Assert.assertEquals(deviceUpdateMsg.getIdLSB(), savedDevice.getUuidId().getLeastSignificantBits()); - log.info("Devices tested successfully"); } - private void testAssets() throws Exception { - log.info("Testing assets"); + @Test + public void testDeviceReachedMaximumAllowedOnCloud() throws Exception { + // update tenant profile configuration + loginSysAdmin(); + TenantProfile tenantProfile = doGet("/api/tenantProfile/" + savedTenant.getTenantProfileId().getId(), TenantProfile.class); + DefaultTenantProfileConfiguration profileConfiguration = + (DefaultTenantProfileConfiguration) tenantProfile.getProfileData().getConfiguration(); + profileConfiguration.setMaxDevices(1); + tenantProfile.getProfileData().setConfiguration(profileConfiguration); + doPost("/api/tenantProfile/", tenantProfile, TenantProfile.class); + + loginTenantAdmin(); + + UUID uuid = Uuids.timeBased(); + + UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); + DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder(); + deviceUpdateMsgBuilder.setIdMSB(uuid.getMostSignificantBits()); + deviceUpdateMsgBuilder.setIdLSB(uuid.getLeastSignificantBits()); + deviceUpdateMsgBuilder.setName("Edge Device"); + deviceUpdateMsgBuilder.setType("default"); + deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE); + uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build()); + + edgeImitator.expectResponsesAmount(1); + + edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build()); + + Assert.assertTrue(edgeImitator.waitForResponses()); + + UplinkResponseMsg latestResponseMsg = edgeImitator.getLatestResponseMsg(); + Assert.assertTrue(latestResponseMsg.getSuccess()); + } + @Test + public void testAssets() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Asset savedAsset = saveAsset("Edge Asset 2"); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/asset/" + savedAsset.getId().getId().toString(), Asset.class); + doPost("/api/edge/" + edge.getUuidId() + + "/asset/" + savedAsset.getUuidId(), Asset.class); Assert.assertTrue(edgeImitator.waitForMessages()); AbstractMessage latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof AssetUpdateMsg); @@ -455,8 +479,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 2 edgeImitator.expectMessageAmount(1); - doDelete("/api/edge/" + edge.getId().getId().toString() - + "/asset/" + savedAsset.getId().getId().toString(), Asset.class); + doDelete("/api/edge/" + edge.getUuidId() + + "/asset/" + savedAsset.getUuidId(), Asset.class); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof AssetUpdateMsg); @@ -467,15 +491,15 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/asset/" + savedAsset.getId().getId().toString()) + doDelete("/api/asset/" + savedAsset.getUuidId()) .andExpect(status().isOk()); Assert.assertFalse(edgeImitator.waitForMessages(1)); // 4 edgeImitator.expectMessageAmount(1); savedAsset = saveAsset("Edge Asset 3"); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/asset/" + savedAsset.getId().getId().toString(), Asset.class); + doPost("/api/edge/" + edge.getUuidId() + + "/asset/" + savedAsset.getUuidId(), Asset.class); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof AssetUpdateMsg); @@ -488,7 +512,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 5 edgeImitator.expectMessageAmount(1); - doDelete("/api/asset/" + savedAsset.getId().getId().toString()) + doDelete("/api/asset/" + savedAsset.getUuidId()) .andExpect(status().isOk()); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); @@ -497,21 +521,18 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, assetUpdateMsg.getMsgType()); Assert.assertEquals(assetUpdateMsg.getIdMSB(), savedAsset.getUuidId().getMostSignificantBits()); Assert.assertEquals(assetUpdateMsg.getIdLSB(), savedAsset.getUuidId().getLeastSignificantBits()); - - log.info("Assets tested successfully"); } - private void testRuleChains() throws Exception { - log.info("Testing RuleChains"); - + @Test + public void testRuleChains() throws Exception { // 1 edgeImitator.expectMessageAmount(2); RuleChain ruleChain = new RuleChain(); ruleChain.setName("Edge Test Rule Chain"); ruleChain.setType(RuleChainType.EDGE); RuleChain savedRuleChain = doPost("/api/ruleChain", ruleChain, RuleChain.class); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/ruleChain/" + savedRuleChain.getId().getId().toString(), RuleChain.class); + doPost("/api/edge/" + edge.getUuidId() + + "/ruleChain/" + savedRuleChain.getUuidId(), RuleChain.class); createRuleChainMetadata(savedRuleChain); Assert.assertTrue(edgeImitator.waitForMessages()); Optional ruleChainUpdateMsgOpt = edgeImitator.findMessageByType(RuleChainUpdateMsg.class); @@ -528,8 +549,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/edge/" + edge.getId().getId().toString() - + "/ruleChain/" + savedRuleChain.getId().getId().toString(), RuleChain.class); + doDelete("/api/edge/" + edge.getUuidId() + + "/ruleChain/" + savedRuleChain.getUuidId(), RuleChain.class); Assert.assertTrue(edgeImitator.waitForMessages()); ruleChainUpdateMsgOpt = edgeImitator.findMessageByType(RuleChainUpdateMsg.class); Assert.assertTrue(ruleChainUpdateMsgOpt.isPresent()); @@ -540,11 +561,9 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 4 edgeImitator.expectMessageAmount(1); - doDelete("/api/ruleChain/" + savedRuleChain.getId().getId().toString()) + doDelete("/api/ruleChain/" + savedRuleChain.getUuidId()) .andExpect(status().isOk()); Assert.assertFalse(edgeImitator.waitForMessages(1)); - - log.info("RuleChains tested successfully"); } private void testRuleChainMetadataRequestMsg(RuleChainId ruleChainId) throws Exception { @@ -603,21 +622,18 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { ruleChainMetaData.addConnectionInfo(0, 2, "fail"); ruleChainMetaData.addConnectionInfo(1, 2, "success"); - ruleChainMetaData.addRuleChainConnectionInfo(2, edge.getRootRuleChainId(), "success", mapper.createObjectNode()); - doPost("/api/ruleChain/metadata", ruleChainMetaData, RuleChainMetaData.class); } - private void testDashboards() throws Exception { - log.info("Testing Dashboards"); - + @Test + public void testDashboards() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Dashboard dashboard = new Dashboard(); dashboard.setTitle("Edge Test Dashboard"); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); + doPost("/api/edge/" + edge.getUuidId() + + "/dashboard/" + savedDashboard.getUuidId(), Dashboard.class); Assert.assertTrue(edgeImitator.waitForMessages()); AbstractMessage latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof DashboardUpdateMsg); @@ -641,8 +657,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/edge/" + edge.getId().getId().toString() - + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); + doDelete("/api/edge/" + edge.getUuidId() + + "/dashboard/" + savedDashboard.getUuidId(), Dashboard.class); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof DashboardUpdateMsg); @@ -653,16 +669,13 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 4 edgeImitator.expectMessageAmount(1); - doDelete("/api/dashboard/" + savedDashboard.getId().getId().toString()) + doDelete("/api/dashboard/" + savedDashboard.getUuidId()) .andExpect(status().isOk()); Assert.assertFalse(edgeImitator.waitForMessages(1)); - - log.info("Dashboards tested successfully"); } - private void testRelations() throws Exception { - log.info("Testing Relations"); - + @Test + public void testRelations() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Device device = findDeviceByName("Edge Device 1"); @@ -710,13 +723,10 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(relationUpdateMsg.getToIdLSB(), relation.getTo().getId().getLeastSignificantBits()); Assert.assertEquals(relationUpdateMsg.getToEntityType(), relation.getTo().getEntityType().name()); Assert.assertEquals(relationUpdateMsg.getTypeGroup(), relation.getTypeGroup().name()); - - log.info("Relations tested successfully"); } - private void testAlarms() throws Exception { - log.info("Testing Alarms"); - + @Test + public void testAlarms() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Device device = findDeviceByName("Edge Device 1"); @@ -739,7 +749,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 2 edgeImitator.expectMessageAmount(1); - doPost("/api/alarm/" + savedAlarm.getId().getId().toString() + "/ack"); + doPost("/api/alarm/" + savedAlarm.getUuidId() + "/ack"); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof AlarmUpdateMsg); @@ -752,7 +762,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doPost("/api/alarm/" + savedAlarm.getId().getId().toString() + "/clear"); + doPost("/api/alarm/" + savedAlarm.getUuidId() + "/clear"); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof AlarmUpdateMsg); @@ -765,7 +775,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 4 edgeImitator.expectMessageAmount(1); - doDelete("/api/alarm/" + savedAlarm.getId().getId().toString()) + doDelete("/api/alarm/" + savedAlarm.getUuidId()) .andExpect(status().isOk()); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); @@ -776,13 +786,10 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(alarmUpdateMsg.getName(), savedAlarm.getName()); Assert.assertEquals(alarmUpdateMsg.getOriginatorName(), device.getName()); Assert.assertEquals(alarmUpdateMsg.getStatus(), AlarmStatus.CLEARED_ACK.name()); - - log.info("Alarms tested successfully"); } - private void testEntityView() throws Exception { - log.info("Testing EntityView"); - + @Test + public void testEntityView() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Device device = findDeviceByName("Edge Device 1"); @@ -791,8 +798,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { entityView.setType("test"); entityView.setEntityId(device.getId()); EntityView savedEntityView = doPost("/api/entityView", entityView, EntityView.class); - doPost("/api/edge/" + edge.getId().getId().toString() - + "/entityView/" + savedEntityView.getId().getId().toString(), EntityView.class); + doPost("/api/edge/" + edge.getUuidId() + + "/entityView/" + savedEntityView.getUuidId(), EntityView.class); Assert.assertTrue(edgeImitator.waitForMessages()); verifyEntityViewUpdateMsg(savedEntityView, device); @@ -818,8 +825,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/edge/" + edge.getId().getId().toString() - + "/entityView/" + savedEntityView.getId().getId().toString(), EntityView.class); + doDelete("/api/edge/" + edge.getUuidId() + + "/entityView/" + savedEntityView.getUuidId(), EntityView.class); Assert.assertTrue(edgeImitator.waitForMessages()); AbstractMessage latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof EntityViewUpdateMsg); @@ -830,11 +837,9 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { edgeImitator.expectMessageAmount(1); - doDelete("/api/entityView/" + savedEntityView.getId().getId().toString()) + doDelete("/api/entityView/" + savedEntityView.getUuidId()) .andExpect(status().isOk()); Assert.assertFalse(edgeImitator.waitForMessages(1)); - - log.info("EntityView tested successfully"); } private void verifyEntityViewUpdateMsg(EntityView entityView, Device device) { @@ -851,16 +856,15 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(entityViewUpdateMsg.getEntityType().name(), device.getId().getEntityType().name()); } - private void testCustomerAndNewUser() throws Exception { - log.info("Testing Customer"); - + @Test + public void testCustomerAndNewUser() throws Exception { // 1 edgeImitator.expectMessageAmount(1); Customer customer = new Customer(); customer.setTitle("Edge Customer 1"); Customer savedCustomer = doPost("/api/customer", customer, Customer.class); - doPost("/api/customer/" + savedCustomer.getId().getId().toString() - + "/edge/" + edge.getId().getId().toString(), Edge.class); + doPost("/api/customer/" + savedCustomer.getUuidId() + + "/edge/" + edge.getUuidId(), Edge.class); Assert.assertTrue(edgeImitator.waitForMessages()); AbstractMessage latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof CustomerUpdateMsg); @@ -893,7 +897,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/customer/edge/" + edge.getId().getId().toString(), Edge.class); + doDelete("/api/customer/edge/" + edge.getUuidId(), Edge.class); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); Assert.assertTrue(latestMessage instanceof CustomerUpdateMsg); @@ -903,16 +907,13 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(customerUpdateMsg.getIdLSB(), savedCustomer.getUuidId().getLeastSignificantBits()); edgeImitator.expectMessageAmount(1); - doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) + doDelete("/api/customer/" + savedCustomer.getUuidId()) .andExpect(status().isOk()); Assert.assertFalse(edgeImitator.waitForMessages(1)); - - log.info("Customer tested successfully"); } - private void testWidgetsBundleAndWidgetType() throws Exception { - log.info("Testing WidgetsBundle and WidgetType"); - + @Test + public void testWidgetsBundleAndWidgetType() throws Exception { // 1 edgeImitator.expectMessageAmount(1); WidgetsBundle widgetsBundle = new WidgetsBundle(); @@ -951,7 +952,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 3 edgeImitator.expectMessageAmount(1); - doDelete("/api/widgetType/" + savedWidgetType.getId().getId().toString()) + doDelete("/api/widgetType/" + savedWidgetType.getUuidId()) .andExpect(status().isOk()); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); @@ -963,7 +964,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { // 4 edgeImitator.expectMessageAmount(1); - doDelete("/api/widgetsBundle/" + savedWidgetsBundle.getId().getId().toString()) + doDelete("/api/widgetsBundle/" + savedWidgetsBundle.getUuidId()) .andExpect(status().isOk()); Assert.assertTrue(edgeImitator.waitForMessages()); latestMessage = edgeImitator.getLatestMessage(); @@ -972,19 +973,16 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE, widgetsBundleUpdateMsg.getMsgType()); Assert.assertEquals(widgetsBundleUpdateMsg.getIdMSB(), savedWidgetsBundle.getUuidId().getMostSignificantBits()); Assert.assertEquals(widgetsBundleUpdateMsg.getIdLSB(), savedWidgetsBundle.getUuidId().getLeastSignificantBits()); - - log.info("WidgetsBundle and WidgetType tested successfully"); } - private void testTimeseries() throws Exception { - log.info("Testing timeseries"); - + @Test + public void testTimeseries() throws Exception { edgeImitator.expectMessageAmount(1); Device device = findDeviceByName("Edge Device 1"); String timeseriesData = "{\"data\":{\"temperature\":25},\"ts\":" + System.currentTimeMillis() + "}"; JsonNode timeseriesEntityData = mapper.readTree(timeseriesData); EdgeEvent edgeEvent = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.TIMESERIES_UPDATED, device.getId().getId(), EdgeEventType.DEVICE, timeseriesEntityData); - edgeEventService.save(edgeEvent); + edgeEventService.saveAsync(edgeEvent).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); Assert.assertTrue(edgeImitator.waitForMessages()); @@ -1004,26 +1002,23 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { TransportProtos.KeyValueProto keyValueProto = tsKvListProto.getKv(0); Assert.assertEquals("temperature", keyValueProto.getKey()); Assert.assertEquals(25, keyValueProto.getLongV()); - log.info("Timeseries tested successfully"); } - private void testAttributes() throws Exception { - log.info("Testing attributes"); + @Test + public void testAttributes() throws Exception { Device device = findDeviceByName("Edge Device 1"); testAttributesUpdatedMsg(device); testPostAttributesMsg(device); testAttributesDeleteMsg(device); - - log.info("Attributes tested successfully"); } - private void testAttributesUpdatedMsg(Device device) throws JsonProcessingException, InterruptedException { + private void testAttributesUpdatedMsg(Device device) throws Exception { String attributesData = "{\"scope\":\"SERVER_SCOPE\",\"kv\":{\"key1\":\"value1\"}}"; JsonNode attributesEntityData = mapper.readTree(attributesData); EdgeEvent edgeEvent1 = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.ATTRIBUTES_UPDATED, device.getId().getId(), EdgeEventType.DEVICE, attributesEntityData); edgeImitator.expectMessageAmount(1); - edgeEventService.save(edgeEvent1); + edgeEventService.saveAsync(edgeEvent1).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); Assert.assertTrue(edgeImitator.waitForMessages()); @@ -1043,12 +1038,12 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals("value1", keyValueProto.getStringV()); } - private void testPostAttributesMsg(Device device) throws JsonProcessingException, InterruptedException { + private void testPostAttributesMsg(Device device) throws Exception { String postAttributesData = "{\"scope\":\"SERVER_SCOPE\",\"kv\":{\"key2\":\"value2\"}}"; JsonNode postAttributesEntityData = mapper.readTree(postAttributesData); EdgeEvent edgeEvent = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.POST_ATTRIBUTES, device.getId().getId(), EdgeEventType.DEVICE, postAttributesEntityData); edgeImitator.expectMessageAmount(1); - edgeEventService.save(edgeEvent); + edgeEventService.saveAsync(edgeEvent).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); Assert.assertTrue(edgeImitator.waitForMessages()); @@ -1068,12 +1063,12 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals("value2", keyValueProto.getStringV()); } - private void testAttributesDeleteMsg(Device device) throws JsonProcessingException, InterruptedException { + private void testAttributesDeleteMsg(Device device) throws Exception { String deleteAttributesData = "{\"scope\":\"SERVER_SCOPE\",\"keys\":[\"key1\",\"key2\"]}"; JsonNode deleteAttributesEntityData = mapper.readTree(deleteAttributesData); EdgeEvent edgeEvent = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.ATTRIBUTES_DELETED, device.getId().getId(), EdgeEventType.DEVICE, deleteAttributesEntityData); edgeImitator.expectMessageAmount(1); - edgeEventService.save(edgeEvent); + edgeEventService.saveAsync(edgeEvent).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); Assert.assertTrue(edgeImitator.waitForMessages()); @@ -1094,7 +1089,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals("key2", attributeDeleteMsg.getAttributeNames(1)); } - private void testRpcCall() throws Exception { + @Test + public void testRpcCall() throws Exception { Device device = findDeviceByName("Edge Device 1"); ObjectNode body = mapper.createObjectNode(); @@ -1107,7 +1103,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { EdgeEvent edgeEvent = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.RPC_CALL, device.getId().getId(), EdgeEventType.DEVICE, body); edgeImitator.expectMessageAmount(1); - edgeEventService.save(edgeEvent); + edgeEventService.saveAsync(edgeEvent).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); Assert.assertTrue(edgeImitator.waitForMessages()); @@ -1117,9 +1113,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals("test_method", latestDeviceRpcCallMsg.getRequestMsg().getMethod()); } - private void testTimeseriesWithFailures() throws Exception { - log.info("Testing timeseries with failures"); - + @Test + public void testTimeseriesWithFailures() throws Exception { int numberOfTimeseriesToSend = 1000; edgeImitator.setRandomFailuresOnTimeseriesDownlink(true); @@ -1133,11 +1128,11 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { JsonNode timeseriesEntityData = mapper.readTree(timeseriesData); EdgeEvent edgeEvent = constructEdgeEvent(tenantId, edge.getId(), EdgeEventActionType.TIMESERIES_UPDATED, device.getId().getId(), EdgeEventType.DEVICE, timeseriesEntityData); - edgeEventService.save(edgeEvent); + edgeEventService.saveAsync(edgeEvent).get(); clusterService.onEdgeEventUpdate(tenantId, edge.getId()); } - Assert.assertTrue(edgeImitator.waitForMessages(60)); + Assert.assertTrue(edgeImitator.waitForMessages(120)); List allTelemetryMsgs = edgeImitator.findAllMessagesByType(EntityDataProto.class); Assert.assertEquals(numberOfTimeseriesToSend, allTelemetryMsgs.size()); @@ -1147,7 +1142,6 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { } edgeImitator.setRandomFailuresOnTimeseriesDownlink(false); - log.info("Timeseries with failures tested successfully"); } private boolean isIdxExistsInTheDownlinkList(int idx, List allTelemetryMsgs) { @@ -1165,25 +1159,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { return false; } - private void testSendMessagesToCloud() throws Exception { - log.info("Sending messages to cloud"); - sendDevice(); - sendDeviceWithNameThatAlreadyExistsOnCloud(); - sendRelationRequest(); - sendAlarm(); - sendTelemetry(); - sendRelation(); - sendDeleteDeviceOnEdge(); - sendRuleChainMetadataRequest(); - sendUserCredentialsRequest(); - sendDeviceCredentialsRequest(); - sendDeviceRpcResponse(); - sendDeviceCredentialsUpdate(); - sendAttributesRequest(); - log.info("Messages were sent successfully"); - } - - private void sendDevice() throws Exception { + @Test + public void testSendDeviceToCloud() throws Exception { UUID uuid = Uuids.timeBased(); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); @@ -1218,7 +1195,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals("Edge Device 2", device.getName()); } - private void sendDeviceWithNameThatAlreadyExistsOnCloud() throws Exception { + @Test + public void testSendDeviceToCloudWithNameThatAlreadyExistsOnCloud() throws Exception { String deviceOnCloudName = RandomStringUtils.randomAlphanumeric(15); Device deviceOnCloud = saveDevice(deviceOnCloudName, "Default"); @@ -1270,7 +1248,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertNotEquals(deviceOnCloudName, device.getName()); } - private void sendRelationRequest() throws Exception { + @Test + public void testSendRelationRequestToCloud() throws Exception { Device device = findDeviceByName("Edge Device 1"); Asset asset = findAssetByName("Edge Asset 1"); @@ -1317,8 +1296,9 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(relation.getTypeGroup().name(), relationUpdateMsg.getTypeGroup()); } - private void sendAlarm() throws Exception { - Device device = findDeviceByName("Edge Device 2"); + @Test + public void testSendAlarmToCloud() throws Exception { + Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); AlarmUpdateMsg.Builder alarmUpdateMgBuilder = AlarmUpdateMsg.newBuilder(); @@ -1339,7 +1319,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { List alarms = doGetTypedWithPageLink("/api/alarm/{entityType}/{entityId}?", new TypeReference>() {}, - new PageLink(100), device.getId().getEntityType().name(), device.getId().getId().toString()) + new PageLink(100), device.getId().getEntityType().name(), device.getUuidId()) .getData(); Optional foundAlarm = alarms.stream().filter(alarm -> alarm.getType().equals("alarm from edge")).findAny(); Assert.assertTrue(foundAlarm.isPresent()); @@ -1349,12 +1329,9 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(AlarmSeverity.CRITICAL, alarmInfo.getSeverity()); } - private void sendTelemetry() throws Exception { - List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/devices?", - new TypeReference>() {}, new PageLink(100)).getData(); - Optional foundDevice = edgeDevices.stream().filter(device1 -> device1.getName().equals("Edge Device 2")).findAny(); - Assert.assertTrue(foundDevice.isPresent()); - Device device = foundDevice.get(); + @Test + public void testSendTelemetryToCloud() throws Exception { + Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); edgeImitator.expectResponsesAmount(2); @@ -1402,7 +1379,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(1, timeseries.get(timeseriesKey).size()); Assert.assertEquals(timeseriesValue, timeseries.get(timeseriesKey).get(0).get("value")); - List> attributes = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + device.getId() + "/values/attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {}); + String attributeValuesUrl = "/api/plugins/telemetry/DEVICE/" + device.getId() + "/values/attributes/" + DataConstants.SERVER_SCOPE; + List> attributes = doGetAsyncTyped(attributeValuesUrl, new TypeReference<>() {}); Assert.assertEquals(2, attributes.size()); var result = attributes.stream().filter(kv -> kv.get("key").equals(attributesKey)).filter(kv -> kv.get("value").equals(attributesValue)).findFirst(); Assert.assertTrue(result.isPresent()); @@ -1413,15 +1391,10 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { new TypeReference<>() {}); } - private void sendRelation() throws Exception { - List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/devices?", - new TypeReference>() {}, new PageLink(100)).getData(); - Optional foundDevice1 = edgeDevices.stream().filter(device1 -> device1.getName().equals("Edge Device 1")).findAny(); - Assert.assertTrue(foundDevice1.isPresent()); - Device device1 = foundDevice1.get(); - Optional foundDevice2 = edgeDevices.stream().filter(device2 -> device2.getName().equals("Edge Device 2")).findAny(); - Assert.assertTrue(foundDevice2.isPresent()); - Device device2 = foundDevice2.get(); + @Test + public void testSendRelationToCloud() throws Exception { + Device device1 = saveDeviceOnCloudAndVerifyDeliveryToEdge(); + Device device2 = saveDeviceOnCloudAndVerifyDeliveryToEdge(); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); RelationUpdateMsg.Builder relationUpdateMsgBuilder = RelationUpdateMsg.newBuilder(); @@ -1444,17 +1417,18 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertTrue(edgeImitator.waitForResponses()); EntityRelation relation = doGet("/api/relation?" + - "&fromId=" + device2.getId().getId().toString() + + "&fromId=" + device2.getUuidId() + "&fromType=" + device2.getId().getEntityType().name() + "&relationType=" + "test" + "&relationTypeGroup=" + RelationTypeGroup.COMMON.name() + - "&toId=" + device1.getId().getId().toString() + + "&toId=" + device1.getUuidId() + "&toType=" + device1.getId().getEntityType().name(), EntityRelation.class); Assert.assertNotNull(relation); } - private void sendDeleteDeviceOnEdge() throws Exception { - Device device = findDeviceByName("Edge Device 2"); + @Test + public void testSendDeleteDeviceOnEdgeToCloud() throws Exception { + Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge(); UplinkMsg.Builder upLinkMsgBuilder = UplinkMsg.newBuilder(); DeviceUpdateMsg.Builder deviceDeleteMsgBuilder = DeviceUpdateMsg.newBuilder(); deviceDeleteMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE); @@ -1468,15 +1442,16 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { edgeImitator.expectResponsesAmount(1); edgeImitator.sendUplinkMsg(upLinkMsgBuilder.build()); Assert.assertTrue(edgeImitator.waitForResponses()); - device = doGet("/api/device/" + device.getId().getId().toString(), Device.class); + device = doGet("/api/device/" + device.getUuidId(), Device.class); Assert.assertNotNull(device); - List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/devices?", + List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/devices?", new TypeReference>() { }, new PageLink(100)).getData(); Assert.assertFalse(edgeDevices.contains(device)); } - private void sendRuleChainMetadataRequest() throws Exception { + @Test + public void testSendRuleChainMetadataRequestToCloud() throws Exception { RuleChainId edgeRootRuleChainId = edge.getRootRuleChainId(); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); @@ -1503,7 +1478,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { testAutoGeneratedCodeByProtobuf(ruleChainMetadataUpdateMsg); } - private void sendUserCredentialsRequest() throws Exception { + @Test + public void testSendUserCredentialsRequestToCloud() throws Exception { UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); UserCredentialsRequestMsg.Builder userCredentialsRequestMsgBuilder = UserCredentialsRequestMsg.newBuilder(); userCredentialsRequestMsgBuilder.setUserIdMSB(tenantAdmin.getId().getId().getMostSignificantBits()); @@ -1528,10 +1504,11 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { testAutoGeneratedCodeByProtobuf(userCredentialsUpdateMsg); } - private void sendDeviceCredentialsRequest() throws Exception { + @Test + public void testSendDeviceCredentialsRequestToCloud() throws Exception { Device device = findDeviceByName("Edge Device 1"); - DeviceCredentials deviceCredentials = doGet("/api/device/" + device.getId().getId().toString() + "/credentials", DeviceCredentials.class); + DeviceCredentials deviceCredentials = doGet("/api/device/" + device.getUuidId() + "/credentials", DeviceCredentials.class); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); DeviceCredentialsRequestMsg.Builder deviceCredentialsRequestMsgBuilder = DeviceCredentialsRequestMsg.newBuilder(); @@ -1557,7 +1534,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertEquals(deviceCredentialsUpdateMsg.getCredentialsId(), deviceCredentials.getCredentialsId()); } - private void sendDeviceRpcResponse() throws Exception { + @Test + public void testSendDeviceRpcResponseToCloud() throws Exception { Device device = findDeviceByName("Edge Device 1"); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); @@ -1582,7 +1560,8 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertTrue(edgeImitator.waitForResponses()); } - private void sendDeviceCredentialsUpdate() throws Exception { + @Test + public void testSendDeviceCredentialsUpdateToCloud() throws Exception { Device device = findDeviceByName("Edge Device 1"); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); @@ -1601,24 +1580,30 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertTrue(edgeImitator.waitForResponses()); } - private void sendAttributesRequest() throws Exception { + @Test + public void testSendAttributesRequestToCloud() throws Exception { Device device = findDeviceByName("Edge Device 1"); - sendAttributesRequest(device, DataConstants.SERVER_SCOPE, "{\"key1\":\"value1\"}", - "key1", "value1", 2); - sendAttributesRequest(device, DataConstants.SHARED_SCOPE, "{\"key2\":\"value2\"}", - "key2", "value2", 1); + sendAttributesRequestAndVerify(device, DataConstants.SERVER_SCOPE, "{\"key1\":\"value1\"}", + "key1", "value1"); + sendAttributesRequestAndVerify(device, DataConstants.SHARED_SCOPE, "{\"key2\":\"value2\"}", + "key2", "value2"); } - private void sendAttributesRequest(Device device, String scope, String attributesDataStr, String expectedKey, - String expectedValue, int expectedSize) throws Exception { + private void sendAttributesRequestAndVerify(Device device, String scope, String attributesDataStr, String expectedKey, + String expectedValue) throws Exception { JsonNode attributesData = mapper.readTree(attributesDataStr); - doPost("/api/plugins/telemetry/DEVICE/" + device.getId().getId().toString() + "/attributes/" + scope, + doPost("/api/plugins/telemetry/DEVICE/" + device.getUuidId() + "/attributes/" + scope, attributesData); // Wait before device attributes saved to database before requesting them from edge - // queue used to save attributes to database - Thread.sleep(500); + Awaitility.await() + .atMost(10, TimeUnit.SECONDS) + .until(() -> { + String urlTemplate = "/api/plugins/telemetry/DEVICE/" + device.getId() + "/keys/attributes/" + scope; + List actualKeys = doGetAsyncTyped(urlTemplate, new TypeReference<>() {}); + return actualKeys != null && !actualKeys.isEmpty() && actualKeys.contains(expectedKey); + }); UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder(); AttributesRequestMsg.Builder attributesRequestMsgBuilder = AttributesRequestMsg.newBuilder(); @@ -1646,19 +1631,39 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { Assert.assertTrue(latestEntityDataMsg.hasAttributesUpdatedMsg()); TransportProtos.PostAttributeMsg attributesUpdatedMsg = latestEntityDataMsg.getAttributesUpdatedMsg(); - Assert.assertEquals(expectedSize, attributesUpdatedMsg.getKvList().size()); + + boolean found = false; for (TransportProtos.KeyValueProto keyValueProto : attributesUpdatedMsg.getKvList()) { if (keyValueProto.getKey().equals(expectedKey)) { Assert.assertEquals(expectedKey, keyValueProto.getKey()); Assert.assertEquals(expectedValue, keyValueProto.getStringV()); + found = true; } } + Assert.assertTrue("Expected key and value must be found", found); } // Utility methods + private Device saveDeviceOnCloudAndVerifyDeliveryToEdge() throws Exception { + edgeImitator.expectMessageAmount(1); + Device savedDevice = saveDevice(RandomStringUtils.randomAlphanumeric(15), "Default"); + doPost("/api/edge/" + edge.getUuidId() + + "/device/" + savedDevice.getUuidId(), Device.class); + Assert.assertTrue(edgeImitator.waitForMessages()); + AbstractMessage latestMessage = edgeImitator.getLatestMessage(); + Assert.assertTrue(latestMessage instanceof DeviceUpdateMsg); + DeviceUpdateMsg deviceUpdateMsg = (DeviceUpdateMsg) latestMessage; + Assert.assertEquals(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, deviceUpdateMsg.getMsgType()); + Assert.assertEquals(deviceUpdateMsg.getIdMSB(), savedDevice.getUuidId().getMostSignificantBits()); + Assert.assertEquals(deviceUpdateMsg.getIdLSB(), savedDevice.getUuidId().getLeastSignificantBits()); + Assert.assertEquals(deviceUpdateMsg.getName(), savedDevice.getName()); + Assert.assertEquals(deviceUpdateMsg.getType(), savedDevice.getType()); + return savedDevice; + } + private Device findDeviceByName(String deviceName) throws Exception { - List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/devices?", + List edgeDevices = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/devices?", new TypeReference>() { }, new PageLink(100)).getData(); Optional foundDevice = edgeDevices.stream().filter(d -> d.getName().equals(deviceName)).findAny(); @@ -1669,7 +1674,7 @@ abstract public class BaseEdgeTest extends AbstractControllerTest { } private Asset findAssetByName(String assetName) throws Exception { - List edgeAssets = doGetTypedWithPageLink("/api/edge/" + edge.getId().getId().toString() + "/assets?", + List edgeAssets = doGetTypedWithPageLink("/api/edge/" + edge.getUuidId() + "/assets?", new TypeReference>() { }, new PageLink(100)).getData(); diff --git a/application/src/test/java/org/thingsboard/server/edge/EdgeSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/edge/EdgeSqlTestSuite.java deleted file mode 100644 index ea7b275cfd..0000000000 --- a/application/src/test/java/org/thingsboard/server/edge/EdgeSqlTestSuite.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.edge; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ - "org.thingsboard.server.edge.sql.*Test", -}) -public class EdgeSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } -} diff --git a/application/src/test/java/org/thingsboard/server/edge/imitator/EdgeImitator.java b/application/src/test/java/org/thingsboard/server/edge/imitator/EdgeImitator.java index 46ee981be1..cfb652dd9f 100644 --- a/application/src/test/java/org/thingsboard/server/edge/imitator/EdgeImitator.java +++ b/application/src/test/java/org/thingsboard/server/edge/imitator/EdgeImitator.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,6 +88,9 @@ public class EdgeImitator { @Getter private List downlinkMsgs; + @Getter + private UplinkResponseMsg latestResponseMsg; + private boolean connected = false; public EdgeImitator(String host, int port, String routingKey, String routingSecret) throws NoSuchFieldException, IllegalAccessException { @@ -132,6 +135,7 @@ public class EdgeImitator { private void onUplinkResponse(UplinkResponseMsg msg) { log.info("onUplinkResponse: {}", msg); + latestResponseMsg = msg; responsesLatch.countDown(); } diff --git a/application/src/test/java/org/thingsboard/server/edge/sql/EdgeSqlTest.java b/application/src/test/java/org/thingsboard/server/edge/sql/EdgeSqlTest.java index 041023d0b1..8f6c26271b 100644 --- a/application/src/test/java/org/thingsboard/server/edge/sql/EdgeSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/edge/sql/EdgeSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/rules/RuleEngineSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/rules/RuleEngineSqlTestSuite.java deleted file mode 100644 index 2989d2de7f..0000000000 --- a/application/src/test/java/org/thingsboard/server/rules/RuleEngineSqlTestSuite.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.rules; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ - "org.thingsboard.server.rules.flow.sql.*Test", - "org.thingsboard.server.rules.lifecycle.sql.*Test", -}) -public class RuleEngineSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/rules/flow/AbstractRuleEngineFlowIntegrationTest.java b/application/src/test/java/org/thingsboard/server/rules/flow/AbstractRuleEngineFlowIntegrationTest.java index 90a0404751..9d96fe9d9c 100644 --- a/application/src/test/java/org/thingsboard/server/rules/flow/AbstractRuleEngineFlowIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/rules/flow/AbstractRuleEngineFlowIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,19 +15,28 @@ */ package org.thingsboard.server.rules.flow; +import com.google.common.util.concurrent.ListenableFuture; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.util.ReflectionTestUtils; +import org.thingsboard.rule.engine.flow.TbRuleChainInputNodeConfiguration; import org.thingsboard.rule.engine.metadata.TbGetAttributesNodeConfiguration; import org.thingsboard.server.actors.ActorSystemContext; -import org.thingsboard.server.common.data.*; +import org.thingsboard.server.common.data.DataConstants; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.Event; +import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.rule.NodeConnectionInfo; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.rule.RuleNode; @@ -38,12 +47,14 @@ import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg; import org.thingsboard.server.common.msg.queue.TbMsgCallback; import org.thingsboard.server.controller.AbstractRuleEngineControllerTest; import org.thingsboard.server.dao.attributes.AttributesService; +import org.thingsboard.server.dao.event.EventService; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import static org.mockito.Mockito.spy; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** @@ -61,8 +72,26 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule @Autowired protected AttributesService attributesService; + @Autowired + protected EventService eventService; + @Before public void beforeTest() throws Exception { + + EventService spyEventService = spy(eventService); + + Mockito.doAnswer((Answer>) invocation -> { + Object[] args = invocation.getArguments(); + Event event = (Event) args[0]; + ListenableFuture future = eventService.saveAsync(event); + try { + future.get(); + } catch (Exception e) {} + return future; + }).when(spyEventService).saveAsync(Mockito.any(Event.class)); + + ReflectionTestUtils.setField(actorSystem, "eventService", spyEventService); + loginSysAdmin(); Tenant tenant = new Tenant(); @@ -136,14 +165,12 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule device = doPost("/api/device", device, Device.class); attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, - Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))); + Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))).get(); attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, - Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))); - - - Thread.sleep(1000); + Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))).get(); TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class); + Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true); TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback); QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null); // Pushing Message to the system @@ -215,16 +242,27 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule configuration1.setServerAttributeNames(Collections.singletonList("serverAttributeKey1")); ruleNode1.setConfiguration(mapper.valueToTree(configuration1)); - rootMetaData.setNodes(Collections.singletonList(ruleNode1)); + RuleNode ruleNode12 = new RuleNode(); + ruleNode12.setName("Simple Rule Node 1"); + ruleNode12.setType(org.thingsboard.rule.engine.flow.TbRuleChainInputNode.class.getName()); + ruleNode12.setDebugMode(true); + TbRuleChainInputNodeConfiguration configuration12 = new TbRuleChainInputNodeConfiguration(); + configuration12.setRuleChainId(secondaryRuleChain.getId().getId().toString()); + ruleNode12.setConfiguration(mapper.valueToTree(configuration12)); + + rootMetaData.setNodes(Arrays.asList(ruleNode1, ruleNode12)); rootMetaData.setFirstNodeIndex(0); - rootMetaData.addRuleChainConnectionInfo(0, secondaryRuleChain.getId(), "Success", mapper.createObjectNode()); + NodeConnectionInfo connection = new NodeConnectionInfo(); + connection.setFromIndex(0); + connection.setToIndex(1); + connection.setType("Success"); + rootMetaData.setConnections(Collections.singletonList(connection)); rootMetaData = saveRuleChainMetaData(rootMetaData); Assert.assertNotNull(rootMetaData); rootRuleChain = getRuleChain(rootRuleChain.getId()); Assert.assertNotNull(rootRuleChain.getFirstRuleNodeId()); - RuleChainMetaData secondaryMetaData = new RuleChainMetaData(); secondaryMetaData.setRuleChainId(secondaryRuleChain.getId()); @@ -248,14 +286,12 @@ public abstract class AbstractRuleEngineFlowIntegrationTest extends AbstractRule device = doPost("/api/device", device, Device.class); attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, - Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))); + Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey1", "serverAttributeValue1"), System.currentTimeMillis()))).get(); attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, - Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))); - - - Thread.sleep(1000); + Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey2", "serverAttributeValue2"), System.currentTimeMillis()))).get(); TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class); + Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true); TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback); QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null); // Pushing Message to the system diff --git a/application/src/test/java/org/thingsboard/server/rules/flow/sql/RuleEngineFlowSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/rules/flow/sql/RuleEngineFlowSqlIntegrationTest.java index 7ad379a216..7e00371b2d 100644 --- a/application/src/test/java/org/thingsboard/server/rules/flow/sql/RuleEngineFlowSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/rules/flow/sql/RuleEngineFlowSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/rules/lifecycle/AbstractRuleEngineLifecycleIntegrationTest.java b/application/src/test/java/org/thingsboard/server/rules/lifecycle/AbstractRuleEngineLifecycleIntegrationTest.java index ccdf788634..5d86e6a2a5 100644 --- a/application/src/test/java/org/thingsboard/server/rules/lifecycle/AbstractRuleEngineLifecycleIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/rules/lifecycle/AbstractRuleEngineLifecycleIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,41 +16,41 @@ package org.thingsboard.server.rules.lifecycle; import lombok.extern.slf4j.Slf4j; +import org.awaitility.Awaitility; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.ClassRule; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.test.context.support.TestPropertySourceUtils; +import org.testcontainers.containers.GenericContainer; import org.thingsboard.rule.engine.metadata.TbGetAttributesNodeConfiguration; import org.thingsboard.server.actors.ActorSystemContext; import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Event; -import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry; import org.thingsboard.server.common.data.kv.StringDataEntry; -import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.rule.RuleChainMetaData; import org.thingsboard.server.common.data.rule.RuleNode; -import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg; import org.thingsboard.server.common.msg.queue.TbMsgCallback; import org.thingsboard.server.controller.AbstractRuleEngineControllerTest; import org.thingsboard.server.dao.attributes.AttributesService; -import org.thingsboard.server.queue.memory.InMemoryStorage; +import org.thingsboard.server.dao.event.EventService; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import static org.awaitility.Awaitility.await; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * @author Valerii Sosliuk @@ -58,41 +58,23 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @Slf4j public abstract class AbstractRuleEngineLifecycleIntegrationTest extends AbstractRuleEngineControllerTest { - protected Tenant savedTenant; - protected User tenantAdmin; - @Autowired protected ActorSystemContext actorSystem; @Autowired protected AttributesService attributesService; + @Autowired + protected EventService eventService; + @Before public void beforeTest() throws Exception { - loginSysAdmin(); - - Tenant tenant = new Tenant(); - tenant.setTitle("My tenant"); - savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedTenant); - ruleChainService.deleteRuleChainsByTenantId(savedTenant.getId()); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant2@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); - - createUserAndLogin(tenantAdmin, "testPassword1"); + loginTenantAdmin(); + ruleChainService.deleteRuleChainsByTenantId(tenantId); } @After public void afterTest() throws Exception { - loginSysAdmin(); - if (savedTenant != null) { - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk()); - } } @Test @@ -100,7 +82,7 @@ public abstract class AbstractRuleEngineLifecycleIntegrationTest extends Abstrac // Creating Rule Chain RuleChain ruleChain = new RuleChain(); ruleChain.setName("Simple Rule Chain"); - ruleChain.setTenantId(savedTenant.getId()); + ruleChain.setTenantId(tenantId); ruleChain.setRoot(true); ruleChain.setDebugMode(true); ruleChain = saveRuleChain(ruleChain); @@ -123,8 +105,24 @@ public abstract class AbstractRuleEngineLifecycleIntegrationTest extends Abstrac metaData = saveRuleChainMetaData(metaData); Assert.assertNotNull(metaData); - ruleChain = getRuleChain(ruleChain.getId()); - Assert.assertNotNull(ruleChain.getFirstRuleNodeId()); + final RuleChain ruleChainFinal = getRuleChain(ruleChain.getId()); + Assert.assertNotNull(ruleChainFinal.getFirstRuleNodeId()); + + //TODO find out why RULE_NODE update event did not appear all the time + List rcEvents = Awaitility.await("Rule Node started successfully") + .pollInterval(10, MILLISECONDS) + .atMost(TIMEOUT, TimeUnit.SECONDS) + .until(() -> { + List debugEvents = getEvents(tenantId, ruleChainFinal.getFirstRuleNodeId(), DataConstants.LC_EVENT, 1000) + .getData().stream().filter(e -> { + var body = e.getBody(); + return body.has("event") && body.get("event").asText().equals("STARTED") + && body.has("success") && body.get("success").asBoolean(); + }).collect(Collectors.toList()); + debugEvents.forEach((e) -> log.trace("event: {}", e)); + return debugEvents; + }, + x -> x.size() == 1); // Saving the device Device device = new Device(); @@ -132,34 +130,46 @@ public abstract class AbstractRuleEngineLifecycleIntegrationTest extends Abstrac device.setType("default"); device = doPost("/api/device", device, Device.class); + log.warn("before update attr"); attributesService.save(device.getTenantId(), device.getId(), DataConstants.SERVER_SCOPE, - Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey", "serverAttributeValue"), System.currentTimeMillis()))); - - await("total inMemory queue lag is empty").atMost(30, TimeUnit.SECONDS) - .until(() -> InMemoryStorage.getInstance().getLagTotal() == 0); - Thread.sleep(1000); - + Collections.singletonList(new BaseAttributeKvEntry(new StringDataEntry("serverAttributeKey", "serverAttributeValue"), System.currentTimeMillis()))) + .get(TIMEOUT, TimeUnit.SECONDS); + log.warn("attr updated"); TbMsgCallback tbMsgCallback = Mockito.mock(TbMsgCallback.class); + Mockito.when(tbMsgCallback.isMsgValid()).thenReturn(true); TbMsg tbMsg = TbMsg.newMsg("CUSTOM", device.getId(), new TbMsgMetaData(), "{}", tbMsgCallback); - QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(savedTenant.getId(), tbMsg, null, null); + QueueToRuleEngineMsg qMsg = new QueueToRuleEngineMsg(tenantId, tbMsg, null, null); // Pushing Message to the system + log.warn("before tell tbMsgCallback"); actorSystem.tell(qMsg); - Mockito.verify(tbMsgCallback, Mockito.timeout(10000)).onSuccess(); - - - PageData eventsPage = getDebugEvents(savedTenant.getId(), ruleChain.getFirstRuleNodeId(), 1000); - List events = eventsPage.getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList()); - - Assert.assertEquals(2, events.size()); + log.warn("awaiting tbMsgCallback"); + Mockito.verify(tbMsgCallback, Mockito.timeout(TimeUnit.SECONDS.toMillis(TIMEOUT))).onSuccess(); + log.warn("awaiting events"); + List events = Awaitility.await("get debug by custom event") + .pollInterval(10, MILLISECONDS) + .atMost(TIMEOUT, TimeUnit.SECONDS) + .until(() -> { + List debugEvents = getDebugEvents(tenantId, ruleChainFinal.getFirstRuleNodeId(), 1000) + .getData().stream().filter(filterByCustomEvent()).collect(Collectors.toList()); + log.warn("filtered debug events [{}]", debugEvents.size()); + debugEvents.forEach((e) -> log.warn("event: {}", e)); + return debugEvents; + }, + x -> x.size() == 2); + log.warn("asserting.."); Event inEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.IN)).findFirst().get(); - Assert.assertEquals(ruleChain.getFirstRuleNodeId(), inEvent.getEntityId()); + Assert.assertEquals(ruleChainFinal.getFirstRuleNodeId(), inEvent.getEntityId()); Assert.assertEquals(device.getId().getId().toString(), inEvent.getBody().get("entityId").asText()); Event outEvent = events.stream().filter(e -> e.getBody().get("type").asText().equals(DataConstants.OUT)).findFirst().get(); - Assert.assertEquals(ruleChain.getFirstRuleNodeId(), outEvent.getEntityId()); + Assert.assertEquals(ruleChainFinal.getFirstRuleNodeId(), outEvent.getEntityId()); Assert.assertEquals(device.getId().getId().toString(), outEvent.getBody().get("entityId").asText()); + log.warn("OUT event {}", outEvent); + log.warn("OUT event metadata {}", getMetadata(outEvent)); + + Assert.assertNotNull("metadata has ss_serverAttributeKey", getMetadata(outEvent).get("ss_serverAttributeKey")); Assert.assertEquals("serverAttributeValue", getMetadata(outEvent).get("ss_serverAttributeKey").asText()); } diff --git a/application/src/test/java/org/thingsboard/server/rules/lifecycle/sql/RuleEngineLifecycleSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/rules/lifecycle/sql/RuleEngineLifecycleSqlIntegrationTest.java index dabea31723..02205248fe 100644 --- a/application/src/test/java/org/thingsboard/server/rules/lifecycle/sql/RuleEngineLifecycleSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/rules/lifecycle/sql/RuleEngineLifecycleSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.thingsboard.server.rules.lifecycle.sql; import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.rules.flow.AbstractRuleEngineFlowIntegrationTest; import org.thingsboard.server.rules.lifecycle.AbstractRuleEngineLifecycleIntegrationTest; /** diff --git a/application/src/test/java/org/thingsboard/server/service/ServiceSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/service/ServiceSqlTestSuite.java deleted file mode 100644 index 508272085c..0000000000 --- a/application/src/test/java/org/thingsboard/server/service/ServiceSqlTestSuite.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.service; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ - "org.thingsboard.server.service.resource.sql.*Test", -}) -public class ServiceSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/service/apiusage/DefaultTbApiUsageStateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/apiusage/DefaultTbApiUsageStateServiceTest.java new file mode 100644 index 0000000000..fde595ea3b --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/apiusage/DefaultTbApiUsageStateServiceTest.java @@ -0,0 +1,86 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.apiusage; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.thingsboard.rule.engine.api.MailService; +import org.thingsboard.server.cluster.TbClusterService; +import org.thingsboard.server.common.data.ApiUsageState; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.msg.queue.ServiceType; +import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; +import org.thingsboard.server.dao.tenant.TbTenantProfileCache; +import org.thingsboard.server.dao.tenant.TenantService; +import org.thingsboard.server.dao.timeseries.TimeseriesService; +import org.thingsboard.server.dao.usagerecord.ApiUsageStateService; +import org.thingsboard.server.queue.discovery.PartitionService; +import org.thingsboard.server.queue.scheduler.SchedulerComponent; +import org.thingsboard.server.service.executors.DbCallbackExecutorService; + +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.BDDMockito.willReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +@RunWith(MockitoJUnitRunner.class) +public class DefaultTbApiUsageStateServiceTest { + + @Mock + TenantService tenantService; + @Mock + TimeseriesService tsService; + @Mock + TbClusterService clusterService; + @Mock + PartitionService partitionService; + @Mock + TenantApiUsageState tenantUsageStateMock; + @Mock + ApiUsageStateService apiUsageStateService; + @Mock + TbTenantProfileCache tenantProfileCache; + @Mock + MailService mailService; + @Mock + DbCallbackExecutorService dbExecutor; + + TenantId tenantId = TenantId.fromUUID(UUID.fromString("00797a3b-7aeb-4b5b-b57a-c2a810d0f112")); + + DefaultTbApiUsageStateService service; + + @Before + public void setUp() { + service = spy(new DefaultTbApiUsageStateService(clusterService, partitionService, tenantService, tsService, apiUsageStateService, tenantProfileCache, mailService, dbExecutor)); + } + + @Test + public void givenTenantIdFromEntityStatesMap_whenGetApiUsageState() { + service.myUsageStates.put(tenantId, tenantUsageStateMock); + ApiUsageState tenantUsageState = service.getApiUsageState(tenantId); + assertThat(tenantUsageState, is(tenantUsageStateMock.getApiUsageState())); + Mockito.verify(service, never()).getOrFetchState(tenantId, tenantId); + } + +} \ No newline at end of file diff --git a/application/src/test/java/org/thingsboard/server/service/cluster/routing/HashPartitionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/cluster/routing/HashPartitionServiceTest.java index 820127a81c..cea08003bf 100644 --- a/application/src/test/java/org/thingsboard/server/service/cluster/routing/HashPartitionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/cluster/routing/HashPartitionServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,20 +21,18 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.context.ApplicationEventPublisher; import org.springframework.test.util.ReflectionTestUtils; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.TenantId; -import org.thingsboard.server.queue.QueueService; -import org.thingsboard.server.queue.discovery.HashPartitionService; import org.thingsboard.server.common.msg.queue.ServiceType; -import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.common.msg.queue.TopicPartitionInfo; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.queue.discovery.HashPartitionService; +import org.thingsboard.server.queue.discovery.QueueRoutingInfoService; +import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; import org.thingsboard.server.queue.discovery.TenantRoutingInfoService; -import org.thingsboard.server.queue.settings.TbQueueRuleEngineSettings; import java.util.ArrayList; import java.util.Collections; @@ -45,7 +43,6 @@ import java.util.Map; import java.util.stream.Collectors; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; @Slf4j @RunWith(MockitoJUnitRunner.class) @@ -58,33 +55,25 @@ public class HashPartitionServiceTest { private TbServiceInfoProvider discoveryService; private TenantRoutingInfoService routingInfoService; private ApplicationEventPublisher applicationEventPublisher; - private TbQueueRuleEngineSettings ruleEngineSettings; - private QueueService queueService; + private QueueRoutingInfoService queueRoutingInfoService; private String hashFunctionName = "sha256"; - @Before public void setup() throws Exception { discoveryService = mock(TbServiceInfoProvider.class); applicationEventPublisher = mock(ApplicationEventPublisher.class); routingInfoService = mock(TenantRoutingInfoService.class); - ruleEngineSettings = mock(TbQueueRuleEngineSettings.class); - queueService = mock(QueueService.class); + queueRoutingInfoService = mock(QueueRoutingInfoService.class); clusterRoutingService = new HashPartitionService(discoveryService, routingInfoService, applicationEventPublisher, - ruleEngineSettings, - queueService - ); - when(ruleEngineSettings.getQueues()).thenReturn(Collections.emptyList()); + queueRoutingInfoService); ReflectionTestUtils.setField(clusterRoutingService, "coreTopic", "tb.core"); ReflectionTestUtils.setField(clusterRoutingService, "corePartitions", 10); ReflectionTestUtils.setField(clusterRoutingService, "hashFunctionName", hashFunctionName); TransportProtos.ServiceInfo currentServer = TransportProtos.ServiceInfo.newBuilder() .setServiceId("tb-core-0") - .setTenantIdMSB(TenantId.NULL_UUID.getMostSignificantBits()) - .setTenantIdLSB(TenantId.NULL_UUID.getLeastSignificantBits()) .addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name())) .build(); // when(queueService.resolve(Mockito.any(), Mockito.anyString())).thenAnswer(i -> i.getArguments()[1]); @@ -93,12 +82,12 @@ public class HashPartitionServiceTest { for (int i = 1; i < SERVER_COUNT; i++) { otherServers.add(TransportProtos.ServiceInfo.newBuilder() .setServiceId("tb-rule-" + i) - .setTenantIdMSB(TenantId.NULL_UUID.getMostSignificantBits()) - .setTenantIdLSB(TenantId.NULL_UUID.getLeastSignificantBits()) .addAllServiceTypes(Collections.singletonList(ServiceType.TB_CORE.name())) .build()); } + clusterRoutingService.init(); + clusterRoutingService.partitionsInit(); clusterRoutingService.recalculatePartitions(currentServer, otherServers); } diff --git a/application/src/test/java/org/thingsboard/server/service/edge/rpc/constructor/RuleChainMsgConstructorTest.java b/application/src/test/java/org/thingsboard/server/service/edge/rpc/constructor/RuleChainMsgConstructorTest.java new file mode 100644 index 0000000000..f55190130c --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/edge/rpc/constructor/RuleChainMsgConstructorTest.java @@ -0,0 +1,358 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.edge.rpc.constructor; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import lombok.extern.slf4j.Slf4j; +import org.jetbrains.annotations.NotNull; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.id.RuleNodeId; +import org.thingsboard.server.common.data.rule.NodeConnectionInfo; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.common.data.rule.RuleNode; +import org.thingsboard.server.gen.edge.v1.EdgeVersion; +import org.thingsboard.server.gen.edge.v1.RuleChainConnectionInfoProto; +import org.thingsboard.server.gen.edge.v1.RuleChainMetadataUpdateMsg; +import org.thingsboard.server.gen.edge.v1.UpdateMsgType; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +@Slf4j +@RunWith(MockitoJUnitRunner.class) +public class RuleChainMsgConstructorTest { + + private static final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void testConstructRuleChainMetadataUpdatedMsg_V_3_3_3() throws JsonProcessingException { + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainMsgConstructor constructor = new RuleChainMsgConstructor(); + RuleChainMetaData ruleChainMetaData = createRuleChainMetaData(ruleChainId, 3, createRuleNodes(ruleChainId), createConnections()); + RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg = + constructor.constructRuleChainMetadataUpdatedMsg(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, ruleChainMetaData, EdgeVersion.V_3_3_3); + + Assert.assertEquals("First rule node index incorrect!", 3, ruleChainMetadataUpdateMsg.getFirstNodeIndex()); + Assert.assertEquals("Nodes count incorrect!", 12, ruleChainMetadataUpdateMsg.getNodesCount()); + Assert.assertEquals("Connections count incorrect!", 13, ruleChainMetadataUpdateMsg.getConnectionsCount()); + Assert.assertEquals("Rule chain connections count incorrect!", 0, ruleChainMetadataUpdateMsg.getRuleChainConnectionsCount()); + + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(3, 6, "Success"), ruleChainMetadataUpdateMsg.getConnections(0)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(3, 10, "Success"), ruleChainMetadataUpdateMsg.getConnections(1)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(3, 0, "Success"), ruleChainMetadataUpdateMsg.getConnections(2)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 11, "Success"), ruleChainMetadataUpdateMsg.getConnections(3)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 11, "Success"), ruleChainMetadataUpdateMsg.getConnections(4)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 11, "Attributes Updated"), ruleChainMetadataUpdateMsg.getConnections(5)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 7, "RPC Request from Device"), ruleChainMetadataUpdateMsg.getConnections(6)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 4, "Post telemetry"), ruleChainMetadataUpdateMsg.getConnections(7)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 5, "Post attributes"), ruleChainMetadataUpdateMsg.getConnections(8)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 8, "Other"), ruleChainMetadataUpdateMsg.getConnections(9)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 9, "RPC Request to Device"), ruleChainMetadataUpdateMsg.getConnections(10)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(7, 11, "Success"), ruleChainMetadataUpdateMsg.getConnections(11)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(10, 9, "RPC"), ruleChainMetadataUpdateMsg.getConnections(12)); + } + + @Test + public void testConstructRuleChainMetadataUpdatedMsg_V_3_3_0() throws JsonProcessingException { + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainMsgConstructor constructor = new RuleChainMsgConstructor(); + RuleChainMetaData ruleChainMetaData = createRuleChainMetaData(ruleChainId, 3, createRuleNodes(ruleChainId), createConnections()); + RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg = + constructor.constructRuleChainMetadataUpdatedMsg(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, ruleChainMetaData, EdgeVersion.V_3_3_0); + + Assert.assertEquals("First rule node index incorrect!", 2, ruleChainMetadataUpdateMsg.getFirstNodeIndex()); + Assert.assertEquals("Nodes count incorrect!", 10, ruleChainMetadataUpdateMsg.getNodesCount()); + Assert.assertEquals("Connections count incorrect!", 10, ruleChainMetadataUpdateMsg.getConnectionsCount()); + Assert.assertEquals("Rule chain connections count incorrect!", 1, ruleChainMetadataUpdateMsg.getRuleChainConnectionsCount()); + + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(2, 5, "Success"), ruleChainMetadataUpdateMsg.getConnections(0)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(3, 9, "Success"), ruleChainMetadataUpdateMsg.getConnections(1)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 9, "Success"), ruleChainMetadataUpdateMsg.getConnections(2)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 9, "Attributes Updated"), ruleChainMetadataUpdateMsg.getConnections(3)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 6, "RPC Request from Device"), ruleChainMetadataUpdateMsg.getConnections(4)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 3, "Post telemetry"), ruleChainMetadataUpdateMsg.getConnections(5)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 4, "Post attributes"), ruleChainMetadataUpdateMsg.getConnections(6)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 7, "Other"), ruleChainMetadataUpdateMsg.getConnections(7)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 8, "RPC Request to Device"), ruleChainMetadataUpdateMsg.getConnections(8)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 9, "Success"), ruleChainMetadataUpdateMsg.getConnections(9)); + + RuleChainConnectionInfoProto ruleChainConnection = ruleChainMetadataUpdateMsg.getRuleChainConnections(0); + Assert.assertEquals("From index incorrect!", 2, ruleChainConnection.getFromIndex()); + Assert.assertEquals("Type index incorrect!", "Success", ruleChainConnection.getType()); + Assert.assertEquals("Additional info incorrect!", + "{\"description\":\"\",\"layoutX\":477,\"layoutY\":560,\"ruleChainNodeId\":\"rule-chain-node-UNDEFINED\"}", + ruleChainConnection.getAdditionalInfo()); + Assert.assertTrue("Target rule chain id MSB incorrect!", ruleChainConnection.getTargetRuleChainIdMSB() != 0); + Assert.assertTrue("Target rule chain id LSB incorrect!", ruleChainConnection.getTargetRuleChainIdLSB() != 0); + } + + @Test + public void testConstructRuleChainMetadataUpdatedMsg_V_3_3_0_inDifferentOrder() throws JsonProcessingException { + // same rule chain metadata, but different order of rule nodes + RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID()); + RuleChainMsgConstructor constructor = new RuleChainMsgConstructor(); + RuleChainMetaData ruleChainMetaData1 = createRuleChainMetaData(ruleChainId, 8, createRuleNodesInDifferentOrder(ruleChainId), createConnectionsInDifferentOrder()); + RuleChainMetadataUpdateMsg ruleChainMetadataUpdateMsg = + constructor.constructRuleChainMetadataUpdatedMsg(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE, ruleChainMetaData1, EdgeVersion.V_3_3_0); + + Assert.assertEquals("First rule node index incorrect!", 7, ruleChainMetadataUpdateMsg.getFirstNodeIndex()); + Assert.assertEquals("Nodes count incorrect!", 10, ruleChainMetadataUpdateMsg.getNodesCount()); + Assert.assertEquals("Connections count incorrect!", 10, ruleChainMetadataUpdateMsg.getConnectionsCount()); + Assert.assertEquals("Rule chain connections count incorrect!", 1, ruleChainMetadataUpdateMsg.getRuleChainConnectionsCount()); + + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(3, 0, "Success"), ruleChainMetadataUpdateMsg.getConnections(0)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 0, "Attributes Updated"), ruleChainMetadataUpdateMsg.getConnections(1)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 3, "RPC Request from Device"), ruleChainMetadataUpdateMsg.getConnections(2)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 6, "Post telemetry"), ruleChainMetadataUpdateMsg.getConnections(3)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 5, "Post attributes"), ruleChainMetadataUpdateMsg.getConnections(4)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 2, "Other"), ruleChainMetadataUpdateMsg.getConnections(5)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(4, 1, "RPC Request to Device"), ruleChainMetadataUpdateMsg.getConnections(6)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(5, 0, "Success"), ruleChainMetadataUpdateMsg.getConnections(7)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(6, 0, "Success"), ruleChainMetadataUpdateMsg.getConnections(8)); + compareNodeConnectionInfoAndProto(createNodeConnectionInfo(7, 4, "Success"), ruleChainMetadataUpdateMsg.getConnections(9)); + + RuleChainConnectionInfoProto ruleChainConnection = ruleChainMetadataUpdateMsg.getRuleChainConnections(0); + Assert.assertEquals("From index incorrect!", 7, ruleChainConnection.getFromIndex()); + Assert.assertEquals("Type index incorrect!", "Success", ruleChainConnection.getType()); + Assert.assertEquals("Additional info incorrect!", + "{\"description\":\"\",\"layoutX\":477,\"layoutY\":560,\"ruleChainNodeId\":\"rule-chain-node-UNDEFINED\"}", + ruleChainConnection.getAdditionalInfo()); + Assert.assertTrue("Target rule chain id MSB incorrect!", ruleChainConnection.getTargetRuleChainIdMSB() != 0); + Assert.assertTrue("Target rule chain id LSB incorrect!", ruleChainConnection.getTargetRuleChainIdLSB() != 0); + } + + private void compareNodeConnectionInfoAndProto(NodeConnectionInfo expected, org.thingsboard.server.gen.edge.v1.NodeConnectionInfoProto actual) { + Assert.assertEquals(expected.getFromIndex(), actual.getFromIndex()); + Assert.assertEquals(expected.getToIndex(), actual.getToIndex()); + Assert.assertEquals(expected.getType(), actual.getType()); + } + + private RuleChainMetaData createRuleChainMetaData(RuleChainId ruleChainId, Integer firstNodeIndex, List nodes, List connections) { + RuleChainMetaData ruleChainMetaData = new RuleChainMetaData(); + ruleChainMetaData.setRuleChainId(ruleChainId); + ruleChainMetaData.setFirstNodeIndex(firstNodeIndex); + ruleChainMetaData.setNodes(nodes); + ruleChainMetaData.setConnections(connections); + ruleChainMetaData.setRuleChainConnections(null); + return ruleChainMetaData; + } + + private List createConnections() { + List result = new ArrayList<>(); + result.add(createNodeConnectionInfo(3, 6, "Success")); + result.add(createNodeConnectionInfo(3, 10, "Success")); + result.add(createNodeConnectionInfo(3, 0, "Success")); + result.add(createNodeConnectionInfo(4, 11, "Success")); + result.add(createNodeConnectionInfo(5, 11, "Success")); + result.add(createNodeConnectionInfo(6, 11, "Attributes Updated")); + result.add(createNodeConnectionInfo(6, 7, "RPC Request from Device")); + result.add(createNodeConnectionInfo(6, 4, "Post telemetry")); + result.add(createNodeConnectionInfo(6, 5, "Post attributes")); + result.add(createNodeConnectionInfo(6, 8, "Other")); + result.add(createNodeConnectionInfo(6, 9, "RPC Request to Device")); + result.add(createNodeConnectionInfo(7, 11, "Success")); + result.add(createNodeConnectionInfo(10, 9, "RPC")); + return result; + } + + private NodeConnectionInfo createNodeConnectionInfo(int fromIndex, int toIndex, String type) { + NodeConnectionInfo result = new NodeConnectionInfo(); + result.setFromIndex(fromIndex); + result.setToIndex(toIndex); + result.setType(type); + return result; + } + + private List createRuleNodes(RuleChainId ruleChainId) throws JsonProcessingException { + List result = new ArrayList<>(); + result.add(getOutputNode(ruleChainId)); + result.add(getAcknowledgeNode(ruleChainId)); + result.add(getCheckpointNode(ruleChainId)); + result.add(getDeviceProfileNode(ruleChainId)); + result.add(getSaveTimeSeriesNode(ruleChainId)); + result.add(getSaveClientAttributesNode(ruleChainId)); + result.add(getMessageTypeSwitchNode(ruleChainId)); + result.add(getLogRpcFromDeviceNode(ruleChainId)); + result.add(getLogOtherNode(ruleChainId)); + result.add(getRpcCallRequestNode(ruleChainId)); + result.add(getPushToAnalyticsNode(ruleChainId)); + result.add(getPushToCloudNode(ruleChainId)); + return result; + } + + private RuleNode createRuleNode(RuleChainId ruleChainId, String type, String name, JsonNode configuration, JsonNode additionalInfo) { + RuleNode e = new RuleNode(); + e.setRuleChainId(ruleChainId); + e.setType(type); + e.setName(name); + e.setDebugMode(false); + e.setConfiguration(configuration); + e.setAdditionalInfo(additionalInfo); + e.setId(new RuleNodeId(UUID.randomUUID())); + return e; + } + + private List createConnectionsInDifferentOrder() { + List result = new ArrayList<>(); + result.add(createNodeConnectionInfo(0, 2, "RPC")); + result.add(createNodeConnectionInfo(4, 1, "Success")); + result.add(createNodeConnectionInfo(5, 1, "Attributes Updated")); + result.add(createNodeConnectionInfo(5, 4, "RPC Request from Device")); + result.add(createNodeConnectionInfo(5, 7, "Post telemetry")); + result.add(createNodeConnectionInfo(5, 6, "Post attributes")); + result.add(createNodeConnectionInfo(5, 3, "Other")); + result.add(createNodeConnectionInfo(5, 2, "RPC Request to Device")); + result.add(createNodeConnectionInfo(6, 1, "Success")); + result.add(createNodeConnectionInfo(7, 1, "Success")); + result.add(createNodeConnectionInfo(8, 11, "Success")); + result.add(createNodeConnectionInfo(8, 5, "Success")); + result.add(createNodeConnectionInfo(8, 0, "Success")); + return result; + } + + private List createRuleNodesInDifferentOrder(RuleChainId ruleChainId) throws JsonProcessingException { + List result = new ArrayList<>(); + result.add(getPushToAnalyticsNode(ruleChainId)); + result.add(getPushToCloudNode(ruleChainId)); + result.add(getRpcCallRequestNode(ruleChainId)); + result.add(getLogOtherNode(ruleChainId)); + result.add(getLogRpcFromDeviceNode(ruleChainId)); + result.add(getMessageTypeSwitchNode(ruleChainId)); + result.add(getSaveClientAttributesNode(ruleChainId)); + result.add(getSaveTimeSeriesNode(ruleChainId)); + result.add(getDeviceProfileNode(ruleChainId)); + result.add(getCheckpointNode(ruleChainId)); + result.add(getAcknowledgeNode(ruleChainId)); + result.add(getOutputNode(ruleChainId)); + return result; + } + + + @NotNull + private RuleNode getOutputNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.flow.TbRuleChainOutputNode", + "Output node", + mapper.readTree("{\"version\":0}"), + mapper.readTree("{\"description\":\"\",\"layoutX\":178,\"layoutY\":592}")); + } + + @NotNull + private RuleNode getCheckpointNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.flow.TbCheckpointNode", + "Checkpoint node", + mapper.readTree("{\"queueName\":\"HighPriority\"}"), + mapper.readTree("{\"description\":\"\",\"layoutX\":178,\"layoutY\":647}")); + } + + @NotNull + private RuleNode getSaveTimeSeriesNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.telemetry.TbMsgTimeseriesNode", + "Save Timeseries", + mapper.readTree("{\"defaultTTL\":0}"), + mapper.readTree("{\"layoutX\":823,\"layoutY\":157}")); + } + + @NotNull + private RuleNode getMessageTypeSwitchNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.filter.TbMsgTypeSwitchNode", + "Message Type Switch", + mapper.readTree("{\"version\":0}"), + mapper.readTree("{\"layoutX\":347,\"layoutY\":149}")); + } + + @NotNull + private RuleNode getLogOtherNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.action.TbLogNode", + "Log Other", + mapper.readTree("{\"jsScript\":\"return '\\\\nIncoming message:\\\\n' + JSON.stringify(msg) + '\\\\nIncoming metadata:\\\\n' + JSON.stringify(metadata);\"}"), + mapper.readTree("{\"layoutX\":824,\"layoutY\":378}")); + } + + @NotNull + private RuleNode getPushToCloudNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.edge.TbMsgPushToCloudNode", + "Push to cloud", + mapper.readTree("{\"scope\":\"SERVER_SCOPE\"}"), + mapper.readTree("{\"layoutX\":1129,\"layoutY\":52}")); + } + + @NotNull + private RuleNode getAcknowledgeNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.flow.TbAckNode", + "Acknowledge node", + mapper.readTree("{\"version\":0}"), + mapper.readTree("{\"description\":\"\",\"layoutX\":177,\"layoutY\":703}")); + } + + @NotNull + private RuleNode getDeviceProfileNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.profile.TbDeviceProfileNode", + "Device Profile Node", + mapper.readTree("{\"persistAlarmRulesState\":false,\"fetchAlarmRulesStateOnStart\":false}"), + mapper.readTree("{\"description\":\"Process incoming messages from devices with the alarm rules defined in the device profile. Dispatch all incoming messages with \\\"Success\\\" relation type.\",\"layoutX\":187,\"layoutY\":468}")); + } + + @NotNull + private RuleNode getSaveClientAttributesNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.telemetry.TbMsgAttributesNode", + "Save Client Attributes", + mapper.readTree("{\"scope\":\"CLIENT_SCOPE\"}"), + mapper.readTree("{\"layoutX\":824,\"layoutY\":52}")); + } + + @NotNull + private RuleNode getLogRpcFromDeviceNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.action.TbLogNode", + "Log RPC from Device", + mapper.readTree("{\"jsScript\":\"return '\\\\nIncoming message:\\\\n' + JSON.stringify(msg) + '\\\\nIncoming metadata:\\\\n' + JSON.stringify(metadata);\"}"), + mapper.readTree("{\"layoutX\":825,\"layoutY\":266}")); + } + + @NotNull + private RuleNode getRpcCallRequestNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.rpc.TbSendRPCRequestNode", + "RPC Call Request", + mapper.readTree("{\"timeoutInSeconds\":60}"), + mapper.readTree("{\"layoutX\":824,\"layoutY\":466}")); + } + + @NotNull + private RuleNode getPushToAnalyticsNode(RuleChainId ruleChainId) throws JsonProcessingException { + return createRuleNode(ruleChainId, + "org.thingsboard.rule.engine.flow.TbRuleChainInputNode", + "Push to Analytics", + mapper.readTree("{\"ruleChainId\":\"af588000-6c7c-11ec-bafd-c9a47a5c8d99\"}"), + mapper.readTree("{\"description\":\"\",\"layoutX\":477,\"layoutY\":560}")); + } +} \ No newline at end of file diff --git a/application/src/test/java/org/thingsboard/server/service/install/PsqlEntityDatabaseSchemaServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceTest.java similarity index 64% rename from application/src/test/java/org/thingsboard/server/service/install/PsqlEntityDatabaseSchemaServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceTest.java index eb08390ec7..07a32d5cdc 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/PsqlEntityDatabaseSchemaServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/SqlEntityDatabaseSchemaServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,31 +23,31 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -public class PsqlEntityDatabaseSchemaServiceTest { +public class SqlEntityDatabaseSchemaServiceTest { @Test public void givenPsqlDbSchemaService_whenCreateDatabaseSchema_thenVerifyPsqlIndexSpecificCall() throws Exception { - PsqlEntityDatabaseSchemaService service = spy(new PsqlEntityDatabaseSchemaService()); + SqlEntityDatabaseSchemaService service = spy(new SqlEntityDatabaseSchemaService()); willDoNothing().given(service).executeQueryFromFile(anyString()); service.createDatabaseSchema(); verify(service, times(1)).createDatabaseIndexes(); - verify(service, times(1)).executeQueryFromFile(PsqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL); - verify(service, times(1)).executeQueryFromFile(PsqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_SQL); - verify(service, times(1)).executeQueryFromFile(PsqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL); + verify(service, times(1)).executeQueryFromFile(SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_SQL); + verify(service, times(1)).executeQueryFromFile(SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_SQL); + verify(service, times(1)).executeQueryFromFile(SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL); verify(service, times(3)).executeQueryFromFile(anyString()); } @Test public void givenPsqlDbSchemaService_whenCreateDatabaseIndexes_thenVerifyPsqlIndexSpecificCall() throws Exception { - PsqlEntityDatabaseSchemaService service = spy(new PsqlEntityDatabaseSchemaService()); + SqlEntityDatabaseSchemaService service = spy(new SqlEntityDatabaseSchemaService()); willDoNothing().given(service).executeQueryFromFile(anyString()); service.createDatabaseIndexes(); - verify(service, times(1)).executeQueryFromFile(PsqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_SQL); - verify(service, times(1)).executeQueryFromFile(PsqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL); + verify(service, times(1)).executeQueryFromFile(SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_SQL); + verify(service, times(1)).executeQueryFromFile(SqlEntityDatabaseSchemaService.SCHEMA_ENTITIES_IDX_PSQL_ADDON_SQL); verify(service, times(2)).executeQueryFromFile(anyString()); } diff --git a/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java index 2a37fa7c2a..704e81ab9b 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/update/DefaultDataUpdateServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/service/mail/TestMailService.java b/application/src/test/java/org/thingsboard/server/service/mail/TestMailService.java index b68319fe73..9422870574 100644 --- a/application/src/test/java/org/thingsboard/server/service/mail/TestMailService.java +++ b/application/src/test/java/org/thingsboard/server/service/mail/TestMailService.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/service/queue/TbMsgPackProcessingContextTest.java b/application/src/test/java/org/thingsboard/server/service/queue/TbMsgPackProcessingContextTest.java index 4438dfc3f2..7a827f0e94 100644 --- a/application/src/test/java/org/thingsboard/server/service/queue/TbMsgPackProcessingContextTest.java +++ b/application/src/test/java/org/thingsboard/server/service/queue/TbMsgPackProcessingContextTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,7 +69,7 @@ public class TbMsgPackProcessingContextTest { TbRuleEngineSubmitStrategy strategyMock = mock(TbRuleEngineSubmitStrategy.class); when(strategyMock.getPendingMap()).thenReturn(messages); - TbMsgPackProcessingContext context = new TbMsgPackProcessingContext("Main", strategyMock); + TbMsgPackProcessingContext context = new TbMsgPackProcessingContext("Main", strategyMock, false); for (UUID uuid : messages.keySet()) { final CountDownLatch readyLatch = new CountDownLatch(parallelCount); final CountDownLatch startLatch = new CountDownLatch(1); diff --git a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java index caf4431e7d..31349ebec4 100644 --- a/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/resource/sql/BaseTbResourceServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.server.common.data.EntityInfo; -import org.thingsboard.server.common.data.OtaPackage; import org.thingsboard.server.common.data.ResourceType; import org.thingsboard.server.common.data.TbResource; import org.thingsboard.server.common.data.TbResourceInfo; @@ -173,7 +172,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(filename); resource.setData("1"); - return resourceService.saveResource(resource); + return resourceService.saveResourceInternal(resource); } @Test @@ -185,7 +184,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); Assert.assertNotNull(savedResource); Assert.assertNotNull(savedResource.getId()); @@ -197,11 +196,11 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { savedResource.setTitle("My new resource"); - resourceService.saveResource(savedResource); + resourceService.saveResourceInternal(savedResource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertEquals(foundResource.getTitle(), savedResource.getTitle()); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } @Test @@ -212,7 +211,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName("test_model.xml"); resource.setData(Base64.getEncoder().encodeToString(LWM2M_TEST_MODEL.getBytes())); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); Assert.assertNotNull(savedResource); Assert.assertNotNull(savedResource.getId()); @@ -222,7 +221,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { Assert.assertEquals("0_1.0", savedResource.getResourceKey()); Assert.assertEquals(resource.getData(), savedResource.getData()); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } @Test @@ -232,11 +231,11 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); Assert.assertEquals(TenantId.SYS_TENANT_ID, savedResource.getTenantId()); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } @Test(expected = DataValidationException.class) @@ -248,7 +247,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); TbResource resource2 = new TbResource(); resource.setTenantId(tenantId); @@ -258,9 +257,9 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setData("Test Data"); try { - resourceService.saveResource(resource2); + resourceService.saveResourceInternal(resource2); } finally { - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } } @@ -271,18 +270,18 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - resourceService.saveResource(resource); + resourceService.saveResourceInternal(resource); } @Test(expected = DataValidationException.class) public void testSaveTbResourceWithInvalidTenant() throws Exception { TbResource resource = new TbResource(); - resource.setTenantId(new TenantId(Uuids.timeBased())); + resource.setTenantId(TenantId.fromUUID(Uuids.timeBased())); resource.setResourceType(ResourceType.JKS); resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - resourceService.saveResource(resource); + resourceService.saveResourceInternal(resource); } @Test @@ -292,12 +291,12 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertNotNull(foundResource); Assert.assertEquals(savedResource, foundResource); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } @Test @@ -308,12 +307,12 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); TbResource foundResource = resourceService.getResource(tenantId, savedResource.getResourceType(), savedResource.getResourceKey()); Assert.assertNotNull(foundResource); Assert.assertEquals(savedResource, foundResource); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); } @Test @@ -323,11 +322,11 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setTitle("My resource"); resource.setFileName(DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResource savedResource = resourceService.saveResource(resource); + TbResource savedResource = resourceService.saveResourceInternal(resource); TbResource foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertNotNull(foundResource); - resourceService.deleteResource(tenantId, savedResource.getId()); + resourceService.delete(savedResource, null); foundResource = resourceService.findResourceById(tenantId, savedResource.getId()); Assert.assertNull(foundResource); } @@ -349,7 +348,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - resources.add(new TbResourceInfo(resourceService.saveResource(resource))); + resources.add(new TbResourceInfo(resourceService.saveResourceInternal(resource))); } List loadedResources = new ArrayList<>(); @@ -397,7 +396,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - TbResourceInfo tbResourceInfo = new TbResourceInfo(resourceService.saveResource(resource)); + TbResourceInfo tbResourceInfo = new TbResourceInfo(resourceService.saveResourceInternal(resource)); if (i >= 50) { resources.add(tbResourceInfo); } @@ -410,7 +409,7 @@ public class BaseTbResourceServiceTest extends AbstractControllerTest { resource.setResourceType(ResourceType.JKS); resource.setFileName(i + DEFAULT_FILE_NAME); resource.setData("Test Data"); - resources.add(new TbResourceInfo(resourceService.saveResource(resource))); + resources.add(new TbResourceInfo(resourceService.saveResourceInternal(resource))); } List loadedResources = new ArrayList<>(); diff --git a/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java b/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java new file mode 100644 index 0000000000..17803bac96 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/script/MockJsInvokeService.java @@ -0,0 +1,50 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.script; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Service; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.TenantId; + +import java.util.UUID; + +@Slf4j +@Service +@ConditionalOnProperty(prefix = "js", value = "evaluator", havingValue = "mock") +public class MockJsInvokeService implements JsInvokeService { + + @Override + public ListenableFuture eval(TenantId tenantId, JsScriptType scriptType, String scriptBody, String... argNames) { + log.warn("eval {} {} {} {}", tenantId, scriptType, scriptBody, argNames); + return Futures.immediateFuture(UUID.randomUUID()); + } + + @Override + public ListenableFuture invokeFunction(TenantId tenantId, CustomerId customerId, UUID scriptId, Object... args) { + log.warn("invokeFunction {} {} {} {}", tenantId, customerId, scriptId, args); + return Futures.immediateFuture("{}"); + } + + @Override + public ListenableFuture release(UUID scriptId) { + log.warn("release {}", scriptId); + return Futures.immediateFuture(null); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/JwtTokenFactoryTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/JwtTokenFactoryTest.java new file mode 100644 index 0000000000..f865c9b5e0 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/JwtTokenFactoryTest.java @@ -0,0 +1,165 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.security.auth; + +import io.jsonwebtoken.Claims; +import org.junit.BeforeClass; +import org.junit.Test; +import org.thingsboard.server.common.data.id.CustomerId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.data.security.model.JwtToken; +import org.thingsboard.server.config.JwtSettings; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.security.model.UserPrincipal; +import org.thingsboard.server.service.security.model.token.AccessJwtToken; +import org.thingsboard.server.service.security.model.token.JwtTokenFactory; +import org.thingsboard.server.service.security.model.token.RawAccessJwtToken; + +import java.util.Calendar; +import java.util.Date; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JwtTokenFactoryTest { + + private static JwtTokenFactory tokenFactory; + private static JwtSettings jwtSettings; + + @BeforeClass + public static void beforeAll() { + jwtSettings = new JwtSettings(); + jwtSettings.setTokenIssuer("tb"); + jwtSettings.setTokenSigningKey("abewafaf"); + jwtSettings.setTokenExpirationTime((int) TimeUnit.HOURS.toSeconds(2)); + jwtSettings.setRefreshTokenExpTime((int) TimeUnit.DAYS.toSeconds(7)); + + tokenFactory = new JwtTokenFactory(jwtSettings); + } + + @Test + public void testCreateAndParseAccessJwtToken() { + SecurityUser securityUser = new SecurityUser(); + securityUser.setId(new UserId(UUID.randomUUID())); + securityUser.setEmail("tenant@thingsboard.org"); + securityUser.setAuthority(Authority.TENANT_ADMIN); + securityUser.setTenantId(new TenantId(UUID.randomUUID())); + securityUser.setEnabled(true); + securityUser.setFirstName("A"); + securityUser.setLastName("B"); + securityUser.setUserPrincipal(new UserPrincipal(UserPrincipal.Type.USER_NAME, securityUser.getEmail())); + securityUser.setCustomerId(new CustomerId(UUID.randomUUID())); + + testCreateAndParseAccessJwtToken(securityUser); + + securityUser = new SecurityUser(securityUser, true, new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, securityUser.getEmail())); + securityUser.setFirstName(null); + securityUser.setLastName(null); + securityUser.setCustomerId(null); + + testCreateAndParseAccessJwtToken(securityUser); + } + + public void testCreateAndParseAccessJwtToken(SecurityUser securityUser) { + AccessJwtToken accessToken = tokenFactory.createAccessJwtToken(securityUser); + checkExpirationTime(accessToken, jwtSettings.getTokenExpirationTime()); + + SecurityUser parsedSecurityUser = tokenFactory.parseAccessJwtToken(new RawAccessJwtToken(accessToken.getToken())); + assertThat(parsedSecurityUser.getId()).isEqualTo(securityUser.getId()); + assertThat(parsedSecurityUser.getEmail()).isEqualTo(securityUser.getEmail()); + assertThat(parsedSecurityUser.getUserPrincipal()).matches(userPrincipal -> { + return userPrincipal.getType().equals(securityUser.getUserPrincipal().getType()) + && userPrincipal.getValue().equals(securityUser.getUserPrincipal().getValue()); + }); + assertThat(parsedSecurityUser.getAuthorities()).isEqualTo(securityUser.getAuthorities()); + assertThat(parsedSecurityUser.isEnabled()).isEqualTo(securityUser.isEnabled()); + assertThat(parsedSecurityUser.getTenantId()).isEqualTo(securityUser.getTenantId()); + assertThat(parsedSecurityUser.getCustomerId()).isEqualTo(securityUser.getCustomerId()); + assertThat(parsedSecurityUser.getFirstName()).isEqualTo(securityUser.getFirstName()); + assertThat(parsedSecurityUser.getLastName()).isEqualTo(securityUser.getLastName()); + } + + @Test + public void testCreateAndParseRefreshJwtToken() { + SecurityUser securityUser = new SecurityUser(); + securityUser.setId(new UserId(UUID.randomUUID())); + securityUser.setEmail("tenant@thingsboard.org"); + securityUser.setAuthority(Authority.TENANT_ADMIN); + securityUser.setUserPrincipal(new UserPrincipal(UserPrincipal.Type.USER_NAME, securityUser.getEmail())); + securityUser.setEnabled(true); + securityUser.setTenantId(new TenantId(UUID.randomUUID())); + securityUser.setCustomerId(new CustomerId(UUID.randomUUID())); + + JwtToken refreshToken = tokenFactory.createRefreshToken(securityUser); + checkExpirationTime(refreshToken, jwtSettings.getRefreshTokenExpTime()); + + SecurityUser parsedSecurityUser = tokenFactory.parseRefreshToken(new RawAccessJwtToken(refreshToken.getToken())); + assertThat(parsedSecurityUser.getId()).isEqualTo(securityUser.getId()); + assertThat(parsedSecurityUser.getUserPrincipal()).matches(userPrincipal -> { + return userPrincipal.getType().equals(securityUser.getUserPrincipal().getType()) + && userPrincipal.getValue().equals(securityUser.getUserPrincipal().getValue()); + }); + assertThat(parsedSecurityUser.getAuthority()).isNull(); + } + + @Test + public void testCreateAndParsePreVerificationJwtToken() { + SecurityUser securityUser = new SecurityUser(); + securityUser.setId(new UserId(UUID.randomUUID())); + securityUser.setEmail("tenant@thingsboard.org"); + securityUser.setAuthority(Authority.TENANT_ADMIN); + securityUser.setUserPrincipal(new UserPrincipal(UserPrincipal.Type.USER_NAME, securityUser.getEmail())); + securityUser.setEnabled(true); + securityUser.setTenantId(new TenantId(UUID.randomUUID())); + securityUser.setCustomerId(new CustomerId(UUID.randomUUID())); + + int tokenLifetime = (int) TimeUnit.MINUTES.toSeconds(30); + JwtToken preVerificationToken = tokenFactory.createPreVerificationToken(securityUser, tokenLifetime); + checkExpirationTime(preVerificationToken, tokenLifetime); + + SecurityUser parsedSecurityUser = tokenFactory.parseAccessJwtToken(new RawAccessJwtToken(preVerificationToken.getToken())); + assertThat(parsedSecurityUser.getId()).isEqualTo(securityUser.getId()); + assertThat(parsedSecurityUser.getAuthority()).isEqualTo(Authority.PRE_VERIFICATION_TOKEN); + assertThat(parsedSecurityUser.getTenantId()).isEqualTo(securityUser.getTenantId()); + assertThat(parsedSecurityUser.getCustomerId()).isEqualTo(securityUser.getCustomerId()); + assertThat(parsedSecurityUser.getUserPrincipal()).matches(userPrincipal -> { + return userPrincipal.getType() == UserPrincipal.Type.USER_NAME + && userPrincipal.getValue().equals(securityUser.getUserPrincipal().getValue()); + }); + } + + private void checkExpirationTime(JwtToken jwtToken, int tokenLifetime) { + Claims claims = tokenFactory.parseTokenClaims(jwtToken).getBody(); + assertThat(claims.getExpiration()).matches(actualExpirationTime -> { + Calendar expirationTime = Calendar.getInstance(); + expirationTime.setTime(new Date()); + expirationTime.add(Calendar.SECOND, tokenLifetime); + if (actualExpirationTime.equals(expirationTime.getTime())) { + return true; + } else if (actualExpirationTime.before(expirationTime.getTime())) { + int gap = 2; + expirationTime.add(Calendar.SECOND, -gap); + return actualExpirationTime.after(expirationTime.getTime()); + } else { + return false; + } + }); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/security/auth/TokenOutdatingTest.java b/application/src/test/java/org/thingsboard/server/service/security/auth/TokenOutdatingTest.java index 39abc09365..82f3e2ebcd 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/auth/TokenOutdatingTest.java +++ b/application/src/test/java/org/thingsboard/server/service/security/auth/TokenOutdatingTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/service/sms/smpp/SmppSmsSenderTest.java b/application/src/test/java/org/thingsboard/server/service/sms/smpp/SmppSmsSenderTest.java new file mode 100644 index 0000000000..7cbc8c03d2 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/sms/smpp/SmppSmsSenderTest.java @@ -0,0 +1,121 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.sms.smpp; + +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.Assertions; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.junit.MockitoJUnitRunner; +import org.smpp.Session; +import org.smpp.pdu.SubmitSMResp; +import org.thingsboard.server.common.data.sms.config.SmppSmsProviderConfiguration; + +import java.lang.reflect.Constructor; +import java.net.UnknownHostException; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SmppSmsSenderTest { + + SmppSmsSender smppSmsSender; + SmppSmsProviderConfiguration smppConfig; + Session smppSession; + + @Before + public void beforeEach() throws Exception { + Constructor constructor = SmppSmsSender.class.getDeclaredConstructor(); + constructor.setAccessible(true); + smppSmsSender = spy(constructor.newInstance()); + + smppSession = mock(Session.class); + smppSmsSender.smppSession = smppSession; + + smppConfig = new SmppSmsProviderConfiguration(); + smppSmsSender.config = smppConfig; + } + + @Test + public void testSendSms() throws Exception { + when(smppSession.isOpened()).thenReturn(true); + when(smppSession.submit(any())).thenReturn(new SubmitSMResp()); + setDefaultSmppConfig(); + + String number = "123545"; + String message = "message"; + smppSmsSender.sendSms(number, message); + + verify(smppSmsSender, never()).initSmppSession(); + verify(smppSession).submit(argThat(submitRequest -> { + try { + return submitRequest.getShortMessage().equals(message) && + submitRequest.getDestAddr().getAddress().equals(number) && + submitRequest.getServiceType().equals(smppConfig.getServiceType()) && + (StringUtils.isEmpty(smppConfig.getSourceAddress()) ? submitRequest.getSourceAddr().getAddress().equals("") + : submitRequest.getSourceAddr().getAddress().equals(smppConfig.getSourceAddress()) && + submitRequest.getSourceAddr().getTon() == smppConfig.getSourceTon() && + submitRequest.getSourceAddr().getNpi() == smppConfig.getSourceNpi()) && + submitRequest.getDestAddr().getTon() == smppConfig.getDestinationTon() && + submitRequest.getDestAddr().getNpi() == smppConfig.getDestinationNpi() && + submitRequest.getDataCoding() == smppConfig.getCodingScheme() && + submitRequest.getReplaceIfPresentFlag() == 0 && + submitRequest.getEsmClass() == 0 && + submitRequest.getProtocolId() == 0 && + submitRequest.getPriorityFlag() == 0 && + submitRequest.getRegisteredDelivery() == 0 && + submitRequest.getSmDefaultMsgId() == 0; + } catch (Exception e) { + fail(e.getMessage()); + return false; + } + })); + } + + private void setDefaultSmppConfig() { + smppConfig.setProtocolVersion("3.3"); + smppConfig.setHost("smpphost"); + smppConfig.setPort(5687); + smppConfig.setSystemId("213131"); + smppConfig.setPassword("35125q"); + + smppConfig.setSystemType(""); + smppConfig.setBindType(SmppSmsProviderConfiguration.SmppBindType.TX); + smppConfig.setServiceType(""); + + smppConfig.setSourceAddress(""); + smppConfig.setSourceTon((byte) 5); + smppConfig.setSourceNpi((byte) 0); + + smppConfig.setDestinationTon((byte) 5); + smppConfig.setDestinationNpi((byte) 0); + + smppConfig.setAddressRange(""); + smppConfig.setCodingScheme((byte) 0); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/sql/SequentialTimeseriesPersistenceTest.java b/application/src/test/java/org/thingsboard/server/service/sql/SequentialTimeseriesPersistenceTest.java new file mode 100644 index 0000000000..c1b87d9ac5 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/sql/SequentialTimeseriesPersistenceTest.java @@ -0,0 +1,205 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.service.sql; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.jetbrains.annotations.NotNull; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.rule.engine.telemetry.TbMsgTimeseriesNode; +import org.thingsboard.rule.engine.telemetry.TbMsgTimeseriesNodeConfiguration; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.Tenant; +import org.thingsboard.server.common.data.User; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.id.EntityId; +import org.thingsboard.server.common.data.kv.BasicTsKvEntry; +import org.thingsboard.server.common.data.kv.JsonDataEntry; +import org.thingsboard.server.common.data.kv.LongDataEntry; +import org.thingsboard.server.common.data.kv.TsKvEntry; +import org.thingsboard.server.common.data.security.Authority; +import org.thingsboard.server.common.msg.TbMsg; +import org.thingsboard.server.common.msg.TbMsgDataType; +import org.thingsboard.server.common.msg.TbMsgMetaData; +import org.thingsboard.server.common.msg.session.SessionMsgType; +import org.thingsboard.server.controller.AbstractControllerTest; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.dao.timeseries.TimeseriesService; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@DaoSqlTest +public class SequentialTimeseriesPersistenceTest extends AbstractControllerTest { + + final String TOTALIZER = "Totalizer"; + final int TTL = 99999; + final String GENERIC_CUMULATIVE_OBJ = "genericCumulativeObj"; + final List ts = List.of(10L, 20L, 30L, 40L, 60L, 70L, 50L, 80L); + final List msgValue = List.of(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L); + + @Autowired + TimeseriesService timeseriesService; + + TbMsgTimeseriesNodeConfiguration configuration; + Tenant savedTenant; + User tenantAdmin; + + @Before + public void beforeTest() throws Exception { + configuration = new TbMsgTimeseriesNodeConfiguration(); + configuration.setUseServerTs(true); + + loginSysAdmin(); + + Tenant tenant = new Tenant(); + tenant.setTitle("My tenant"); + savedTenant = doPost("/api/tenant", tenant, Tenant.class); + Assert.assertNotNull(savedTenant); + + tenantAdmin = new User(); + tenantAdmin.setAuthority(Authority.TENANT_ADMIN); + tenantAdmin.setTenantId(savedTenant.getId()); + tenantAdmin.setEmail("tenant2@thingsboard.org"); + tenantAdmin.setFirstName("Joe"); + tenantAdmin.setLastName("Downs"); + + tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); + } + + @After + public void afterTest() throws Exception { + loginSysAdmin(); + doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk()); + } + + @Test + public void testSequentialTimeseriesPersistence() throws Exception { + Asset asset = saveAsset("Asset"); + + Device deviceA = saveDevice("Device A"); + Device deviceB = saveDevice("Device B"); + Device deviceC = saveDevice("Device C"); + Device deviceD = saveDevice("Device D"); + List devices = List.of(deviceA, deviceB, deviceC, deviceD); + + for (int i = 0; i < 2; i++) { + int idx = i * devices.size(); + saveLatestTsForAssetAndDevice(devices, asset, idx); + checkDiffBetweenLatestTsForDevicesAndAsset(devices, asset); + } + } + + Device saveDevice(String name) throws Exception { + Device device = new Device(); + device.setName(name); + device.setType("default"); + Device savedDevice = doPost("/api/device", device, Device.class); + Assert.assertNotNull(savedDevice); + return savedDevice; + } + + Asset saveAsset(String name) throws Exception { + Asset asset = new Asset(); + asset.setName(name); + asset.setType("default"); + Asset savedAsset = doPost("/api/asset", asset, Asset.class); + Assert.assertNotNull(savedAsset); + return savedAsset; + } + + void saveLatestTsForAssetAndDevice(List devices, Asset asset, int idx) throws ExecutionException, InterruptedException, TimeoutException { + for (Device device : devices) { + TbMsg tbMsg = TbMsg.newMsg(SessionMsgType.POST_TELEMETRY_REQUEST.name(), + device.getId(), + getTbMsgMetadata(device.getName(), ts.get(idx)), + TbMsgDataType.JSON, + getTbMsgData(msgValue.get(idx))); + saveDeviceTsEntry(device.getId(), tbMsg, msgValue.get(idx)); + saveAssetTsEntry(asset, device.getName(), msgValue.get(idx), TbMsgTimeseriesNode.computeTs(tbMsg, configuration.isUseServerTs())); + idx++; + } + } + + void checkDiffBetweenLatestTsForDevicesAndAsset(List devices, Asset asset) throws ExecutionException, InterruptedException, TimeoutException { + TsKvEntry assetTsKvEntry = getTsKvLatest(asset.getId(), GENERIC_CUMULATIVE_OBJ); + Assert.assertTrue(assetTsKvEntry.getJsonValue().isPresent()); + JsonObject assetJsonObject = new JsonParser().parse(assetTsKvEntry.getJsonValue().get()).getAsJsonObject(); + for (Device device : devices) { + Long assetValue = assetJsonObject.get(device.getName()).getAsLong(); + TsKvEntry deviceLatest = getTsKvLatest(device.getId(), TOTALIZER); + Assert.assertTrue(deviceLatest.getLongValue().isPresent()); + Long deviceValue = deviceLatest.getLongValue().get(); + Assert.assertEquals(assetValue, deviceValue); + } + } + + String getTbMsgData(long value) { + return "{\"Totalizer\": " + value + "}"; + } + + TbMsgMetaData getTbMsgMetadata(String name, long ts) { + Map metadata = new HashMap<>(); + metadata.put("deviceName", name); + metadata.put("ts", String.valueOf(ts)); + return new TbMsgMetaData(metadata); + } + + void saveDeviceTsEntry(EntityId entityId, TbMsg tbMsg, long value) throws ExecutionException, InterruptedException, TimeoutException { + TsKvEntry tsKvEntry = new BasicTsKvEntry(TbMsgTimeseriesNode.computeTs(tbMsg, configuration.isUseServerTs()), new LongDataEntry(TOTALIZER, value)); + saveTimeseries(entityId, tsKvEntry); + } + + void saveAssetTsEntry(Asset asset, String key, long value, long ts) throws ExecutionException, InterruptedException, TimeoutException { + Optional tsKvEntryOpt = getTsKvLatest(asset.getId(), GENERIC_CUMULATIVE_OBJ).getJsonValue(); + TsKvEntry saveTsKvEntry = new BasicTsKvEntry(ts, new JsonDataEntry(GENERIC_CUMULATIVE_OBJ, getJsonObject(key, value, tsKvEntryOpt).toString())); + saveTimeseries(asset.getId(), saveTsKvEntry); + } + + @NotNull + JsonObject getJsonObject(String key, long value, Optional tsKvEntryOpt) { + JsonObject jsonObject = new JsonObject(); + if (tsKvEntryOpt.isPresent()) { + jsonObject = new JsonParser().parse(tsKvEntryOpt.get()).getAsJsonObject(); + } + jsonObject.addProperty(key, value); + return jsonObject; + } + + void saveTimeseries(EntityId entityId, TsKvEntry saveTsKvEntry) throws InterruptedException, ExecutionException, TimeoutException { + timeseriesService.save(savedTenant.getId(), entityId, List.of(saveTsKvEntry), TTL).get(TIMEOUT, TimeUnit.SECONDS); + } + + TsKvEntry getTsKvLatest(EntityId entityId, String key) throws InterruptedException, ExecutionException, TimeoutException { + List tsKvEntries = timeseriesService.findLatest( + savedTenant.getTenantId(), + entityId, + List.of(key)).get(TIMEOUT, TimeUnit.SECONDS); + Assert.assertEquals(1, tsKvEntries.size()); + return tsKvEntries.get(0); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/state/DefaultDeviceStateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/state/DefaultDeviceStateServiceTest.java index ed32020fb7..89a19d0e58 100644 --- a/application/src/test/java/org/thingsboard/server/service/state/DefaultDeviceStateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/state/DefaultDeviceStateServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/service/ttl/EventsCleanUpServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ttl/EventsCleanUpServiceTest.java index 422d5ef358..0d115ded7d 100644 --- a/application/src/test/java/org/thingsboard/server/service/ttl/EventsCleanUpServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ttl/EventsCleanUpServiceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,7 +42,6 @@ public class EventsCleanUpServiceTest { public void givenInterval_whenRandomDelay_ThenDelayInInterval() { log.info("randomDelay {}", randomDelayMs); log.info("executionIntervalMs {}", executionIntervalMs); - assertThat(executionIntervalMs, is(2220000L)); assertThat(randomDelayMs, greaterThanOrEqualTo(0L)); assertThat(randomDelayMs, lessThanOrEqualTo(executionIntervalMs)); } diff --git a/application/src/test/java/org/thingsboard/server/system/BaseHttpDeviceApiTest.java b/application/src/test/java/org/thingsboard/server/system/BaseHttpDeviceApiTest.java index f31e872773..06f57b55f6 100644 --- a/application/src/test/java/org/thingsboard/server/system/BaseHttpDeviceApiTest.java +++ b/application/src/test/java/org/thingsboard/server/system/BaseHttpDeviceApiTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.thingsboard.server.system; import org.junit.Before; import org.junit.Test; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.thingsboard.server.common.data.Device; @@ -35,6 +36,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. /** * @author Andrew Shvayka */ +@TestPropertySource(properties = { + "transport.http.enabled=true", +}) public abstract class BaseHttpDeviceApiTest extends AbstractControllerTest { private static final AtomicInteger idSeq = new AtomicInteger(new Random(System.currentTimeMillis()).nextInt()); diff --git a/application/src/test/java/org/thingsboard/server/system/SystemSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/system/SystemSqlTestSuite.java deleted file mode 100644 index 52f7e07f6a..0000000000 --- a/application/src/test/java/org/thingsboard/server/system/SystemSqlTestSuite.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.system; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -/** - * Created by Valerii Sosliuk on 6/27/2017. - */ -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ - "org.thingsboard.server.system.sql.*SqlTest", -}) -public class SystemSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/system/sql/DeviceApiSqlTest.java b/application/src/test/java/org/thingsboard/server/system/sql/DeviceApiSqlTest.java index 2e70dba6a4..5c41a8c5b2 100644 --- a/application/src/test/java/org/thingsboard/server/system/sql/DeviceApiSqlTest.java +++ b/application/src/test/java/org/thingsboard/server/system/sql/DeviceApiSqlTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/AbstractTransportIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/AbstractTransportIntegrationTest.java index 5931e96c75..09acd96d47 100644 --- a/application/src/test/java/org/thingsboard/server/transport/AbstractTransportIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/AbstractTransportIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,6 @@ package org.thingsboard.server.transport; import lombok.extern.slf4j.Slf4j; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; -import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.gen.transport.TransportProtos; @@ -27,8 +25,6 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @Slf4j public abstract class AbstractTransportIntegrationTest extends AbstractControllerTest { @@ -95,21 +91,11 @@ public abstract class AbstractTransportIntegrationTest extends AbstractControlle " optional string params = 3;\n" + "}"; - protected Tenant savedTenant; - protected User tenantAdmin; - protected Device savedDevice; protected String accessToken; protected DeviceProfile deviceProfile; - protected void processAfterTest() throws Exception { - loginSysAdmin(); - if (savedTenant != null) { - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk()); - } - } - protected List getKvProtos(List expectedKeys) { List keyValueProtos = new ArrayList<>(); TransportProtos.KeyValueProto strKeyValueProto = getKeyValueProto(expectedKeys.get(0), "value1", TransportProtos.KeyValueType.STRING_V); diff --git a/application/src/test/java/org/thingsboard/server/transport/TransportNoSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/transport/TransportNoSqlTestSuite.java index f5e02c146d..255057cc2f 100644 --- a/application/src/test/java/org/thingsboard/server/transport/TransportNoSqlTestSuite.java +++ b/application/src/test/java/org/thingsboard/server/transport/TransportNoSqlTestSuite.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,4 @@ public class TransportNoSqlTestSuite { ), "cassandra-test.yaml", 30000l); - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - } diff --git a/application/src/test/java/org/thingsboard/server/transport/TransportSqlTestSuite.java b/application/src/test/java/org/thingsboard/server/transport/TransportSqlTestSuite.java deleted file mode 100644 index a97a66cc13..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/TransportSqlTestSuite.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport; - -import org.junit.BeforeClass; -import org.junit.extensions.cpsuite.ClasspathSuite; -import org.junit.runner.RunWith; -import org.thingsboard.server.queue.memory.InMemoryStorage; - -@RunWith(ClasspathSuite.class) -@ClasspathSuite.ClassnameFilters({ - "org.thingsboard.server.transport.*.rpc.sql.*Test", - "org.thingsboard.server.transport.*.telemetry.timeseries.sql.*Test", - "org.thingsboard.server.transport.*.telemetry.attributes.sql.*Test", - "org.thingsboard.server.transport.*.attributes.updates.sql.*Test", - "org.thingsboard.server.transport.*.attributes.request.sql.*Test", - "org.thingsboard.server.transport.*.claim.sql.*Test", - "org.thingsboard.server.transport.*.provision.sql.*Test", - "org.thingsboard.server.transport.*.credentials.sql.*Test", - "org.thingsboard.server.transport.lwm2m.*.sql.*Test" -}) -public class TransportSqlTestSuite { - - @BeforeClass - public static void cleanupInMemStorage() { - InMemoryStorage.getInstance().cleanup(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/AbstractCoapIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/AbstractCoapIntegrationTest.java index 8271fc6f95..b3ab39fd51 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/AbstractCoapIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/AbstractCoapIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,16 @@ package org.thingsboard.server.transport.coap; import lombok.extern.slf4j.Slf4j; import org.eclipse.californium.core.CoapClient; -import org.junit.Assert; -import org.springframework.util.StringUtils; +import org.junit.After; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.DeviceProfileInfo; import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.DeviceProfileType; import org.thingsboard.server.common.data.DeviceTransportType; -import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.device.profile.AllowCreateNewDevicesDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.CoapDeviceProfileTransportConfiguration; @@ -41,7 +40,6 @@ import org.thingsboard.server.common.data.device.profile.EfentoCoapDeviceTypeCon import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; -import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.transport.AbstractTransportIntegrationTest; @@ -49,138 +47,114 @@ import org.thingsboard.server.transport.AbstractTransportIntegrationTest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +@TestPropertySource(properties = { + "transport.coap.enabled=true", +}) @Slf4j public abstract class AbstractCoapIntegrationTest extends AbstractTransportIntegrationTest { + protected final byte[] EMPTY_PAYLOAD = new byte[0]; + protected CoapClient client; - @Override protected void processAfterTest() throws Exception { if (client != null) { client.shutdown(); } - super.processAfterTest(); - } - - protected void processBeforeTest(String deviceName, CoapDeviceType coapDeviceType, TransportPayloadType payloadType) throws Exception { - this.processBeforeTest(deviceName, coapDeviceType, payloadType, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED); } - protected void processBeforeTest(String deviceName, - CoapDeviceType coapDeviceType, - TransportPayloadType payloadType, - String telemetryProtoSchema, - String attributesProtoSchema, - String rpcResponseProtoSchema, - String rpcRequestProtoSchema, - String provisionKey, - String provisionSecret, - DeviceProfileProvisionType provisionType - ) throws Exception { - loginSysAdmin(); - - Tenant tenant = new Tenant(); - tenant.setTitle("My tenant"); - savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedTenant); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant" + atomicInteger.getAndIncrement() + "@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); - - tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); - - Device device = new Device(); - device.setName(deviceName); - device.setType("default"); - - if (coapDeviceType != null) { - DeviceProfile coapDeviceProfile = createCoapDeviceProfile(payloadType, coapDeviceType, provisionSecret, provisionType, provisionKey, attributesProtoSchema, telemetryProtoSchema, rpcResponseProtoSchema, rpcRequestProtoSchema); - deviceProfile = doPost("/api/deviceProfile", coapDeviceProfile, DeviceProfile.class); - device.setType(deviceProfile.getName()); - device.setDeviceProfileId(deviceProfile.getId()); - } - - savedDevice = doPost("/api/device", device, Device.class); - + protected void processBeforeTest(CoapTestConfigProperties config) throws Exception { + loginTenantAdmin(); + deviceProfile = createCoapDeviceProfile(config); + assertNotNull(deviceProfile); + savedDevice = createDevice(config.getDeviceName(), deviceProfile.getName()); DeviceCredentials deviceCredentials = doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); - + assertNotNull(deviceCredentials); assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); accessToken = deviceCredentials.getCredentialsId(); assertNotNull(accessToken); - } - protected DeviceProfile createCoapDeviceProfile(TransportPayloadType transportPayloadType, CoapDeviceType coapDeviceType, - String provisionSecret, DeviceProfileProvisionType provisionType, - String provisionKey, String attributesProtoSchema, - String telemetryProtoSchema, String rpcResponseProtoSchema, String rpcRequestProtoSchema) { - DeviceProfile deviceProfile = new DeviceProfile(); - deviceProfile.setName(transportPayloadType.name()); - deviceProfile.setType(DeviceProfileType.DEFAULT); - deviceProfile.setProvisionType(provisionType); - deviceProfile.setProvisionDeviceKey(provisionKey); - deviceProfile.setDescription(transportPayloadType.name() + " Test"); - DeviceProfileData deviceProfileData = new DeviceProfileData(); - DefaultDeviceProfileConfiguration configuration = new DefaultDeviceProfileConfiguration(); - deviceProfile.setTransportType(DeviceTransportType.COAP); - CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = new CoapDeviceProfileTransportConfiguration(); - CoapDeviceTypeConfiguration coapDeviceTypeConfiguration; - if (CoapDeviceType.DEFAULT.equals(coapDeviceType)) { - DefaultCoapDeviceTypeConfiguration defaultCoapDeviceTypeConfiguration = new DefaultCoapDeviceTypeConfiguration(); - TransportPayloadTypeConfiguration transportPayloadTypeConfiguration; - if (TransportPayloadType.PROTOBUF.equals(transportPayloadType)) { - ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = new ProtoTransportPayloadConfiguration(); - if (StringUtils.isEmpty(telemetryProtoSchema)) { - telemetryProtoSchema = DEVICE_TELEMETRY_PROTO_SCHEMA; - } - if (StringUtils.isEmpty(attributesProtoSchema)) { - attributesProtoSchema = DEVICE_ATTRIBUTES_PROTO_SCHEMA; - } - if (StringUtils.isEmpty(rpcResponseProtoSchema)) { - rpcResponseProtoSchema = DEVICE_RPC_RESPONSE_PROTO_SCHEMA; - } - if (StringUtils.isEmpty(rpcRequestProtoSchema)) { - rpcRequestProtoSchema = DEVICE_RPC_REQUEST_PROTO_SCHEMA; + protected DeviceProfile createCoapDeviceProfile(CoapTestConfigProperties config) throws Exception { + CoapDeviceType coapDeviceType = config.getCoapDeviceType(); + if (coapDeviceType == null) { + DeviceProfileInfo defaultDeviceProfileInfo = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); + return doGet("/api/deviceProfile/" + defaultDeviceProfileInfo.getId().getId(), DeviceProfile.class); + } else { + TransportPayloadType transportPayloadType = config.getTransportPayloadType(); + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName(transportPayloadType.name()); + deviceProfile.setType(DeviceProfileType.DEFAULT); + DeviceProfileProvisionType provisionType = config.getProvisionType() != null ? + config.getProvisionType() : DeviceProfileProvisionType.DISABLED; + deviceProfile.setProvisionType(provisionType); + deviceProfile.setProvisionDeviceKey(config.getProvisionKey()); + deviceProfile.setDescription(transportPayloadType.name() + " Test"); + DeviceProfileData deviceProfileData = new DeviceProfileData(); + DefaultDeviceProfileConfiguration configuration = new DefaultDeviceProfileConfiguration(); + deviceProfile.setTransportType(DeviceTransportType.COAP); + CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = new CoapDeviceProfileTransportConfiguration(); + CoapDeviceTypeConfiguration coapDeviceTypeConfiguration; + if (CoapDeviceType.DEFAULT.equals(coapDeviceType)) { + DefaultCoapDeviceTypeConfiguration defaultCoapDeviceTypeConfiguration = new DefaultCoapDeviceTypeConfiguration(); + TransportPayloadTypeConfiguration transportPayloadTypeConfiguration; + if (TransportPayloadType.PROTOBUF.equals(transportPayloadType)) { + ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = new ProtoTransportPayloadConfiguration(); + String telemetryProtoSchema = config.getTelemetryProtoSchema(); + String attributesProtoSchema = config.getAttributesProtoSchema(); + String rpcResponseProtoSchema = config.getRpcResponseProtoSchema(); + String rpcRequestProtoSchema = config.getRpcRequestProtoSchema(); + protoTransportPayloadConfiguration.setDeviceTelemetryProtoSchema( + telemetryProtoSchema != null ? telemetryProtoSchema : DEVICE_TELEMETRY_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceAttributesProtoSchema( + attributesProtoSchema != null ? attributesProtoSchema : DEVICE_ATTRIBUTES_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceRpcResponseProtoSchema( + rpcResponseProtoSchema != null ? rpcResponseProtoSchema : DEVICE_RPC_RESPONSE_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceRpcRequestProtoSchema( + rpcRequestProtoSchema != null ? rpcRequestProtoSchema : DEVICE_RPC_REQUEST_PROTO_SCHEMA + ); + transportPayloadTypeConfiguration = protoTransportPayloadConfiguration; + } else { + transportPayloadTypeConfiguration = new JsonTransportPayloadConfiguration(); } - protoTransportPayloadConfiguration.setDeviceTelemetryProtoSchema(telemetryProtoSchema); - protoTransportPayloadConfiguration.setDeviceAttributesProtoSchema(attributesProtoSchema); - protoTransportPayloadConfiguration.setDeviceRpcResponseProtoSchema(rpcResponseProtoSchema); - protoTransportPayloadConfiguration.setDeviceRpcRequestProtoSchema(rpcRequestProtoSchema); - transportPayloadTypeConfiguration = protoTransportPayloadConfiguration; + defaultCoapDeviceTypeConfiguration.setTransportPayloadTypeConfiguration(transportPayloadTypeConfiguration); + coapDeviceTypeConfiguration = defaultCoapDeviceTypeConfiguration; } else { - transportPayloadTypeConfiguration = new JsonTransportPayloadConfiguration(); + coapDeviceTypeConfiguration = new EfentoCoapDeviceTypeConfiguration(); } - defaultCoapDeviceTypeConfiguration.setTransportPayloadTypeConfiguration(transportPayloadTypeConfiguration); - coapDeviceTypeConfiguration = defaultCoapDeviceTypeConfiguration; - } else { - coapDeviceTypeConfiguration = new EfentoCoapDeviceTypeConfiguration(); - } - coapDeviceProfileTransportConfiguration.setCoapDeviceTypeConfiguration(coapDeviceTypeConfiguration); - deviceProfileData.setTransportConfiguration(coapDeviceProfileTransportConfiguration); - DeviceProfileProvisionConfiguration provisionConfiguration; - switch (provisionType) { - case ALLOW_CREATE_NEW_DEVICES: - provisionConfiguration = new AllowCreateNewDevicesDeviceProfileProvisionConfiguration(provisionSecret); - break; - case CHECK_PRE_PROVISIONED_DEVICES: - provisionConfiguration = new CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration(provisionSecret); - break; - case DISABLED: - default: - provisionConfiguration = new DisabledDeviceProfileProvisionConfiguration(provisionSecret); - break; + coapDeviceProfileTransportConfiguration.setCoapDeviceTypeConfiguration(coapDeviceTypeConfiguration); + deviceProfileData.setTransportConfiguration(coapDeviceProfileTransportConfiguration); + DeviceProfileProvisionConfiguration provisionConfiguration; + switch (provisionType) { + case ALLOW_CREATE_NEW_DEVICES: + provisionConfiguration = new AllowCreateNewDevicesDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; + case CHECK_PRE_PROVISIONED_DEVICES: + provisionConfiguration = new CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; + case DISABLED: + default: + provisionConfiguration = new DisabledDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; + } + deviceProfileData.setProvisionConfiguration(provisionConfiguration); + deviceProfileData.setConfiguration(configuration); + deviceProfile.setProfileData(deviceProfileData); + deviceProfile.setDefault(false); + deviceProfile.setDefaultRuleChainId(null); + return doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); } - deviceProfileData.setProvisionConfiguration(provisionConfiguration); - deviceProfileData.setConfiguration(configuration); - deviceProfile.setProfileData(deviceProfileData); - deviceProfile.setDefault(false); - deviceProfile.setDefaultRuleChainId(null); - return deviceProfile; + } + + protected Device createDevice(String name, String type) throws Exception { + Device device = new Device(); + device.setName(name); + device.setType(type); + return doPost("/api/device", device, Device.class); } protected CoapClient getCoapClient(FeatureType featureType) { diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/CoapTestConfigProperties.java b/application/src/test/java/org/thingsboard/server/transport/coap/CoapTestConfigProperties.java new file mode 100644 index 0000000000..c387a3b41a --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/coap/CoapTestConfigProperties.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.coap; + +import lombok.Builder; +import lombok.Data; +import org.thingsboard.server.common.data.CoapDeviceType; +import org.thingsboard.server.common.data.DeviceProfileProvisionType; +import org.thingsboard.server.common.data.TransportPayloadType; + +@Data +@Builder +public class CoapTestConfigProperties { + + String deviceName; + + CoapDeviceType coapDeviceType; + + TransportPayloadType transportPayloadType; + + String telemetryTopicFilter; + String attributesTopicFilter; + + String telemetryProtoSchema; + String attributesProtoSchema; + String rpcResponseProtoSchema; + String rpcRequestProtoSchema; + + DeviceProfileProvisionType provisionType; + String provisionKey; + String provisionSecret; + +} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/AbstractCoapAttributesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/AbstractCoapAttributesIntegrationTest.java index 53d345ec3d..9d0078aa3f 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/AbstractCoapAttributesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/AbstractCoapAttributesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,8 @@ package org.thingsboard.server.transport.coap.attributes; import lombok.extern.slf4j.Slf4j; -import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; -import org.thingsboard.server.common.data.CoapDeviceType; -import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import java.util.ArrayList; import java.util.List; @@ -30,14 +28,6 @@ public abstract class AbstractCoapAttributesIntegrationTest extends AbstractCoap protected static final String POST_ATTRIBUTES_PAYLOAD = "{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73," + "\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}"; - protected void processBeforeTest(String deviceName, CoapDeviceType coapDeviceType, TransportPayloadType payloadType) throws Exception { - super.processBeforeTest(deviceName, coapDeviceType, payloadType); - } - - protected void processAfterTest() throws Exception { - super.processAfterTest(); - } - protected List getTsKvProtoList() { TransportProtos.TsKvProto tsKvProtoAttribute1 = getTsKvProto("attribute1", "value1", TransportProtos.KeyValueType.STRING_V); TransportProtos.TsKvProto tsKvProtoAttribute2 = getTsKvProto("attribute2", "true", TransportProtos.KeyValueType.BOOLEAN_V); diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestIntegrationTest.java similarity index 89% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestIntegrationTest.java index bced75775e..977502e0e6 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.thingsboard.server.transport.coap.attributes.request; import com.fasterxml.jackson.core.type.TypeReference; import com.google.protobuf.InvalidProtocolBufferException; import lombok.extern.slf4j.Slf4j; -import org.eclipse.californium.core.CoapClient; import org.eclipse.californium.core.CoapResponse; import org.eclipse.californium.core.coap.CoAP; import org.eclipse.californium.core.coap.MediaTypeRegistry; @@ -26,6 +25,8 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import org.thingsboard.server.transport.coap.attributes.AbstractCoapAttributesIntegrationTest; import org.thingsboard.server.common.msg.session.FeatureType; @@ -37,13 +38,17 @@ import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapAttributesRequestIntegrationTest extends AbstractCoapAttributesIntegrationTest { +@DaoSqlTest +public class CoapAttributesRequestIntegrationTest extends AbstractCoapAttributesIntegrationTest { protected static final long CLIENT_REQUEST_TIMEOUT = 60000L; @Before public void beforeTest() throws Exception { - processBeforeTest("Test Request attribute values from the server", null, null); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server") + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestJsonIntegrationTest.java similarity index 64% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestJsonIntegrationTest.java index eb479fa2ad..e421fbf1a0 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,21 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapAttributesRequestJsonIntegrationTest extends AbstractCoapAttributesRequestIntegrationTest { +@DaoSqlTest +public class CoapAttributesRequestJsonIntegrationTest extends CoapAttributesRequestIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Request attribute values from the server json", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server json") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestProtoIntegrationTest.java similarity index 92% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestProtoIntegrationTest.java index a8277fe0c7..7bdcce1400 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/AbstractCoapAttributesRequestProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/CoapAttributesRequestProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,9 @@ import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportC import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.util.List; import java.util.stream.Collectors; @@ -47,7 +49,8 @@ import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapAttributesRequestProtoIntegrationTest extends AbstractCoapAttributesRequestIntegrationTest { +@DaoSqlTest +public class CoapAttributesRequestProtoIntegrationTest extends CoapAttributesRequestIntegrationTest { public static final String ATTRIBUTES_SCHEMA_STR = "syntax =\"proto3\";\n" + "\n" + @@ -73,8 +76,13 @@ public abstract class AbstractCoapAttributesRequestProtoIntegrationTest extends @Before @Override public void beforeTest() throws Exception { - processBeforeTest("Test Request attribute values from the server proto", CoapDeviceType.DEFAULT, - TransportPayloadType.PROTOBUF, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .build(); + processBeforeTest(configProperties); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestJsonSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestJsonSqlIntegrationTest.java deleted file mode 100644 index 5e9b788ec0..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestJsonSqlIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.attributes.request.sql; - -import org.thingsboard.server.transport.coap.attributes.request.AbstractCoapAttributesRequestJsonIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapAttributesRequestJsonSqlIntegrationTest extends AbstractCoapAttributesRequestJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestProtoSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestProtoSqlIntegrationTest.java deleted file mode 100644 index e08a09bcb2..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestProtoSqlIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.attributes.request.sql; - -import org.thingsboard.server.transport.coap.attributes.request.AbstractCoapAttributesRequestProtoIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapAttributesRequestProtoSqlIntegrationTest extends AbstractCoapAttributesRequestProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesIntegrationTest.java similarity index 74% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesIntegrationTest.java index 025819e104..bbbfad3c65 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,18 +17,25 @@ package org.thingsboard.server.transport.coap.attributes.updates; import com.google.protobuf.InvalidProtocolBufferException; import lombok.extern.slf4j.Slf4j; -import org.eclipse.californium.core.CoapClient; +import org.awaitility.Awaitility; import org.eclipse.californium.core.CoapHandler; import org.eclipse.californium.core.CoapObserveRelation; import org.eclipse.californium.core.CoapResponse; import org.eclipse.californium.core.coap.CoAP; import org.eclipse.californium.core.coap.Request; +import org.eclipse.californium.core.server.resources.Resource; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.transport.coap.attributes.AbstractCoapAttributesIntegrationTest; +import org.thingsboard.server.coapserver.DefaultCoapServerService; import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.common.transport.service.DefaultTransportService; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; +import org.thingsboard.server.transport.coap.CoapTransportResource; +import org.thingsboard.server.transport.coap.attributes.AbstractCoapAttributesIntegrationTest; import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; @@ -37,19 +44,36 @@ import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.spy; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapAttributesUpdatesIntegrationTest extends AbstractCoapAttributesIntegrationTest { +@DaoSqlTest +public class CoapAttributesUpdatesIntegrationTest extends AbstractCoapAttributesIntegrationTest { private static final String RESPONSE_ATTRIBUTES_PAYLOAD_DELETED = "{\"deleted\":[\"attribute5\"]}"; protected static final String POST_ATTRIBUTES_PAYLOAD_ON_CURRENT_STATE_NOTIFICATION = "{\"attribute1\":\"value\",\"attribute2\":false,\"attribute3\":41.0,\"attribute4\":72," + "\"attribute5\":{\"someNumber\":41,\"someArray\":[],\"someNestedObject\":{\"key\":\"value\"}}}"; + CoapTransportResource coapTransportResource; + + @Autowired + DefaultCoapServerService defaultCoapServerService; + + @Autowired + DefaultTransportService defaultTransportService; + @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", null, null); + Resource api = defaultCoapServerService.getCoapServer().getRoot().getChild("api"); + coapTransportResource = spy( (CoapTransportResource) api.getChild("v1") ); + api.delete(api.getChild("v1") ); + api.add(coapTransportResource); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .build(); + processBeforeTest(configProperties); } @After @@ -89,21 +113,23 @@ public abstract class AbstractCoapAttributesUpdatesIntegrationTest extends Abstr } latch = new CountDownLatch(1); - + int expectedObserveCnt = callback.getObserve().intValue() + 1; doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); latch.await(3, TimeUnit.SECONDS); - validateUpdateAttributesResponse(callback); + validateUpdateAttributesResponse(callback, expectedObserveCnt); - latch = new CountDownLatch(1); + latch = new CountDownLatch(1); + int expectedObserveBeforeDeleteCnt = callback.getObserve().intValue() + 1; doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=attribute5", String.class); latch.await(3, TimeUnit.SECONDS); - validateDeleteAttributesResponse(callback); - + validateDeleteAttributesResponse(callback, expectedObserveBeforeDeleteCnt); observeRelation.proactiveCancel(); assertTrue(observeRelation.isCanceled()); + + awaitClientAfterCancelObserve(); } protected void validateCurrentStateAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { @@ -124,20 +150,20 @@ public abstract class AbstractCoapAttributesUpdatesIntegrationTest extends Abstr assertEquals("{}", response); } - protected void validateUpdateAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { + protected void validateUpdateAttributesResponse(TestCoapCallback callback, int expectedObserveCnt) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(CoAP.ResponseCode.CONTENT, callback.getResponseCode()); - assertEquals(1, callback.getObserve().intValue()); + assertEquals(expectedObserveCnt, callback.getObserve().intValue()); String response = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); assertEquals(JacksonUtil.toJsonNode(POST_ATTRIBUTES_PAYLOAD), JacksonUtil.toJsonNode(response)); } - protected void validateDeleteAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { + protected void validateDeleteAttributesResponse(TestCoapCallback callback, int expectedObserveCnt) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(CoAP.ResponseCode.CONTENT, callback.getResponseCode()); - assertEquals(2, callback.getObserve().intValue()); + assertEquals(expectedObserveCnt, callback.getObserve().intValue()); String response = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); assertEquals(JacksonUtil.toJsonNode(RESPONSE_ATTRIBUTES_PAYLOAD_DELETED), JacksonUtil.toJsonNode(response)); } @@ -180,4 +206,13 @@ public abstract class AbstractCoapAttributesUpdatesIntegrationTest extends Abstr } } + + private void awaitClientAfterCancelObserve() { + Awaitility.await("awaitClientAfterCancelObserve") + .pollInterval(10, TimeUnit.MILLISECONDS) + .atMost(5, TimeUnit.SECONDS) + .until(()->{ + log.trace("awaiting defaultTransportService.sessions is empty"); + return defaultTransportService.sessions.isEmpty();}); + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesJsonIntegrationTest.java similarity index 69% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesJsonIntegrationTest.java index 24cc40f5c7..4ab052db46 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,21 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapAttributesUpdatesJsonIntegrationTest extends AbstractCoapAttributesUpdatesIntegrationTest { +@DaoSqlTest +public class CoapAttributesUpdatesJsonIntegrationTest extends CoapAttributesUpdatesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesProtoIntegrationTest.java similarity index 87% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesProtoIntegrationTest.java index c3e56ccc62..4d9970b2dc 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/AbstractCoapAttributesUpdatesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/CoapAttributesUpdatesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,25 +23,31 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; @Slf4j -public abstract class AbstractCoapAttributesUpdatesProtoIntegrationTest extends AbstractCoapAttributesUpdatesIntegrationTest { +@DaoSqlTest +public class CoapAttributesUpdatesProtoIntegrationTest extends CoapAttributesUpdatesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); } @After @@ -88,17 +94,17 @@ public abstract class AbstractCoapAttributesUpdatesProtoIntegrationTest extends } protected void validateEmptyCurrentStateAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { - assertNull(callback.getPayloadBytes()); + assertArrayEquals(EMPTY_PAYLOAD, callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(CoAP.ResponseCode.CONTENT, callback.getResponseCode()); assertEquals(0, callback.getObserve().intValue()); } - protected void validateUpdateAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { + protected void validateUpdateAttributesResponse(TestCoapCallback callback, int expectedObserveCnt) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(CoAP.ResponseCode.CONTENT, callback.getResponseCode()); - assertEquals(1, callback.getObserve().intValue()); + assertEquals(expectedObserveCnt, callback.getObserve().intValue()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); List tsKvProtoList = getTsKvProtoList(); attributeUpdateNotificationMsgBuilder.addAllSharedUpdated(tsKvProtoList); @@ -114,11 +120,11 @@ public abstract class AbstractCoapAttributesUpdatesProtoIntegrationTest extends } - protected void validateDeleteAttributesResponse(TestCoapCallback callback) throws InvalidProtocolBufferException { + protected void validateDeleteAttributesResponse(TestCoapCallback callback, int expectedObserveCnt) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(CoAP.ResponseCode.CONTENT, callback.getResponseCode()); - assertEquals(2, callback.getObserve().intValue()); + assertEquals(expectedObserveCnt, callback.getObserve().intValue()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); attributeUpdateNotificationMsgBuilder.addSharedDeleted("attribute5"); diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlIntegrationTest.java deleted file mode 100644 index f0fce3a0c5..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.attributes.updates.sql; - -import org.thingsboard.server.transport.coap.attributes.updates.AbstractCoapAttributesUpdatesIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapAttributesUpdatesSqlIntegrationTest extends AbstractCoapAttributesUpdatesIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlJsonIntegrationTest.java deleted file mode 100644 index 9ca721503d..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlJsonIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.attributes.updates.sql; - -import org.thingsboard.server.transport.coap.attributes.updates.AbstractCoapAttributesUpdatesJsonIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapAttributesUpdatesSqlJsonIntegrationTest extends AbstractCoapAttributesUpdatesJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlProtoIntegrationTest.java deleted file mode 100644 index cf8e453973..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/updates/sql/CoapAttributesUpdatesSqlProtoIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.attributes.updates.sql; - -import org.thingsboard.server.transport.coap.attributes.updates.AbstractCoapAttributesUpdatesProtoIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapAttributesUpdatesSqlProtoIntegrationTest extends AbstractCoapAttributesUpdatesProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimDeviceTest.java similarity index 90% rename from application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimDeviceTest.java index 30c30070b9..de9c024bb8 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,6 @@ import org.eclipse.californium.elements.exception.ConnectorException; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import org.thingsboard.server.common.data.ClaimRequest; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; @@ -33,6 +32,9 @@ import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.dao.device.claim.ClaimResponse; import org.thingsboard.server.dao.device.claim.ClaimResult; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.io.IOException; @@ -41,7 +43,8 @@ import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapClaimDeviceTest extends AbstractCoapIntegrationTest { +@DaoSqlTest +public class CoapClaimDeviceTest extends AbstractCoapIntegrationTest { protected static final String CUSTOMER_USER_PASSWORD = "customerUser123!"; @@ -50,21 +53,24 @@ public abstract class AbstractCoapClaimDeviceTest extends AbstractCoapIntegratio @Before public void beforeTest() throws Exception { - super.processBeforeTest("Test Claim device", null, null); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Claim device") + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } protected void createCustomerAndUser() throws Exception { Customer customer = new Customer(); - customer.setTenantId(savedTenant.getId()); + customer.setTenantId(tenantId); customer.setTitle("Test Claiming Customer"); savedCustomer = doPost("/api/customer", customer, Customer.class); assertNotNull(savedCustomer); - assertEquals(savedTenant.getId(), savedCustomer.getTenantId()); + assertEquals(tenantId, savedCustomer.getTenantId()); User user = new User(); user.setAuthority(Authority.CUSTOMER_USER); - user.setTenantId(savedTenant.getId()); + user.setTenantId(tenantId); user.setCustomerId(savedCustomer.getId()); user.setEmail("customer@thingsboard.org"); @@ -75,7 +81,7 @@ public abstract class AbstractCoapClaimDeviceTest extends AbstractCoapIntegratio @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimJsonDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimJsonDeviceTest.java similarity index 69% rename from application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimJsonDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimJsonDeviceTest.java index 4455feffb0..7807dc0635 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimJsonDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimJsonDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,21 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapClaimJsonDeviceTest extends AbstractCoapClaimDeviceTest { +@DaoSqlTest +public class CoapClaimJsonDeviceTest extends CoapClaimDeviceTest { @Before public void beforeTest() throws Exception { - super.processBeforeTest("Test Claim device Json", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Claim device Json") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimProtoDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimProtoDeviceTest.java similarity index 82% rename from application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimProtoDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimProtoDeviceTest.java index cd64d85bf3..812ea7392b 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/claim/AbstractCoapClaimProtoDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/claim/CoapClaimProtoDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,28 @@ package org.thingsboard.server.transport.coap.claim; import lombok.extern.slf4j.Slf4j; -import org.eclipse.californium.core.CoapClient; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportApiProtos; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapClaimProtoDeviceTest extends AbstractCoapClaimDeviceTest { +@DaoSqlTest +public class CoapClaimProtoDeviceTest extends CoapClaimDeviceTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Claim device Proto", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Claim device Proto") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionJsonDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionJsonDeviceTest.java similarity index 68% rename from application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionJsonDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionJsonDeviceTest.java index 091900488b..a952ef6d63 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionJsonDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionJsonDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.Device; @@ -37,13 +38,13 @@ import org.thingsboard.server.common.transport.util.JsonUtils; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.provision.ProvisionResponseStatus; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.io.IOException; -import static org.junit.Assert.assertEquals; - @Slf4j -public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIntegrationTest { +@DaoSqlTest +public class CoapProvisionJsonDeviceTest extends AbstractCoapIntegrationTest { @Autowired DeviceCredentialsService deviceCredentialsService; @@ -53,7 +54,7 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test @@ -88,7 +89,12 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn private void processTestProvisioningDisabledDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); byte[] result = createCoapClientAndPublish().getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); Assert.assertEquals("Provision data was not found!", response.get("errorMsg").getAsString()); @@ -97,15 +103,23 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn private void processTestProvisioningCreateNewDeviceWithoutCredentials() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); byte[] result = createCoapClientAndPublish().getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); @@ -113,16 +127,24 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn private void processTestProvisioningCreateNewDeviceWithAccessToken() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); String requestCredentials = ",\"credentialsType\": \"ACCESS_TOKEN\",\"token\": \"test_token\""; byte[] result = createCoapClientAndPublish(requestCredentials).getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), "ACCESS_TOKEN"); @@ -132,16 +154,24 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn private void processTestProvisioningCreateNewDeviceWithCert() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); String requestCredentials = ",\"credentialsType\": \"X509_CERTIFICATE\",\"hash\": \"testHash\""; byte[] result = createCoapClientAndPublish(requestCredentials).getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), "X509_CERTIFICATE"); @@ -156,18 +186,34 @@ public abstract class AbstractCoapProvisionJsonDeviceTest extends AbstractCoapIn } private void processTestProvisioningCheckPreProvisionedDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); byte[] result = createCoapClientAndPublish().getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); } private void processTestProvisioningWithBadKeyDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.JSON, null, null, null, null, "testProvisionKeyOrig", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKeyOrig") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); byte[] result = createCoapClientAndPublish().getPayload(); JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); Assert.assertEquals("Provision data was not found!", response.get("errorMsg").getAsString()); diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionProtoDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionProtoDeviceTest.java similarity index 71% rename from application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionProtoDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionProtoDeviceTest.java index 671741c7d0..a2e270796e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/provision/AbstractCoapProvisionProtoDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/provision/CoapProvisionProtoDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.Device; @@ -43,11 +44,13 @@ import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceReque import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceTokenRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceX509CertRequestMsg; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.io.IOException; @Slf4j -public abstract class AbstractCoapProvisionProtoDeviceTest extends AbstractCoapIntegrationTest { +@DaoSqlTest +public class CoapProvisionProtoDeviceTest extends AbstractCoapIntegrationTest { @Autowired DeviceCredentialsService deviceCredentialsService; @@ -57,7 +60,7 @@ public abstract class AbstractCoapProvisionProtoDeviceTest extends AbstractCoapI @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test @@ -92,37 +95,58 @@ public abstract class AbstractCoapProvisionProtoDeviceTest extends AbstractCoapI private void processTestProvisioningDisabledDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); ProvisionDeviceResponseMsg result = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish().getPayload()); Assert.assertNotNull(result); Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), result.getStatus().toString()); } private void processTestProvisioningCreateNewDeviceWithoutCredentials() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish().getPayload()); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().toString()); } private void processTestProvisioningCreateNewDeviceWithAccessToken() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder().setValidateDeviceTokenRequestMsg(ValidateDeviceTokenRequestMsg.newBuilder().setToken("test_token").build()).build(); ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish(createTestsProvisionMessage(CredentialsType.ACCESS_TOKEN, requestCredentials)).getPayload()); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(deviceCredentials.getCredentialsType(), DeviceCredentialsType.ACCESS_TOKEN); @@ -131,16 +155,24 @@ public abstract class AbstractCoapProvisionProtoDeviceTest extends AbstractCoapI } private void processTestProvisioningCreateNewDeviceWithCert() throws Exception { - super.processBeforeTest("Test Provision device3", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device3") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder().setValidateDeviceX509CertRequestMsg(ValidateDeviceX509CertRequestMsg.newBuilder().setHash("testHash").build()).build(); ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish(createTestsProvisionMessage(CredentialsType.X509_CERTIFICATE, requestCredentials)).getPayload()); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(deviceCredentials.getCredentialsType(), DeviceCredentialsType.X509_CERTIFICATE); @@ -155,17 +187,33 @@ public abstract class AbstractCoapProvisionProtoDeviceTest extends AbstractCoapI } private void processTestProvisioningCheckPreProvisionedDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish().getPayload()); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), savedDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().toString()); } private void processTestProvisioningWithBadKeyDevice() throws Exception { - super.processBeforeTest("Test Provision device", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, null, "testProvisionKeyOrig", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Provision device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKeyOrig") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createCoapClientAndPublish().getPayload()); Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.getStatus().toString()); } diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceProtoSqlTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceProtoSqlTest.java deleted file mode 100644 index cde83c41e7..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceProtoSqlTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.provision.sql; - -import org.thingsboard.server.transport.coap.provision.AbstractCoapProvisionProtoDeviceTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapProvisionDeviceProtoSqlTest extends AbstractCoapProvisionProtoDeviceTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcIntegrationTest.java index 3fbc8cd214..5262b55b97 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,18 +26,15 @@ import org.eclipse.californium.core.coap.CoAP; import org.eclipse.californium.core.coap.MediaTypeRegistry; import org.eclipse.californium.core.coap.Request; import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.CoapDeviceType; -import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.msg.session.FeatureType; import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; -import java.nio.charset.StandardCharsets; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -46,12 +43,7 @@ public abstract class AbstractCoapServerSideRpcIntegrationTest extends AbstractC protected static final String DEVICE_RESPONSE = "{\"value1\":\"A\",\"value2\":\"B\"}"; - protected Long asyncContextTimeoutToUseRpcPlugin; - - protected void processBeforeTest(String deviceName, CoapDeviceType coapDeviceType, TransportPayloadType payloadType) throws Exception { - super.processBeforeTest(deviceName, coapDeviceType, payloadType); - asyncContextTimeoutToUseRpcPlugin = 10000L; - } + protected static final Long asyncContextTimeoutToUseRpcPlugin = 10000L; protected void processOneWayRpcTest() throws Exception { client = getCoapClient(FeatureType.RPC); @@ -186,7 +178,7 @@ public abstract class AbstractCoapServerSideRpcIntegrationTest extends AbstractC } private void validateCurrentStateNotification(TestCoapCallback callback) { - assertNull(callback.getPayloadBytes()); + assertArrayEquals(EMPTY_PAYLOAD, callback.getPayloadBytes()); assertNotNull(callback.getObserve()); assertEquals(callback.getResponseCode(), CoAP.ResponseCode.VALID); assertEquals(0, callback.getObserve().intValue()); diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcDefaultIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcDefaultIntegrationTest.java similarity index 81% rename from application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcDefaultIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcDefaultIntegrationTest.java index 2a5e46473a..cd0e9268b4 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcDefaultIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcDefaultIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,21 +21,30 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.thingsboard.server.common.data.CoapDeviceType; +import org.thingsboard.server.common.data.DeviceProfileProvisionType; +import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.service.security.AccessValidator; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapServerSideRpcDefaultIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { +@DaoSqlTest +public class CoapServerSideRpcDefaultIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", null, null); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("RPC test device") + .build(); + processBeforeTest(configProperties); } @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcJsonIntegrationTest.java similarity index 65% rename from application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcJsonIntegrationTest.java index 3aa1dec074..6dde4b919b 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,18 +21,26 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapServerSideRpcJsonIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { +@DaoSqlTest +public class CoapServerSideRpcJsonIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("RPC test device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcProtoIntegrationTest.java similarity index 87% rename from application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcProtoIntegrationTest.java index ad5cf78bc3..ae1c89d765 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/AbstractCoapServerSideRpcProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/CoapServerSideRpcProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,16 +23,12 @@ import com.squareup.wire.schema.internal.parser.ProtoFileElement; import lombok.extern.slf4j.Slf4j; import org.eclipse.californium.core.CoapClient; import org.eclipse.californium.core.CoapHandler; -import org.eclipse.californium.core.CoapObserveRelation; import org.eclipse.californium.core.CoapResponse; -import org.eclipse.californium.core.coap.CoAP; import org.eclipse.californium.core.coap.MediaTypeRegistry; -import org.eclipse.californium.core.coap.Request; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.CoapDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.CoapDeviceTypeConfiguration; @@ -40,19 +36,16 @@ import org.thingsboard.server.common.data.device.profile.DefaultCoapDeviceTypeCo import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; -import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; -import java.util.List; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Slf4j -public abstract class AbstractCoapServerSideRpcProtoIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { +@DaoSqlTest +public class CoapServerSideRpcProtoIntegrationTest extends AbstractCoapServerSideRpcIntegrationTest { private static final String RPC_REQUEST_PROTO_SCHEMA = "syntax =\"proto3\";\n" + "package rpc;\n" + @@ -70,12 +63,18 @@ public abstract class AbstractCoapServerSideRpcProtoIntegrationTest extends Abst @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("RPC test device") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .build(); + processBeforeTest(configProperties); } @After public void afterTest() throws Exception { - super.processAfterTest(); + processAfterTest(); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcJsonSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcJsonSqlIntegrationTest.java deleted file mode 100644 index ec417fa45f..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcJsonSqlIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.rpc.sql; - -import org.thingsboard.server.transport.coap.rpc.AbstractCoapServerSideRpcJsonIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapServerSideRpcJsonSqlIntegrationTest extends AbstractCoapServerSideRpcJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcSqlIntegrationTest.java deleted file mode 100644 index b505de2f39..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/rpc/sql/CoapServerSideRpcSqlIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.rpc.sql; - -import org.thingsboard.server.transport.coap.rpc.AbstractCoapServerSideRpcDefaultIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -@DaoSqlTest -public class CoapServerSideRpcSqlIntegrationTest extends AbstractCoapServerSideRpcDefaultIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesIntegrationTest.java similarity index 93% rename from application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesIntegrationTest.java index ccaf221c46..ee566be2bb 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,6 @@ */ package org.thingsboard.server.transport.coap.telemetry.attributes; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import lombok.extern.slf4j.Slf4j; import org.eclipse.californium.core.CoapClient; @@ -26,9 +25,11 @@ import org.eclipse.californium.elements.exception.ConnectorException; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.io.IOException; import java.util.Arrays; @@ -43,14 +44,18 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @Slf4j -public abstract class AbstractCoapAttributesIntegrationTest extends AbstractCoapIntegrationTest { +@DaoSqlTest +public class CoapAttributesIntegrationTest extends AbstractCoapIntegrationTest { private static final String PAYLOAD_VALUES_STR = "{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4," + " \"key5\": {\"someNumber\": 42, \"someArray\": [1,2,3], \"someNestedObject\": {\"key\": \"value\"}}}"; @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Attributes device", null, null); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesJsonIntegrationTest.java similarity index 64% rename from application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesJsonIntegrationTest.java index a07d02bcd7..38f5b872af 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,21 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j -public abstract class AbstractCoapAttributesJsonIntegrationTest extends AbstractCoapAttributesIntegrationTest { +@DaoSqlTest +public class CoapAttributesJsonIntegrationTest extends CoapAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Attributes device Json", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Attributes device Json") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesProtoIntegrationTest.java similarity index 93% rename from application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesProtoIntegrationTest.java index 4ed46b5e76..539f62f614 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/AbstractCoapAttributesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/CoapAttributesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,8 @@ import org.thingsboard.server.common.data.device.profile.DefaultCoapDeviceTypeCo import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.util.Arrays; @@ -37,12 +39,18 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @Slf4j -public abstract class AbstractCoapAttributesProtoIntegrationTest extends AbstractCoapAttributesIntegrationTest { +@DaoSqlTest +public class CoapAttributesProtoIntegrationTest extends CoapAttributesIntegrationTest { @Before @Override public void beforeTest() throws Exception { - processBeforeTest("Test Post Attributes device Proto", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Attributes device Proto") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlIntegrationTest.java deleted file mode 100644 index 4a2b655214..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.telemetry.attributes.sql; - -import org.thingsboard.server.transport.coap.telemetry.attributes.AbstractCoapAttributesIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ -@DaoSqlTest -public class CoapAttributesSqlIntegrationTest extends AbstractCoapAttributesIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlJsonIntegrationTest.java deleted file mode 100644 index eb4981414e..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlJsonIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.telemetry.attributes.sql; - -import org.thingsboard.server.transport.coap.telemetry.attributes.AbstractCoapAttributesJsonIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ -@DaoSqlTest -public class CoapAttributesSqlJsonIntegrationTest extends AbstractCoapAttributesJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlProtoIntegrationTest.java deleted file mode 100644 index aabb98cfba..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/attributes/sql/CoapAttributesSqlProtoIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.coap.telemetry.attributes.sql; - -import org.thingsboard.server.transport.coap.telemetry.attributes.AbstractCoapAttributesProtoIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; - -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ -@DaoSqlTest -public class CoapAttributesSqlProtoIntegrationTest extends AbstractCoapAttributesProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesIntegrationTest.java index 6993d73320..0c7ab4d1c5 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,9 @@ import org.eclipse.californium.elements.exception.ConnectorException; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; import org.thingsboard.server.common.msg.session.FeatureType; +import org.thingsboard.server.transport.coap.AbstractCoapIntegrationTest; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.io.IOException; import java.util.Arrays; @@ -46,7 +47,10 @@ public abstract class AbstractCoapTimeseriesIntegrationTest extends AbstractCoap @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Telemetry device", null, null); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device") + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesJsonIntegrationTest.java index ab05773cab..bfb8b24bf7 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,19 @@ import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.CoapDeviceType; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; @Slf4j public abstract class AbstractCoapTimeseriesJsonIntegrationTest extends AbstractCoapTimeseriesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Telemetry device json payload", CoapDeviceType.DEFAULT, TransportPayloadType.JSON); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @After diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesProtoIntegrationTest.java index 612867636c..93e132663e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/AbstractCoapTimeseriesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import org.thingsboard.server.common.data.device.profile.DefaultCoapDeviceTypeCo import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; +import org.thingsboard.server.transport.coap.CoapTestConfigProperties; import java.util.Arrays; @@ -48,7 +49,12 @@ public abstract class AbstractCoapTimeseriesProtoIntegrationTest extends Abstrac @Test public void testPushTelemetry() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); assertTrue(transportConfiguration instanceof CoapDeviceProfileTransportConfiguration); CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration; @@ -117,7 +123,13 @@ public abstract class AbstractCoapTimeseriesProtoIntegrationTest extends Abstrac " }\n" + " }\n" + "}"; - processBeforeTest("Test Post Telemetry device proto payload", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, schemaStr, null, null, null, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryProtoSchema(schemaStr) + .build(); + processBeforeTest(configProperties); DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); assertTrue(transportConfiguration instanceof CoapDeviceProfileTransportConfiguration); CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration; @@ -172,7 +184,12 @@ public abstract class AbstractCoapTimeseriesProtoIntegrationTest extends Abstrac @Test public void testPushTelemetryWithExplicitPresenceProtoKeys() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); assertTrue(transportConfiguration instanceof CoapDeviceProfileTransportConfiguration); CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration; @@ -239,7 +256,13 @@ public abstract class AbstractCoapTimeseriesProtoIntegrationTest extends Abstrac " }\n" + " }\n" + "}"; - processBeforeTest("Test Post Telemetry device proto payload", CoapDeviceType.DEFAULT, TransportPayloadType.PROTOBUF, schemaStr, null, null, null, null, null, DeviceProfileProvisionType.DISABLED); + CoapTestConfigProperties configProperties = CoapTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .coapDeviceType(CoapDeviceType.DEFAULT) + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryProtoSchema(schemaStr) + .build(); + processBeforeTest(configProperties); DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); assertTrue(transportConfiguration instanceof CoapDeviceProfileTransportConfiguration); CoapDeviceProfileTransportConfiguration coapDeviceProfileTransportConfiguration = (CoapDeviceProfileTransportConfiguration) transportConfiguration; diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlIntegrationTest.java index 459e7cae7b..4fdf5cb2bc 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlJsonIntegrationTest.java index ec4988875b..cea386836f 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlProtoIntegrationTest.java index 46ce05aa7b..b5ca963cb9 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/nosql/CoapTimeseriesNoSqlProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlIntegrationTest.java index c1f4e4f2c7..b7553debf1 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlJsonIntegrationTest.java index 19b13e2293..4fff3532fb 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlProtoIntegrationTest.java index acec631414..cf6f7e9d90 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/coap/telemetry/timeseries/sql/CoapTimeseriesSqlProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java index 5d4c32641d..20aa0a1805 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/AbstractLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,18 @@ package org.thingsboard.server.transport.lwm2m; import com.fasterxml.jackson.core.type.TypeReference; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; -import org.eclipse.californium.core.network.config.NetworkConfig; +import org.eclipse.californium.elements.config.Configuration; +import org.eclipse.leshan.client.californium.LeshanClient; import org.eclipse.leshan.client.object.Security; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.SpyBean; +import org.springframework.test.context.TestPropertySource; import org.springframework.util.SocketUtils; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.ThingsBoardThreadFactory; @@ -41,6 +47,11 @@ import org.thingsboard.server.common.data.device.profile.DefaultDeviceProfileCon import org.thingsboard.server.common.data.device.profile.DeviceProfileData; import org.thingsboard.server.common.data.device.profile.DisabledDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.OtherConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.TelemetryMappingConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.AbstractLwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.NoSecLwM2MBootstrapServerCredential; import org.thingsboard.server.common.data.query.EntityData; import org.thingsboard.server.common.data.query.EntityDataPageLink; import org.thingsboard.server.common.data.query.EntityDataQuery; @@ -49,103 +60,143 @@ import org.thingsboard.server.common.data.query.EntityKeyType; import org.thingsboard.server.common.data.query.SingleEntityFilter; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; -import org.thingsboard.server.controller.AbstractWebsocketTest; -import org.thingsboard.server.controller.TbTestWebSocketClient; +import org.thingsboard.server.controller.AbstractControllerTest; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.service.telemetry.cmd.TelemetryPluginCmdsWrapper; import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataCmd; import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate; import org.thingsboard.server.service.telemetry.cmd.v2.LatestValueCmd; import org.thingsboard.server.transport.lwm2m.client.LwM2MTestClient; +import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClientContext; +import org.thingsboard.server.transport.lwm2m.server.uplink.DefaultLwM2mUplinkMsgHandler; +import java.io.IOException; +import java.net.ServerSocket; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Base64; import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import static org.awaitility.Awaitility.await; +import static org.eclipse.californium.core.config.CoapConfig.COAP_PORT; +import static org.eclipse.californium.core.config.CoapConfig.COAP_SECURE_PORT; +import static org.eclipse.leshan.client.object.Security.noSec; +import static org.eclipse.leshan.client.object.Security.noSecBootstap; +import static org.hamcrest.core.IsInstanceOf.instanceOf; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_INIT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; +@TestPropertySource(properties = { + "transport.lwm2m.enabled=true", +}) +@Slf4j @DaoSqlTest -public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest { - - protected String transportConfiguration = "{\n" + - " \"type\": \"LWM2M\",\n" + - " \"observeAttr\": {\n" + - " \"keyName\": {\n" + - " \"/3_1.0/0/9\": \"batteryLevel\"\n" + - " },\n" + - " \"observe\": [],\n" + - " \"attribute\": [\n" + - " ],\n" + - " \"telemetry\": [\n" + - " \"/3_1.0/0/9\"\n" + - " ],\n" + - " \"attributeLwm2m\": {}\n" + - " },\n" + - " \"bootstrapServerUpdateEnable\": true,\n" + - " \"bootstrap\": [\n" + +public abstract class AbstractLwM2MIntegrationTest extends AbstractControllerTest { + + @SpyBean + DefaultLwM2mUplinkMsgHandler defaultLwM2mUplinkMsgHandlerTest; + + @Autowired + private LwM2mClientContext clientContextTest; + + // Lwm2m Server + public static final int port = 5685; + public static final int securityPort = 5686; + public static final int portBs = 5687; + public static final int securityPortBs = 5688; + public static final int[] SERVERS_PORT_NUMBERS = {port, securityPort, portBs, securityPortBs}; + + public static final String host = "localhost"; + public static final String hostBs = "localhost"; + public static final int shortServerId = 123; + public static final int shortServerIdBs = 111; + public static final String COAP = "coap://"; + public static final String COAPS = "coaps://"; + public static final String URI = COAP + host + ":" + port; + public static final String SECURE_URI = COAPS + host + ":" + securityPort; + public static final String URI_BS = COAP + hostBs + ":" + portBs; + public static final String SECURE_URI_BS = COAPS + hostBs + ":" + securityPortBs; + public static final Configuration COAP_CONFIG = new Configuration().set(COAP_PORT, port).set(COAP_SECURE_PORT, securityPort); + public static Configuration COAP_CONFIG_BS = new Configuration().set(COAP_PORT, portBs).set(COAP_SECURE_PORT, securityPortBs); + public static final Security SECURITY_NO_SEC = noSec(URI, shortServerId); + public static final Security SECURITY_NO_SEC_BS = noSecBootstap(URI_BS); + + protected final String OBSERVE_ATTRIBUTES_WITHOUT_PARAMS = " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5687,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 111,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": true,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " },\n" + + " \"keyName\": {},\n" + + " \"observe\": [],\n" + + " \"attribute\": [],\n" + + " \"telemetry\": [],\n" + + " \"attributeLwm2m\": {}\n" + + " }"; + + protected final String OBSERVE_ATTRIBUTES_WITH_PARAMS = + " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5685,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 123,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": false,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " }\n" + - " ],\n" + - " \"clientLwM2mSettings\": {\n" + - " \"edrxCycle\": null,\n" + - " \"powerMode\": \"DRX\",\n" + - " \"fwUpdateResource\": null,\n" + - " \"fwUpdateStrategy\": 1,\n" + - " \"psmActivityTimer\": null,\n" + - " \"swUpdateResource\": null,\n" + - " \"swUpdateStrategy\": 1,\n" + - " \"pagingTransmissionWindow\": null,\n" + - " \"clientOnlyObserveAfterConnect\": 1\n" + - " }\n" + - "}"; + " \"keyName\": {\n" + + " \"/3_1.0/0/9\": \"batteryLevel\"\n" + + " },\n" + + " \"observe\": [],\n" + + " \"attribute\": [\n" + + " ],\n" + + " \"telemetry\": [\n" + + " \"/3_1.0/0/9\"\n" + + " ],\n" + + " \"attributeLwm2m\": {}\n" + + " }"; + protected final String CLIENT_LWM2M_SETTINGS = + " {\n" + + " \"edrxCycle\": null,\n" + + " \"powerMode\": \"DRX\",\n" + + " \"fwUpdateResource\": null,\n" + + " \"fwUpdateStrategy\": 1,\n" + + " \"psmActivityTimer\": null,\n" + + " \"swUpdateResource\": null,\n" + + " \"swUpdateStrategy\": 1,\n" + + " \"pagingTransmissionWindow\": null,\n" + + " \"clientOnlyObserveAfterConnect\": 1\n" + + " }"; + + protected final Set expectedStatusesBsSuccess = new HashSet<>(Arrays.asList(ON_INIT, ON_BOOTSTRAP_STARTED, ON_BOOTSTRAP_SUCCESS)); + protected final Set expectedStatusesRegistrationLwm2mSuccess = new HashSet<>(Arrays.asList(ON_INIT, ON_REGISTRATION_STARTED, ON_REGISTRATION_SUCCESS)); + protected final Set expectedStatusesRegistrationBsSuccess = new HashSet<>(Arrays.asList(ON_INIT, ON_BOOTSTRAP_STARTED, ON_BOOTSTRAP_SUCCESS, ON_REGISTRATION_STARTED, ON_REGISTRATION_SUCCESS)); protected DeviceProfile deviceProfile; protected ScheduledExecutorService executor; - protected TbTestWebSocketClient wsClient; - protected LwM2MTestClient client; - private final LwM2MBootstrapClientCredentials defaultBootstrapCredentials; + protected LwM2MTestClient lwM2MTestClient; private String[] resources; - protected String endpoint; - public AbstractLwM2MIntegrationTest() { - this.defaultBootstrapCredentials = new LwM2MBootstrapClientCredentials(); - NoSecBootstrapClientCredential serverCredentials = new NoSecBootstrapClientCredential(); - this.defaultBootstrapCredentials.setBootstrapServer(serverCredentials); - this.defaultBootstrapCredentials.setLwm2mServer(serverCredentials); + @Before + public void startInit() throws Exception { + init(); } - public void init () throws Exception{ + @After + public void after() { + clientDestroy(); + executor.shutdownNow(); + } + + @AfterClass + public static void afterClass() { + awaitServersDestroy(); + } + + private void init() throws Exception { executor = Executors.newScheduledThreadPool(10, ThingsBoardThreadFactory.forName("test-lwm2m-scheduled")); loginTenantAdmin(); - for (String resourceName : this.resources) { TbResource lwModel = new TbResource(); lwModel.setResourceType(ResourceType.LWM2M_MODEL); @@ -158,27 +209,15 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest }); Assert.assertNotNull(lwModel); } - wsClient = buildAndConnectWebSocketClient(); - } - - @Before - public void beforeTest() throws Exception { - this.init(); - } - - @After - public void after() { - wsClient.close(); - clientDestroy(); - executor.shutdownNow(); } public void basicTestConnectionObserveTelemetry(Security security, - LwM2MClientCredential credentials, - NetworkConfig coapConfig, + LwM2MDeviceCredentials deviceCredentials, + Configuration coapConfig, String endpoint) throws Exception { + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITH_PARAMS, getBootstrapServerCredentialsNoSec(NONE)); createDeviceProfile(transportConfiguration); - Device device = createDevice(credentials); + Device device = createDevice(deviceCredentials, endpoint); SingleEntityFilter sef = new SingleEntityFilter(); sef.setSingleEntity(device.getId()); @@ -191,13 +230,12 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest TelemetryPluginCmdsWrapper wrapper = new TelemetryPluginCmdsWrapper(); wrapper.setEntityDataCmds(Collections.singletonList(cmd)); - wsClient.send(mapper.writeValueAsString(wrapper)); - wsClient.waitForReply(); + getWsClient().send(mapper.writeValueAsString(wrapper)); + getWsClient().waitForReply(); - wsClient.registerWaitForUpdate(); - this.endpoint = endpoint; - createNewClient(security, coapConfig, false); - String msg = wsClient.waitForUpdate(); + getWsClient().registerWaitForUpdate(); + createNewClient(security, coapConfig, false, endpoint, false, null); + String msg = getWsClient().waitForUpdate(); EntityDataUpdate update = mapper.readValue(msg, EntityDataUpdate.class); Assert.assertEquals(1, update.getCmdId()); @@ -207,10 +245,14 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest Assert.assertEquals(device.getId(), eData.get(0).getEntityId()); Assert.assertNotNull(eData.get(0).getLatest().get(EntityKeyType.TIME_SERIES)); var tsValue = eData.get(0).getLatest().get(EntityKeyType.TIME_SERIES).get("batteryLevel"); - Assert.assertEquals(42, Long.parseLong(tsValue.getValue())); + Assert.assertThat(Long.parseLong(tsValue.getValue()), instanceOf(Long.class)); + int expectedMax = 50; + int expectedMin = 5; + Assert.assertTrue(expectedMax >= Long.parseLong(tsValue.getValue())); + Assert.assertTrue(expectedMin <= Long.parseLong(tsValue.getValue())); } - protected void createDeviceProfile(String transportConfiguration) throws Exception { + protected void createDeviceProfile(Lwm2mDeviceProfileTransportConfiguration transportConfiguration) throws Exception { deviceProfile = new DeviceProfile(); deviceProfile.setName("LwM2M"); deviceProfile.setType(DeviceProfileType.DEFAULT); @@ -222,16 +264,16 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest DeviceProfileData deviceProfileData = new DeviceProfileData(); deviceProfileData.setConfiguration(new DefaultDeviceProfileConfiguration()); deviceProfileData.setProvisionConfiguration(new DisabledDeviceProfileProvisionConfiguration(null)); - deviceProfileData.setTransportConfiguration(JacksonUtil.fromString(transportConfiguration, Lwm2mDeviceProfileTransportConfiguration.class)); + deviceProfileData.setTransportConfiguration(transportConfiguration); deviceProfile.setProfileData(deviceProfileData); deviceProfile = doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); Assert.assertNotNull(deviceProfile); } - protected Device createDevice(LwM2MClientCredential clientCredentials) throws Exception { + protected Device createDevice(LwM2MDeviceCredentials credentials, String endpoint) throws Exception { Device device = new Device(); - device.setName("Device A"); + device.setName(endpoint); device.setDeviceProfileId(deviceProfile.getId()); device.setTenantId(tenantId); device = doPost("/api/device", device, Device.class); @@ -241,11 +283,6 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest doGet("/api/device/" + device.getId().getId().toString() + "/credentials", DeviceCredentials.class); Assert.assertEquals(device.getId(), deviceCredentials.getDeviceId()); deviceCredentials.setCredentialsType(DeviceCredentialsType.LWM2M_CREDENTIALS); - - LwM2MDeviceCredentials credentials = new LwM2MDeviceCredentials(); - credentials.setClient(clientCredentials); - credentials.setBootstrap(defaultBootstrapCredentials); - deviceCredentials.setCredentialsValue(JacksonUtil.toString(credentials)); doPost("/api/device/credentials", deviceCredentials).andExpect(status().isOk()); return device; @@ -261,20 +298,98 @@ public abstract class AbstractLwM2MIntegrationTest extends AbstractWebsocketTest this.resources = resources; } - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; + public void createNewClient(Security security, Configuration coapConfig, boolean isRpc, String endpoint, boolean isBootstrap, Security securityBs) throws Exception { + this.clientDestroy(); + lwM2MTestClient = new LwM2MTestClient(this.executor, endpoint); + int clientPort = SocketUtils.findAvailableUdpPort(); + lwM2MTestClient.init(security, coapConfig, clientPort, isRpc, isBootstrap, this.shortServerId, this.shortServerIdBs, + securityBs, this.defaultLwM2mUplinkMsgHandlerTest, this.clientContextTest); } - public void createNewClient(Security security, NetworkConfig coapConfig, boolean isRpc) throws Exception { - clientDestroy(); - client = new LwM2MTestClient(this.executor, this.endpoint); - int clientPort = SocketUtils.findAvailableTcpPort(); - client.init(security, coapConfig, clientPort, isRpc); + private void clientDestroy() { + try { + if (lwM2MTestClient != null) { + lwM2MTestClient.destroy(); + awaitClientDestroy(lwM2MTestClient.getLeshanClient()); + } + } catch (Exception e) { + log.error("Failed client Destroy", e); + } } - private void clientDestroy() { - if (client != null) { - client.destroy(); + protected Lwm2mDeviceProfileTransportConfiguration getTransportConfiguration(String observeAttr, List bootstrapServerCredentials) { + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = new Lwm2mDeviceProfileTransportConfiguration(); + TelemetryMappingConfiguration observeAttrConfiguration = JacksonUtil.fromString(observeAttr, TelemetryMappingConfiguration.class); + OtherConfiguration clientLwM2mSettings = JacksonUtil.fromString(CLIENT_LWM2M_SETTINGS, OtherConfiguration.class); + transportConfiguration.setBootstrapServerUpdateEnable(true); + transportConfiguration.setObserveAttr(observeAttrConfiguration); + transportConfiguration.setClientLwM2mSettings(clientLwM2mSettings); + transportConfiguration.setBootstrap(bootstrapServerCredentials); + return transportConfiguration; + } + + protected List getBootstrapServerCredentialsNoSec(LwM2MProfileBootstrapConfigType bootstrapConfigType) { + List bootstrap = new ArrayList<>(); + switch (bootstrapConfigType) { + case BOTH: + bootstrap.add(getBootstrapServerCredentialNoSec(false)); + bootstrap.add(getBootstrapServerCredentialNoSec(true)); + break; + case BOOTSTRAP_ONLY: + bootstrap.add(getBootstrapServerCredentialNoSec(true)); + break; + case LWM2M_ONLY: + bootstrap.add(getBootstrapServerCredentialNoSec(false)); + break; + case NONE: + } + return bootstrap; + } + + private AbstractLwM2MBootstrapServerCredential getBootstrapServerCredentialNoSec(boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapServerCredential = new NoSecLwM2MBootstrapServerCredential(); + bootstrapServerCredential.setServerPublicKey(""); + bootstrapServerCredential.setShortServerId(isBootstrap ? shortServerIdBs : shortServerId); + bootstrapServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapServerCredential.setHost(isBootstrap ? hostBs : host); + bootstrapServerCredential.setPort(isBootstrap ? portBs : port); + return bootstrapServerCredential; + } + + protected LwM2MDeviceCredentials getDeviceCredentialsNoSec(LwM2MClientCredential clientCredentials) { + LwM2MDeviceCredentials credentials = new LwM2MDeviceCredentials(); + credentials.setClient(clientCredentials); + LwM2MBootstrapClientCredentials bootstrapCredentials = new LwM2MBootstrapClientCredentials(); + NoSecBootstrapClientCredential serverCredentials = new NoSecBootstrapClientCredential(); + bootstrapCredentials.setBootstrapServer(serverCredentials); + bootstrapCredentials.setLwm2mServer(serverCredentials); + credentials.setBootstrap(bootstrapCredentials); + return credentials; + } + + private static void awaitServersDestroy() { + await("One of servers ports number is not free") + .atMost(3000, TimeUnit.MILLISECONDS) + .until(() -> isServerPortsAvailable() == null); + } + + private static String isServerPortsAvailable() { + for (int port : SERVERS_PORT_NUMBERS) { + try (ServerSocket serverSocket = new ServerSocket(port)) { + serverSocket.close(); + Assert.assertEquals(true, serverSocket.isClosed()); + } catch (IOException e) { + log.warn(String.format("Port %n still in use", port)); + return (String.format("Port %n still in use", port)); + } } + return null; } + + private static void awaitClientDestroy(LeshanClient leshanClient) { + await("Destroy LeshanClient: delete All is registered Servers.") + .atMost(2000, TimeUnit.MILLISECONDS) + .until(() -> leshanClient.getRegisteredServers().size() == 0); + } + } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/Lwm2mTestHelper.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/Lwm2mTestHelper.java index 232332e554..8ff0962811 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/Lwm2mTestHelper.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/Lwm2mTestHelper.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,56 +15,118 @@ */ package org.thingsboard.server.transport.lwm2m; -import org.eclipse.californium.core.network.config.NetworkConfig; -import org.eclipse.leshan.client.object.Security; - -import static org.eclipse.leshan.client.object.Security.noSec; - public class Lwm2mTestHelper { - // Server - public static final int SECURE_PORT = 5686; - public static final int SECURE_PORT_BS = 5688; - public static final String HOST = "localhost"; - public static final String HOST_BS = "localhost"; - public static final NetworkConfig SECURE_COAP_CONFIG = new NetworkConfig().setString("COAP_SECURE_PORT", Integer.toString(SECURE_PORT)); - public static final String ENDPOINT_SECURITY = "deviceAEndpoint"; - public static final String SECURE_URI = "coaps://localhost:" + SECURE_PORT; - - public static final int PORT = 5685; - public static final int PORT_BS = 5687; - public static final int SHORT_SERVER_ID = 123; - public static final int SHORT_SERVER_ID_BS = 111; - - public static final Security SECURITY = noSec("coap://localhost:" + PORT, SHORT_SERVER_ID); - public static final NetworkConfig COAP_CONFIG = new NetworkConfig().setString("COAP_PORT", Integer.toString(PORT)); - // Models public static final String[] resources = new String[]{"0.xml", "1.xml", "2.xml", "3.xml", "5.xml", "6.xml", "9.xml", "19.xml", "3303.xml"}; public static final int BINARY_APP_DATA_CONTAINER = 19; public static final int TEMPERATURE_SENSOR = 3303; // Ids in Client - public static final int objectId_0 = 0; - public static final int objectInstanceId_0 = 0; - public static final int objectInstanceId_1 = 1; - public static final int objectInstanceId_2 = 2; - public static final int objectInstanceId_12 = 12; - public static final int resourceId_0 = 0; - public static final int resourceId_1 = 1; - public static final int resourceId_2 = 2; - public static final int resourceId_3 = 3; - public static final int resourceId_4 = 4; - public static final int resourceId_8 = 8; - public static final int resourceId_9 = 9; - public static final int resourceId_11 = 11; - public static final int resourceId_14 = 14; - public static final int resourceId_15= 15; - public static final int resourceInstanceId_2 = 2; - - public static final String resourceIdName_3_9 = "batteryLevel"; - public static final String resourceIdName_3_14 = "UtfOffset"; - public static final String resourceIdName_19_0_0 = "dataRead"; - public static final String resourceIdName_19_1_0 = "dataWrite"; + public static final int OBJECT_ID_0 = 0; + public static final int OBJECT_ID_1 = 1; + public static final int OBJECT_INSTANCE_ID_0 = 0; + public static final int OBJECT_INSTANCE_ID_1 = 1; + public static final int OBJECT_INSTANCE_ID_2 = 2; + public static final int OBJECT_INSTANCE_ID_12 = 12; + public static final int RESOURCE_ID_0 = 0; + public static final int RESOURCE_ID_1 = 1; + public static final int RESOURCE_ID_2 = 2; + public static final int RESOURCE_ID_3 = 3; + public static final int RESOURCE_ID_4 = 4; + public static final int RESOURCE_ID_7 = 7; + public static final int RESOURCE_ID_8 = 8; + public static final int RESOURCE_ID_9 = 9; + public static final int RESOURCE_ID_11 = 11; + public static final int RESOURCE_ID_14 = 14; + public static final int RESOURCE_ID_15 = 15; + public static final int RESOURCE_INSTANCE_ID_2 = 2; + + public static final String RESOURCE_ID_NAME_3_9 = "batteryLevel"; + public static final String RESOURCE_ID_NAME_3_14 = "UtfOffset"; + public static final String RESOURCE_ID_NAME_19_0_0 = "dataRead"; + public static final String RESOURCE_ID_NAME_19_1_0 = "dataWrite"; + public static final String RESOURCE_ID_NAME_19_0_3 = "dataDescription"; + + public enum LwM2MClientState { + + ON_INIT(1, "onInit"), + ON_BOOTSTRAP_STARTED(1, "onBootstrapStarted"), + ON_BOOTSTRAP_SUCCESS(2, "onBootstrapSuccess"), + ON_BOOTSTRAP_FAILURE(3, "onBootstrapFailure"), + ON_BOOTSTRAP_TIMEOUT(4, "onBootstrapTimeout"), + ON_REGISTRATION_STARTED(5, "onRegistrationStarted"), + ON_REGISTRATION_SUCCESS(6, "onRegistrationSuccess"), + ON_REGISTRATION_FAILURE(7, "onRegistrationFailure"), + ON_REGISTRATION_TIMEOUT(7, "onRegistrationTimeout"), + ON_UPDATE_STARTED(8, "onUpdateStarted"), + ON_UPDATE_SUCCESS(9, "onUpdateSuccess"), + ON_UPDATE_FAILURE(10, "onUpdateFailure"), + ON_UPDATE_TIMEOUT(11, "onUpdateTimeout"), + ON_DEREGISTRATION_STARTED(12, "onDeregistrationStarted"), + ON_DEREGISTRATION_SUCCESS(13, "onDeregistrationSuccess"), + ON_DEREGISTRATION_FAILURE(14, "onDeregistrationFailure"), + ON_DEREGISTRATION_TIMEOUT(15, "onDeregistrationTimeout"), + ON_EXPECTED_ERROR(16, "onUnexpectedError"); + + public int code; + public String type; + + LwM2MClientState(int code, String type) { + this.code = code; + this.type = type; + } + + public static LwM2MClientState fromLwM2MClientStateByType(String type) { + for (LwM2MClientState to : LwM2MClientState.values()) { + if (to.type.equals(type)) { + return to; + } + } + throw new IllegalArgumentException(String.format("Unsupported Client State type : %s", type)); + } + + public static LwM2MClientState fromLwM2MClientStateByCode(int code) { + for (LwM2MClientState to : LwM2MClientState.values()) { + if (to.code == code) { + return to; + } + } + throw new IllegalArgumentException(String.format("Unsupported Client State code : %s", code)); + } + } + + public enum LwM2MProfileBootstrapConfigType { + + LWM2M_ONLY(1, "only Lwm2m Server"), + BOOTSTRAP_ONLY(2, "only Bootstrap Server"), + BOTH(3, "Lwm2m Server and Bootstrap Server"), + NONE(4, "Without Lwm2m Server and Bootstrap Server"); + + public int code; + public String type; + + LwM2MProfileBootstrapConfigType(int code, String type) { + this.code = code; + this.type = type; + } + + public static LwM2MProfileBootstrapConfigType fromLwM2MBootstrapConfigByType(String type) { + for (LwM2MProfileBootstrapConfigType to : LwM2MProfileBootstrapConfigType.values()) { + if (to.type.equals(type)) { + return to; + } + } + throw new IllegalArgumentException(String.format("Unsupported Profile Bootstrap Config type : %s", type)); + } + public static LwM2MProfileBootstrapConfigType fromLwM2MBootstrapConfigByCode(int code) { + for (LwM2MProfileBootstrapConfigType to : LwM2MProfileBootstrapConfigType.values()) { + if (to.code == code) { + return to; + } + } + throw new IllegalArgumentException(String.format("Unsupported Profile Bootstrap Config code : %s", code)); + } + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/FwLwM2MDevice.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/FwLwM2MDevice.java index cc097c869d..81159e6584 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/FwLwM2MDevice.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/FwLwM2MDevice.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,10 +131,10 @@ public class FwLwM2MDevice extends BaseInstanceEnabler implements Destroyable { scheduler.schedule(() -> { try { state.set(1); - fireResourcesChange(3); + fireResourceChange(3); Thread.sleep(100); state.set(2); - fireResourcesChange(3); + fireResourceChange(3); } catch (Exception e) { } }, 100, TimeUnit.MILLISECONDS); @@ -144,10 +144,10 @@ public class FwLwM2MDevice extends BaseInstanceEnabler implements Destroyable { scheduler.schedule(() -> { try { state.set(3); - fireResourcesChange(3); + fireResourceChange(3); Thread.sleep(100); updateResult.set(1); - fireResourcesChange(5); + fireResourceChange(5); } catch (Exception e) { } }, 100, TimeUnit.MILLISECONDS); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MLocationParams.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MLocationParams.java index 67d1dc5749..6709340a9d 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MLocationParams.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MLocationParams.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MTestClient.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MTestClient.java index 1c62b2b79d..e169705f22 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MTestClient.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2MTestClient.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,7 @@ package org.thingsboard.server.transport.lwm2m.client; import lombok.Data; import lombok.extern.slf4j.Slf4j; -import org.eclipse.californium.core.network.CoapEndpoint; -import org.eclipse.californium.core.network.config.NetworkConfig; -import org.eclipse.californium.core.observe.ObservationStore; -import org.eclipse.californium.scandium.DTLSConnector; +import org.eclipse.californium.elements.config.Configuration; import org.eclipse.californium.scandium.config.DtlsConnectorConfig; import org.eclipse.leshan.client.californium.LeshanClient; import org.eclipse.leshan.client.californium.LeshanClientBuilder; @@ -29,10 +26,10 @@ import org.eclipse.leshan.client.object.Security; import org.eclipse.leshan.client.object.Server; import org.eclipse.leshan.client.observer.LwM2mClientObserver; import org.eclipse.leshan.client.resource.DummyInstanceEnabler; +import org.eclipse.leshan.client.resource.LwM2mInstanceEnabler; import org.eclipse.leshan.client.resource.ObjectsInitializer; import org.eclipse.leshan.client.servers.ServerIdentity; import org.eclipse.leshan.core.ResponseCode; -import org.eclipse.leshan.core.californium.EndpointFactory; import org.eclipse.leshan.core.model.InvalidDDFFileException; import org.eclipse.leshan.core.model.LwM2mModel; import org.eclipse.leshan.core.model.ObjectLoader; @@ -44,15 +41,23 @@ import org.eclipse.leshan.core.request.BootstrapRequest; import org.eclipse.leshan.core.request.DeregisterRequest; import org.eclipse.leshan.core.request.RegisterRequest; import org.eclipse.leshan.core.request.UpdateRequest; -import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; import org.junit.Assert; +import org.mockito.Mockito; +import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient; +import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClientContext; +import org.thingsboard.server.transport.lwm2m.server.uplink.DefaultLwM2mUplinkMsgHandler; +import org.thingsboard.server.transport.lwm2m.utils.LwM2mValueConverterImpl; import java.io.IOException; -import java.net.InetSocketAddress; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import static org.eclipse.californium.scandium.config.DtlsConfig.DTLS_RECOMMENDED_CIPHER_SUITES_ONLY; import static org.eclipse.leshan.core.LwM2mId.ACCESS_CONTROL; import static org.eclipse.leshan.core.LwM2mId.DEVICE; import static org.eclipse.leshan.core.LwM2mId.FIRMWARE; @@ -61,10 +66,29 @@ import static org.eclipse.leshan.core.LwM2mId.SECURITY; import static org.eclipse.leshan.core.LwM2mId.SERVER; import static org.eclipse.leshan.core.LwM2mId.SOFTWARE_MANAGEMENT; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.BINARY_APP_DATA_CONTAINER; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_FAILURE; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_TIMEOUT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_FAILURE; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_TIMEOUT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_EXPECTED_ERROR; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_INIT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_FAILURE; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_TIMEOUT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_UPDATE_FAILURE; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_UPDATE_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_UPDATE_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_UPDATE_TIMEOUT; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_12; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.TEMPERATURE_SENSOR; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_12; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resources; @@ -74,189 +98,215 @@ public class LwM2MTestClient { private final ScheduledExecutorService executor; private final String endpoint; - private LeshanClient client; + private LeshanClient leshanClient; - private Server lwm2mServer; + private Security lwm2mSecurity; + private Security lwm2mSecurityBs; + private Lwm2mServer lwm2mServer; + private Lwm2mServer lwm2mServerBs; private SimpleLwM2MDevice lwM2MDevice; private FwLwM2MDevice fwLwM2MDevice; private SwLwM2MDevice swLwM2MDevice; private LwM2mBinaryAppDataContainer lwM2MBinaryAppDataContainer; private LwM2MLocationParams locationParams; private LwM2mTemperatureSensor lwM2MTemperatureSensor; - - public void init(Security security, NetworkConfig coapConfig, int port, boolean isRpc) throws InvalidDDFFileException, IOException { - Assert.assertNull("client already initialized", client); + private LwM2MClientState clientState; + private Set clientStates; + private DefaultLwM2mUplinkMsgHandler defaultLwM2mUplinkMsgHandlerTest; + private LwM2mClientContext clientContext; + + public void init(Security security, Configuration coapConfig, int port, boolean isRpc, boolean isBootstrap, + int shortServerId, int shortServerIdBs, Security securityBs, + DefaultLwM2mUplinkMsgHandler defaultLwM2mUplinkMsgHandler, + LwM2mClientContext clientContext) throws InvalidDDFFileException, IOException { + Assert.assertNull("client already initialized", leshanClient); + this.defaultLwM2mUplinkMsgHandlerTest = defaultLwM2mUplinkMsgHandler; + this.clientContext = clientContext; List models = new ArrayList<>(); for (String resourceName : resources) { models.addAll(ObjectLoader.loadDdfFile(LwM2MTestClient.class.getClassLoader().getResourceAsStream("lwm2m/" + resourceName), resourceName)); } - LwM2mModel model = new StaticModel(models); ObjectsInitializer initializer = new ObjectsInitializer(model); - initializer.setInstancesForObject(SECURITY, security); - initializer.setInstancesForObject(SERVER, lwm2mServer = new Server(123, 300)); - initializer.setInstancesForObject(DEVICE, lwM2MDevice = new SimpleLwM2MDevice()); + if (securityBs == null) { + initializer.setInstancesForObject(SECURITY, this.lwm2mSecurity = security); + } else { + securityBs.setId(0); + security.setId(1); + LwM2mInstanceEnabler[] instances = new LwM2mInstanceEnabler[]{this.lwm2mSecurityBs = securityBs, this.lwm2mSecurity = security}; + initializer.setClassForObject(SECURITY, Security.class); + initializer.setInstancesForObject(SECURITY, instances); + } + if (isBootstrap) { + initializer.setInstancesForObject(SERVER, lwm2mServerBs = new Lwm2mServer(shortServerIdBs, 300)); + } else { + if (securityBs == null) { + initializer.setInstancesForObject(SERVER, lwm2mServer = new Lwm2mServer(shortServerId, 300)); + } else { + lwm2mServerBs = new Lwm2mServer(shortServerIdBs, 300); + lwm2mServerBs.setId(0); + lwm2mServer = new Lwm2mServer(shortServerId, 300); + lwm2mServer.setId(1); + LwM2mInstanceEnabler[] instances = new LwM2mInstanceEnabler[]{lwm2mServerBs, lwm2mServer}; + initializer.setClassForObject(SERVER, Server.class); + initializer.setInstancesForObject(SERVER, instances); + } + } + initializer.setInstancesForObject(DEVICE, lwM2MDevice = new SimpleLwM2MDevice(executor)); initializer.setInstancesForObject(FIRMWARE, fwLwM2MDevice = new FwLwM2MDevice()); initializer.setInstancesForObject(SOFTWARE_MANAGEMENT, swLwM2MDevice = new SwLwM2MDevice()); initializer.setClassForObject(ACCESS_CONTROL, DummyInstanceEnabler.class); - initializer.setInstancesForObject(BINARY_APP_DATA_CONTAINER, lwM2MBinaryAppDataContainer = new LwM2mBinaryAppDataContainer(executor, objectInstanceId_0), - new LwM2mBinaryAppDataContainer(executor, objectInstanceId_1)); + initializer.setInstancesForObject(BINARY_APP_DATA_CONTAINER, lwM2MBinaryAppDataContainer = new LwM2mBinaryAppDataContainer(executor, OBJECT_INSTANCE_ID_0), + new LwM2mBinaryAppDataContainer(executor, OBJECT_INSTANCE_ID_1)); locationParams = new LwM2MLocationParams(); locationParams.getPos(); - initializer.setInstancesForObject(LOCATION, new LwM2mLocation(locationParams.getLatitude(), locationParams.getLongitude(), locationParams.getScaleFactor(), executor, objectInstanceId_0)); - initializer.setInstancesForObject(TEMPERATURE_SENSOR, lwM2MTemperatureSensor = new LwM2mTemperatureSensor(executor, objectInstanceId_0), new LwM2mTemperatureSensor(executor, objectInstanceId_12)); + initializer.setInstancesForObject(LOCATION, new LwM2mLocation(locationParams.getLatitude(), locationParams.getLongitude(), locationParams.getScaleFactor(), executor, OBJECT_INSTANCE_ID_0)); + initializer.setInstancesForObject(TEMPERATURE_SENSOR, lwM2MTemperatureSensor = new LwM2mTemperatureSensor(executor, OBJECT_INSTANCE_ID_0), new LwM2mTemperatureSensor(executor, OBJECT_INSTANCE_ID_12)); - DtlsConnectorConfig.Builder dtlsConfig = new DtlsConnectorConfig.Builder(); - dtlsConfig.setRecommendedCipherSuitesOnly(true); - dtlsConfig.setClientOnly(); + DtlsConnectorConfig.Builder dtlsConfig = new DtlsConnectorConfig.Builder(coapConfig); + dtlsConfig.set(DTLS_RECOMMENDED_CIPHER_SUITES_ONLY, true); DefaultRegistrationEngineFactory engineFactory = new DefaultRegistrationEngineFactory(); engineFactory.setReconnectOnUpdate(false); engineFactory.setResumeOnConnect(true); - EndpointFactory endpointFactory = new EndpointFactory() { - - @Override - public CoapEndpoint createUnsecuredEndpoint(InetSocketAddress address, NetworkConfig coapConfig, - ObservationStore store) { - CoapEndpoint.Builder builder = new CoapEndpoint.Builder(); - builder.setInetSocketAddress(address); - builder.setNetworkConfig(coapConfig); - return builder.build(); - } - - @Override - public CoapEndpoint createSecuredEndpoint(DtlsConnectorConfig dtlsConfig, NetworkConfig coapConfig, - ObservationStore store) { - CoapEndpoint.Builder builder = new CoapEndpoint.Builder(); - DtlsConnectorConfig.Builder dtlsConfigBuilder = new DtlsConnectorConfig.Builder(dtlsConfig); - - // tricks to be able to change psk information on the fly -// AdvancedPskStore pskStore = dtlsConfig.getAdvancedPskStore(); -// if (pskStore != null) { -// PskPublicInformation identity = pskStore.getIdentity(null, null); -// SecretKey key = pskStore -// .requestPskSecretResult(ConnectionId.EMPTY, null, identity, null, null, null).getSecret(); -// singlePSKStore = new SinglePSKStore(identity, key); -// dtlsConfigBuilder.setAdvancedPskStore(singlePSKStore); -// } - builder.setConnector(new DTLSConnector(dtlsConfigBuilder.build())); - builder.setNetworkConfig(coapConfig); - return builder.build(); - } - }; - - LeshanClientBuilder builder = new LeshanClientBuilder(endpoint); builder.setLocalAddress("0.0.0.0", port); builder.setObjects(initializer.createAll()); builder.setCoapConfig(coapConfig); builder.setDtlsConfig(dtlsConfig); builder.setRegistrationEngineFactory(engineFactory); - builder.setEndpointFactory(endpointFactory); builder.setSharedExecutor(executor); builder.setDecoder(new DefaultLwM2mDecoder(false)); builder.setEncoder(new DefaultLwM2mEncoder(new LwM2mValueConverterImpl(), false)); - client = builder.build(); + clientState = ON_INIT; + clientStates = new HashSet<>(); + clientStates.add(clientState); + leshanClient = builder.build(); LwM2mClientObserver observer = new LwM2mClientObserver() { @Override public void onBootstrapStarted(ServerIdentity bsserver, BootstrapRequest request) { - log.info("ClientObserver -> onBootstrapStarted..."); + clientState = ON_BOOTSTRAP_STARTED; + clientStates.add(clientState); } @Override public void onBootstrapSuccess(ServerIdentity bsserver, BootstrapRequest request) { - log.info("ClientObserver -> onBootstrapSuccess..."); + clientState = ON_BOOTSTRAP_SUCCESS; + clientStates.add(clientState); } @Override public void onBootstrapFailure(ServerIdentity bsserver, BootstrapRequest request, ResponseCode responseCode, String errorMessage, Exception cause) { - log.info("ClientObserver -> onBootstrapFailure..."); + clientState = ON_BOOTSTRAP_FAILURE; + clientStates.add(clientState); } @Override public void onBootstrapTimeout(ServerIdentity bsserver, BootstrapRequest request) { - log.info("ClientObserver -> onBootstrapTimeout..."); + clientState = ON_BOOTSTRAP_TIMEOUT; + clientStates.add(clientState); } @Override public void onRegistrationStarted(ServerIdentity server, RegisterRequest request) { -// log.info("ClientObserver -> onRegistrationStarted... EndpointName [{}]", request.getEndpointName()); + clientState = ON_REGISTRATION_STARTED; + clientStates.add(clientState); } @Override public void onRegistrationSuccess(ServerIdentity server, RegisterRequest request, String registrationID) { - log.info("ClientObserver -> onRegistrationSuccess... EndpointName [{}] [{}]", request.getEndpointName(), registrationID); + clientState = ON_REGISTRATION_SUCCESS; + clientStates.add(clientState); } @Override public void onRegistrationFailure(ServerIdentity server, RegisterRequest request, ResponseCode responseCode, String errorMessage, Exception cause) { - log.info("ClientObserver -> onRegistrationFailure... ServerIdentity [{}]", server); + clientState = ON_REGISTRATION_FAILURE; + clientStates.add(clientState); } @Override public void onRegistrationTimeout(ServerIdentity server, RegisterRequest request) { - log.info("ClientObserver -> onRegistrationTimeout... RegisterRequest [{}]", request); + clientState = ON_REGISTRATION_TIMEOUT; + clientStates.add(clientState); } @Override public void onUpdateStarted(ServerIdentity server, UpdateRequest request) { -// log.info("ClientObserver -> onUpdateStarted... UpdateRequest [{}]", request); + clientState = ON_UPDATE_STARTED; + clientStates.add(clientState); } @Override public void onUpdateSuccess(ServerIdentity server, UpdateRequest request) { -// log.info("ClientObserver -> onUpdateSuccess... UpdateRequest [{}]", request); + clientState = ON_UPDATE_SUCCESS; + clientStates.add(clientState); } @Override public void onUpdateFailure(ServerIdentity server, UpdateRequest request, ResponseCode responseCode, String errorMessage, Exception cause) { - + clientState = ON_UPDATE_FAILURE; + clientStates.add(clientState); } @Override public void onUpdateTimeout(ServerIdentity server, UpdateRequest request) { - + clientState = ON_UPDATE_TIMEOUT; + clientStates.add(clientState); } @Override public void onDeregistrationStarted(ServerIdentity server, DeregisterRequest request) { - log.info("ClientObserver ->onDeregistrationStarted... DeregisterRequest [{}]", request.getRegistrationId()); - + clientState = ON_DEREGISTRATION_STARTED; + clientStates.add(clientState); } @Override public void onDeregistrationSuccess(ServerIdentity server, DeregisterRequest request) { - log.info("ClientObserver ->onDeregistrationSuccess... DeregisterRequest [{}]", request.getRegistrationId()); - + clientState = ON_DEREGISTRATION_SUCCESS; + clientStates.add(clientState); } @Override public void onDeregistrationFailure(ServerIdentity server, DeregisterRequest request, ResponseCode responseCode, String errorMessage, Exception cause) { - log.info("ClientObserver ->onDeregistrationFailure... DeregisterRequest [{}] [{}]", request.getRegistrationId(), request.getRegistrationId()); + clientState = ON_DEREGISTRATION_FAILURE; + clientStates.add(clientState); } @Override public void onDeregistrationTimeout(ServerIdentity server, DeregisterRequest request) { - log.info("ClientObserver ->onDeregistrationTimeout... DeregisterRequest [{}] [{}]", request.getRegistrationId(), request.getRegistrationId()); + clientState = ON_DEREGISTRATION_TIMEOUT; + clientStates.add(clientState); } @Override public void onUnexpectedError(Throwable unexpectedError) { - + clientState = ON_EXPECTED_ERROR; + clientStates.add(clientState); } }; - this.client.addObserver(observer); + this.leshanClient.addObserver(observer); + if (!isRpc) { - client.start(); + this.start(true); } } public void destroy() { - if (client != null) { - client.destroy(true); + if (leshanClient != null) { + leshanClient.destroy(true); + } + if (lwm2mSecurityBs != null) { + lwm2mSecurityBs = null; + } + if (lwm2mSecurity != null) { + lwm2mSecurity = null; + } + if (lwm2mServerBs != null) { + lwm2mServerBs = null; } if (lwm2mServer != null) { lwm2mServer = null; @@ -278,10 +328,29 @@ public class LwM2MTestClient { } } - public void start() { - if (client != null) { - client.start(); + public void start(boolean isStartLw) { + if (leshanClient != null) { + leshanClient.start(); + if (isStartLw) { + this.awaitClientAfterStartConnectLw(); + } } } + private void awaitClientAfterStartConnectLw() { + LwM2mClient lwM2MClient = this.clientContext.getClientByEndpoint(endpoint); + CountDownLatch latch = new CountDownLatch(1); + Mockito.doAnswer(invocation -> { + latch.countDown(); + return null; + }).when(defaultLwM2mUplinkMsgHandlerTest).initAttributes(lwM2MClient, true); + + try { + if (!latch.await(1, TimeUnit.SECONDS)) { + throw new RuntimeException("Failed to await TimeOut lwm2m client initialization!"); + } + } catch (InterruptedException e) { + throw new RuntimeException("Exception Failed to await lwm2m client initialization! ", e); + } + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mBinaryAppDataContainer.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mBinaryAppDataContainer.java index b7ac889649..797a5da2e3 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mBinaryAppDataContainer.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mBinaryAppDataContainer.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,8 +66,7 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements * "value":4 * }, */ -// private String data = "InNlcnZpY2VJZCI6Ik1ldGVyIiwNCiJzZXJ2aWNlRGF0YSI6ew0KImN1cnJlbnRSZWFkaW5nIjoiNDYuMyIsDQoic2lnbmFsU3RyZW5ndGgiOjE2LA0KImRhaWx5QWN0aXZpdHlUaW1lIjo1NzA2DQo="; -// private byte[] data; + Map data; private Integer priority = 0; private Time timestamp; @@ -82,9 +81,11 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements public LwM2mBinaryAppDataContainer(ScheduledExecutorService executorService, Integer id) { try { if (id != null) this.setId(id); - executorService.scheduleWithFixedDelay(() -> -// fireResourcesChange(0, 2), 5000, 5000, TimeUnit.MILLISECONDS); - fireResourcesChange(0, 2), 1800000, 1800000, TimeUnit.MILLISECONDS); // 30 MIN + executorService.scheduleWithFixedDelay(() -> { + fireResourceChange(0); + fireResourceChange(2); + } + , 1800000, 1800000, TimeUnit.MILLISECONDS); // 30 MIN } catch (Throwable e) { log.error("[{}]Throwable", e.toString()); e.printStackTrace(); @@ -93,15 +94,11 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements @Override public ReadResponse read(ServerIdentity identity, int resourceId) { -// log.warn("Read on Location resource /[{}]/[{}]/[{}]", getModel().id, getId(), resourceId); try { switch (resourceId) { case 0: -// log.warn("Read on Location resource /[{}]/[{}]/[{}]", getModel().id, getId(), resourceId); ReadResponse response = ReadResponse.success(resourceId, getData(), ResourceModel.Type.OPAQUE); -// log.warn("Response [{}]", response); return response; - case 1: return ReadResponse.success(resourceId, getPriority()); case 2: @@ -132,23 +129,23 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements } case 1: setPriority((Integer) (value.getValue() instanceof Long ? ((Long) value.getValue()).intValue() : value.getValue())); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); case 2: setTimestamp(((Date) value.getValue()).getTime()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); case 3: setDescription((String) value.getValue()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); case 4: setDataFormat((String) value.getValue()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); case 5: setAppID((Integer) value.getValue()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); default: return super.write(identity, replace, resourceId, value); @@ -168,7 +165,6 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements } private String getDataFormat() { -// return this.dataFormat == null ? "base64" : this.dataFormat; return this.dataFormat == null ? "OPAQUE" : this.dataFormat; } @@ -177,7 +173,8 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements } private String getDescription() { - return this.description == null ? "meter reading" : this.description; +// return this.description == null ? "meter reading" : this.description; + return this.description; } private void setTimestamp(long time) { @@ -188,12 +185,11 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements return this.timestamp != null ? this.timestamp : new Time(new Date().getTime()); } -// fireResourcesChange(resourceId); private boolean setData(LwM2mResource value, boolean replace) { try { if (value instanceof LwM2mMultipleResource) { if (replace || this.data == null) { - this.data = new HashMap<>(); + this.data = new HashMap<>(); } value.getInstances().values().forEach(v -> { this.data.put(v.getId(), (byte[]) v.getValue()); @@ -208,7 +204,10 @@ public class LwM2mBinaryAppDataContainer extends BaseInstanceEnabler implements } private Map getData() { -// this.data.put(23, new byte[]{0,0, 2,3}); + if (data == null) { + this.data = new HashMap<>(); + this.data.put(0, new byte[]{(byte) 0xAC}); + } return data; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mLocation.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mLocation.java index 079cd9fdac..d9fef9eab3 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mLocation.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mLocation.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,8 +74,10 @@ public class LwM2mLocation extends BaseInstanceEnabler implements Destroyable { } this.scaleFactor = scaleFactor; timestamp = new Date(); - executorService.scheduleWithFixedDelay(() -> - fireResourcesChange(0, 1), 10000, 10000, TimeUnit.MILLISECONDS); + executorService.scheduleWithFixedDelay(() -> { + fireResourceChange(0); + fireResourceChange(1); + }, 10000, 10000, TimeUnit.MILLISECONDS); } catch (Throwable e) { log.error("[{}]Throwable", e.toString()); e.printStackTrace(); @@ -101,19 +103,15 @@ public class LwM2mLocation extends BaseInstanceEnabler implements Destroyable { switch (nextMove.charAt(0)) { case 'w': moveLatitude(1.0f); -// log.info("Move to North [{}]/[{}]", getLatitude(), getLongitude()); break; case 'a': moveLongitude(-1.0f); -// log.info("Move to East [{}]/[{}]", getLatitude(), getLongitude()); break; case 's': moveLatitude(-1.0f); -// log.info("Move to South [{}]/[{}]", getLatitude(), getLongitude()); break; case 'd': moveLongitude(1.0f); -// log.info("Move to West [{}]/[{}]", getLatitude(), getLongitude()); break; } } @@ -121,13 +119,16 @@ public class LwM2mLocation extends BaseInstanceEnabler implements Destroyable { private void moveLatitude(float delta) { latitude = latitude + delta * scaleFactor; timestamp = new Date(); - fireResourcesChange(0, 5); + fireResourceChange(0); + fireResourceChange(5); } private void moveLongitude(float delta) { longitude = longitude + delta * scaleFactor; timestamp = new Date(); - fireResourcesChange(1, 5); + fireResourceChange(1); + fireResourceChange(5); + } public float getLatitude() { diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mTemperatureSensor.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mTemperatureSensor.java index 2e52cfc812..919d69d919 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mTemperatureSensor.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/LwM2mTemperatureSensor.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,10 +93,9 @@ public class LwM2mTemperatureSensor extends BaseInstanceEnabler implements Destr float delta = (RANDOM.nextInt(20) - 10) / 10f; currentTemp += delta; Integer changedResource = adjustMinMaxMeasuredValue(currentTemp); + fireResourceChange(5700); if (changedResource != null) { - fireResourcesChange(5700, changedResource); - } else { - fireResourcesChange(5700); + fireResourceChange(changedResource); } } @@ -127,5 +126,4 @@ public class LwM2mTemperatureSensor extends BaseInstanceEnabler implements Destr } - } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/Lwm2mServer.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/Lwm2mServer.java new file mode 100644 index 0000000000..d4bac0a683 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/Lwm2mServer.java @@ -0,0 +1,235 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.lwm2m.client; + +import lombok.extern.slf4j.Slf4j; +import org.eclipse.leshan.client.resource.BaseInstanceEnabler; +import org.eclipse.leshan.client.resource.LwM2mInstanceEnabler; +import org.eclipse.leshan.client.servers.ServerIdentity; +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.model.ResourceModel.Type; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.request.BindingMode; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.response.WriteResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; + +/** + * A simple {@link LwM2mInstanceEnabler} for the Server (1) object. + */ +@Slf4j +public class Lwm2mServer extends BaseInstanceEnabler { + + private static final Logger LOG = LoggerFactory.getLogger(Lwm2mServer.class); + + private final static List supportedResources = Arrays.asList(0, 1, 2, 3, 6, 7, 8, 22); + + private int shortServerId; + private long lifetime; + private Long defaultMinPeriod; + private Long defaultMaxPeriod; + private EnumSet binding; + private BindingMode preferredTransport; + private boolean notifyWhenDisable; + + public Lwm2mServer() { + // should only be used at bootstrap time + } + + public Lwm2mServer(int shortServerId, long lifetime, EnumSet binding, boolean notifyWhenDisable, + BindingMode preferredTransport) { + this.shortServerId = shortServerId; + this.lifetime = lifetime; + this.binding = binding; + this.notifyWhenDisable = notifyWhenDisable; + this.preferredTransport = preferredTransport; + } + + public Lwm2mServer(int shortServerId, long lifetime) { + this(shortServerId, lifetime, EnumSet.of(BindingMode.U), false, BindingMode.U); + } + + @Override + public ReadResponse read(ServerIdentity identity, int resourceid) { + if (!identity.isSystem()) + LOG.debug("Read on Server resource /{}/{}/{}", getModel().id, getId(), resourceid); + + switch (resourceid) { + case 0: // short server ID + return ReadResponse.success(resourceid, shortServerId); + + case 1: // lifetime + return ReadResponse.success(resourceid, lifetime); + + case 2: // default min period + if (null == defaultMinPeriod) + return ReadResponse.notFound(); + return ReadResponse.success(resourceid, defaultMinPeriod); + + case 3: // default max period + if (null == defaultMaxPeriod) + return ReadResponse.notFound(); + return ReadResponse.success(resourceid, defaultMaxPeriod); + + case 6: // notification storing when disable or offline + return ReadResponse.success(resourceid, notifyWhenDisable); + + case 7: // binding + return ReadResponse.success(resourceid, BindingMode.toString(binding)); + + case 22: // preferred transport + if (preferredTransport == null) + return ReadResponse.notFound(); + return ReadResponse.success(resourceid, preferredTransport.toString()); + + default: + return super.read(identity, resourceid); + } + } + + @Override + public WriteResponse write(ServerIdentity identity, boolean replace, int resourceid, LwM2mResource value) { + if (!identity.isSystem()) + log.debug("Write on Server resource /{}/{}/{}", getModel().id, getId(), resourceid); + + switch (resourceid) { + case 0: + if (value.getType() != Type.INTEGER) { + return WriteResponse.badRequest("invalid type"); + } + int previousShortServerId = shortServerId; + shortServerId = ((Long) value.getValue()).intValue(); + if (previousShortServerId != shortServerId) + fireResourceChange(resourceid); + return WriteResponse.success(); + + case 1: + if (value.getType() != Type.INTEGER) { + return WriteResponse.badRequest("invalid type"); + } + long previousLifetime = lifetime; + lifetime = (Long) value.getValue(); + if (previousLifetime != lifetime) + fireResourceChange(resourceid); + return WriteResponse.success(); + + case 2: + if (value.getType() != Type.INTEGER) { + return WriteResponse.badRequest("invalid type"); + } + Long previousDefaultMinPeriod = defaultMinPeriod; + defaultMinPeriod = (Long) value.getValue(); + if (!Objects.equals(previousDefaultMinPeriod, defaultMinPeriod)) + fireResourceChange(resourceid); + return WriteResponse.success(); + + case 3: + if (value.getType() != Type.INTEGER) { + return WriteResponse.badRequest("invalid type"); + } + Long previousDefaultMaxPeriod = defaultMaxPeriod; + defaultMaxPeriod = (Long) value.getValue(); + if (!Objects.equals(previousDefaultMaxPeriod, defaultMaxPeriod)) + fireResourceChange(resourceid); + return WriteResponse.success(); + + case 6: // notification storing when disable or offline + if (value.getType() != Type.BOOLEAN) { + return WriteResponse.badRequest("invalid type"); + } + boolean previousNotifyWhenDisable = notifyWhenDisable; + notifyWhenDisable = (boolean) value.getValue(); + if (previousNotifyWhenDisable != notifyWhenDisable) + fireResourceChange(resourceid); + return WriteResponse.success(); + + case 7: // binding + if (value.getType() != Type.STRING) { + return WriteResponse.badRequest("invalid type"); + } + try { + EnumSet previousBinding = binding; + binding = BindingMode.parse((String) value.getValue()); + if (!Objects.equals(previousBinding, binding)) + fireResourceChange(resourceid); + return WriteResponse.success(); + } catch (IllegalArgumentException e) { + return WriteResponse.badRequest("invalid value"); + } + case 22: // preferredTransport + if (value.getType() != Type.STRING) { + return WriteResponse.badRequest("invalid type"); + } + try { + BindingMode previousPreferedTransport = preferredTransport; + preferredTransport = BindingMode.valueOf((String) value.getValue()); + if (!Objects.equals(previousPreferedTransport, preferredTransport)) + fireResourceChange(resourceid); + return WriteResponse.success(); + } catch (IllegalArgumentException e) { + return WriteResponse.badRequest("invalid value"); + } + + default: + return super.write(identity, replace, resourceid, value); + } + } + + @Override + public ExecuteResponse execute(ServerIdentity identity, int resourceid, String params) { + log.info("Execute on Server resource /{}/{}/{}", getModel().id, getId(), resourceid); + if (resourceid == 8) { + getLwM2mClient().triggerRegistrationUpdate(identity); + return ExecuteResponse.success(); + } else if (resourceid == 9) { + boolean success = getLwM2mClient().triggerClientInitiatedBootstrap(true); + if (success) { + return ExecuteResponse.success(); + } + else { + return ExecuteResponse.badRequest("probably no bootstrap server configured"); + } + } else { + return super.execute(identity, resourceid, params); + } + } + + @Override + public void reset(int resourceid) { + switch (resourceid) { + case 2: + defaultMinPeriod = null; + break; + case 3: + defaultMaxPeriod = null; + break; + default: + super.reset(resourceid); + } + } + + @Override + public List getAvailableResourceIds(ObjectModel model) { + return supportedResources; + } +} diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SimpleLwM2MDevice.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SimpleLwM2MDevice.java index 8d5c46a1a0..ffd3df0a09 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SimpleLwM2MDevice.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SimpleLwM2MDevice.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.thingsboard.server.transport.lwm2m.client; import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.client.resource.BaseInstanceEnabler; import org.eclipse.leshan.client.servers.ServerIdentity; +import org.eclipse.leshan.core.Destroyable; import org.eclipse.leshan.core.model.ObjectModel; import org.eclipse.leshan.core.model.ResourceModel; import org.eclipse.leshan.core.node.LwM2mResource; @@ -25,23 +26,45 @@ import org.eclipse.leshan.core.response.ExecuteResponse; import org.eclipse.leshan.core.response.ReadResponse; import org.eclipse.leshan.core.response.WriteResponse; -import javax.security.auth.Destroyable; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.PrimitiveIterator; import java.util.Random; import java.util.TimeZone; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; @Slf4j public class SimpleLwM2MDevice extends BaseInstanceEnabler implements Destroyable { private static final Random RANDOM = new Random(); + private static final int min = 5; + private static final int max = 50; + private static final PrimitiveIterator.OfInt randomIterator = new Random().ints(min,max + 1).iterator(); private static final List supportedResources = Arrays.asList(0, 1, 2, 3, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21); + + public SimpleLwM2MDevice() { + } + + public SimpleLwM2MDevice(ScheduledExecutorService executorService) { + try { + executorService.scheduleWithFixedDelay(() -> { + fireResourceChange(9); + } + , 1800000, 1800000, TimeUnit.MILLISECONDS); // 30 MIN + } catch (Throwable e) { + log.error("[{}]Throwable", e.toString()); + e.printStackTrace(); + } + } + + @Override public ReadResponse read(ServerIdentity identity, int resourceId) { if (!identity.isSystem()) @@ -103,11 +126,11 @@ public class SimpleLwM2MDevice extends BaseInstanceEnabler implements Destroyabl return WriteResponse.notFound(); case 14: setUtcOffset((String) value.getValue()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); case 15: setTimezone((String) value.getValue()); - fireResourcesChange(resourceId); + fireResourceChange(resourceId); return WriteResponse.success(); default: return super.write(identity, replace, resourceId, value); @@ -135,7 +158,8 @@ public class SimpleLwM2MDevice extends BaseInstanceEnabler implements Destroyabl } private int getBatteryLevel() { - return 42; + return randomIterator.nextInt(); +// return 42; } private long getMemoryFree() { diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SwLwM2MDevice.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SwLwM2MDevice.java index 4b1e02a68d..b623f4fa19 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SwLwM2MDevice.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/client/SwLwM2MDevice.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,16 +128,17 @@ public class SwLwM2MDevice extends BaseInstanceEnabler implements Destroyable { try { state.set(1); updateResult.set(1); - fireResourcesChange(7, 9); + fireResourceChange(7); + fireResourceChange(9); Thread.sleep(100); state.set(2); - fireResourcesChange(7); + fireResourceChange(7); Thread.sleep(100); state.set(3); - fireResourcesChange(7); + fireResourceChange(7); Thread.sleep(100); updateResult.set(3); - fireResourcesChange(9); + fireResourceChange(9); } catch (Exception e) { } @@ -148,7 +149,8 @@ public class SwLwM2MDevice extends BaseInstanceEnabler implements Destroyable { scheduler.schedule(() -> { state.set(4); updateResult.set(2); - fireResourcesChange(7, 9); + fireResourceChange(7); + fireResourceChange(9); }, 100, TimeUnit.MILLISECONDS); } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/AbstractOtaLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/AbstractOtaLwM2MIntegrationTest.java index e78d74bdcd..5d84ef2b89 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/AbstractOtaLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/AbstractOtaLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,10 +29,13 @@ import static org.thingsboard.server.common.data.ota.OtaPackageType.SOFTWARE; @DaoSqlTest public abstract class AbstractOtaLwM2MIntegrationTest extends AbstractLwM2MIntegrationTest { - private final String[] resources = new String[]{"3.xml", "5.xml", "9.xml"}; + private final String[] RESOURCES_OTA = new String[]{"3.xml", "5.xml", "9.xml"}; + protected static final String CLIENT_ENDPOINT_WITHOUT_FW_INFO = "WithoutFirmwareInfoDevice"; + protected static final String CLIENT_ENDPOINT_OTA5 = "Ota5_Device"; + protected static final String CLIENT_ENDPOINT_OTA9 = "Ota9_Device"; public AbstractOtaLwM2MIntegrationTest() { - setResources(this.resources); + setResources(this.RESOURCES_OTA); } protected OtaPackageInfo createFirmware() throws Exception { diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/sql/OtaLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/sql/OtaLwM2MIntegrationTest.java index 903750663a..f7d1303674 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/sql/OtaLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/ota/sql/OtaLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,8 @@ import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.device.credentials.lwm2m.NoSecClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.kv.KvEntry; import org.thingsboard.server.common.data.kv.TsKvEntry; import org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus; @@ -46,107 +47,57 @@ import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.QUEU import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATING; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.VERIFIED; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURITY; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @Slf4j public class OtaLwM2MIntegrationTest extends AbstractOtaLwM2MIntegrationTest { - public static final int TIMEOUT = 30; - private final String OTA_TRANSPORT_CONFIGURATION = "{\n" + - " \"type\": \"LWM2M\",\n" + - " \"observeAttr\": {\n" + - " \"keyName\": {\n" + - " \"/5_1.0/0/3\": \"state\",\n" + - " \"/5_1.0/0/5\": \"updateResult\",\n" + - " \"/5_1.0/0/6\": \"pkgname\",\n" + - " \"/5_1.0/0/7\": \"pkgversion\",\n" + - " \"/5_1.0/0/9\": \"firmwareUpdateDeliveryMethod\",\n" + - " \"/9_1.0/0/0\": \"pkgname\",\n" + - " \"/9_1.0/0/1\": \"pkgversion\",\n" + - " \"/9_1.0/0/7\": \"updateState\",\n" + - " \"/9_1.0/0/9\": \"updateResult\"\n" + - " },\n" + - " \"observe\": [\n" + - " \"/5_1.0/0/3\",\n" + - " \"/5_1.0/0/5\",\n" + - " \"/5_1.0/0/6\",\n" + - " \"/5_1.0/0/7\",\n" + - " \"/5_1.0/0/9\",\n" + - " \"/9_1.0/0/0\",\n" + - " \"/9_1.0/0/1\",\n" + - " \"/9_1.0/0/7\",\n" + - " \"/9_1.0/0/9\"\n" + - " ],\n" + - " \"attribute\": [],\n" + - " \"telemetry\": [\n" + - " \"/5_1.0/0/3\",\n" + - " \"/5_1.0/0/5\",\n" + - " \"/5_1.0/0/6\",\n" + - " \"/5_1.0/0/7\",\n" + - " \"/5_1.0/0/9\",\n" + - " \"/9_1.0/0/0\",\n" + - " \"/9_1.0/0/1\",\n" + - " \"/9_1.0/0/7\",\n" + - " \"/9_1.0/0/9\"\n" + - " ],\n" + - " \"attributeLwm2m\": {}\n" + - " },\n" + - " \"bootstrapServerUpdateEnable\": true,\n" + - " \"bootstrap\": [\n" + - " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5687,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 111,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": true,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " },\n" + - " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5685,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 123,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": false,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " }\n" + - " ],\n" + - " \"clientLwM2mSettings\": {\n" + - " \"edrxCycle\": null,\n" + - " \"powerMode\": \"DRX\",\n" + - " \"fwUpdateResource\": null,\n" + - " \"fwUpdateStrategy\": 1,\n" + - " \"psmActivityTimer\": null,\n" + - " \"swUpdateResource\": null,\n" + - " \"swUpdateStrategy\": 1,\n" + - " \"pagingTransmissionWindow\": null,\n" + - " \"clientOnlyObserveAfterConnect\": 1\n" + - " }\n" + - "}"; + protected final String OBSERVE_ATTRIBUTES_WITH_PARAMS_OTA = - @Test + " {\n" + + " \"keyName\": {\n" + + " \"/5_1.0/0/3\": \"state\",\n" + + " \"/5_1.0/0/5\": \"updateResult\",\n" + + " \"/5_1.0/0/6\": \"pkgname\",\n" + + " \"/5_1.0/0/7\": \"pkgversion\",\n" + + " \"/5_1.0/0/9\": \"firmwareUpdateDeliveryMethod\",\n" + + " \"/9_1.0/0/0\": \"pkgname\",\n" + + " \"/9_1.0/0/1\": \"pkgversion\",\n" + + " \"/9_1.0/0/7\": \"updateState\",\n" + + " \"/9_1.0/0/9\": \"updateResult\"\n" + + " },\n" + + " \"observe\": [\n" + + " \"/5_1.0/0/3\",\n" + + " \"/5_1.0/0/5\",\n" + + " \"/5_1.0/0/6\",\n" + + " \"/5_1.0/0/7\",\n" + + " \"/5_1.0/0/9\",\n" + + " \"/9_1.0/0/0\",\n" + + " \"/9_1.0/0/1\",\n" + + " \"/9_1.0/0/7\",\n" + + " \"/9_1.0/0/9\"\n" + + " ],\n" + + " \"attribute\": [],\n" + + " \"telemetry\": [\n" + + " \"/5_1.0/0/3\",\n" + + " \"/5_1.0/0/5\",\n" + + " \"/5_1.0/0/6\",\n" + + " \"/5_1.0/0/7\",\n" + + " \"/5_1.0/0/9\",\n" + + " \"/9_1.0/0/0\",\n" + + " \"/9_1.0/0/1\",\n" + + " \"/9_1.0/0/7\",\n" + + " \"/9_1.0/0/9\"\n" + + " ],\n" + + " \"attributeLwm2m\": {}\n" + + " }"; + @Test public void testFirmwareUpdateWithClientWithoutFirmwareOtaInfoFromProfile() throws Exception { - String endpoint = "WithoutFirmwareInfoDevice"; - setEndpoint(endpoint); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITH_PARAMS, getBootstrapServerCredentialsNoSec(NONE)); createDeviceProfile(transportConfiguration); - NoSecClientCredential credentials = createNoSecClientCredentials(endpoint); - final Device device = createDevice(credentials); - createNewClient(SECURITY, COAP_CONFIG, false); - - Thread.sleep(1000); - + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(this.CLIENT_ENDPOINT_WITHOUT_FW_INFO)); + final Device device = createDevice(deviceCredentials, this.CLIENT_ENDPOINT_WITHOUT_FW_INFO); + createNewClient(SECURITY_NO_SEC, COAP_CONFIG, false, this.CLIENT_ENDPOINT_WITHOUT_FW_INFO, false, null); device.setFirmwareId(createFirmware().getId()); final Device savedDevice = doPost("/api/device", device, Device.class); @@ -165,15 +116,11 @@ public class OtaLwM2MIntegrationTest extends AbstractOtaLwM2MIntegrationTest { @Test public void testFirmwareUpdateByObject5() throws Exception { - String endpoint = "Ota5_Device"; - setEndpoint(endpoint); - createDeviceProfile(OTA_TRANSPORT_CONFIGURATION); - NoSecClientCredential credentials = createNoSecClientCredentials(endpoint); - final Device device = createDevice(credentials); - createNewClient(SECURITY, COAP_CONFIG, false); - - Thread.sleep(1000); - + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITH_PARAMS_OTA, getBootstrapServerCredentialsNoSec(NONE)); + createDeviceProfile(transportConfiguration); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(this.CLIENT_ENDPOINT_OTA5)); + final Device device = createDevice(deviceCredentials, this.CLIENT_ENDPOINT_OTA5); + createNewClient(SECURITY_NO_SEC, COAP_CONFIG, false, this.CLIENT_ENDPOINT_OTA5, false, null); device.setFirmwareId(createFirmware().getId()); final Device savedDevice = doPost("/api/device", device, Device.class); @@ -204,12 +151,11 @@ public class OtaLwM2MIntegrationTest extends AbstractOtaLwM2MIntegrationTest { * */ @Test public void testSoftwareUpdateByObject9() throws Exception { - String endpoint = "Ota9_Device"; - setEndpoint(endpoint); - createDeviceProfile(OTA_TRANSPORT_CONFIGURATION); - NoSecClientCredential credentials = createNoSecClientCredentials(endpoint); - final Device device = createDevice(credentials); - createNewClient(SECURITY, COAP_CONFIG, false); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITH_PARAMS_OTA, getBootstrapServerCredentialsNoSec(NONE)); + createDeviceProfile(transportConfiguration); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(this.CLIENT_ENDPOINT_OTA9)); + final Device device = createDevice(deviceCredentials, this.CLIENT_ENDPOINT_OTA9); + createNewClient(SECURITY_NO_SEC, COAP_CONFIG, false, this.CLIENT_ENDPOINT_OTA9, false, null); Thread.sleep(1000); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/AbstractRpcLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/AbstractRpcLwM2MIntegrationTest.java index 95878b74d1..28fd86a383 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/AbstractRpcLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/AbstractRpcLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,13 @@ package org.thingsboard.server.transport.lwm2m.rpc; import org.junit.Before; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.device.credentials.lwm2m.NoSecClientCredential; -import org.thingsboard.server.controller.TbTestWebSocketClient; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.lwm2m.AbstractLwM2MIntegrationTest; + import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; @@ -33,28 +33,24 @@ import static org.eclipse.leshan.core.LwM2mId.FIRMWARE; import static org.eclipse.leshan.core.LwM2mId.SERVER; import static org.eclipse.leshan.core.LwM2mId.SOFTWARE_MANAGEMENT; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.BINARY_APP_DATA_CONTAINER; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURITY; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.TEMPERATURE_SENSOR; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_19_0_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_19_1_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_3_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_3_9; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_19_0_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_19_1_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_3_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_3_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_9; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resources; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; @DaoSqlTest public abstract class AbstractRpcLwM2MIntegrationTest extends AbstractLwM2MIntegrationTest { - protected String RPC_TRANSPORT_CONFIGURATION; - - protected ScheduledExecutorService executor; - protected TbTestWebSocketClient wsClient; + protected String OBSERVE_ATTRIBUTES_WITH_PARAMS_RPC; protected String deviceId; public Set expectedObjects; public Set expectedObjectIdVers; @@ -64,36 +60,39 @@ public abstract class AbstractRpcLwM2MIntegrationTest extends AbstractLwM2MInteg protected String objectInstanceIdVer_1; protected String objectIdVer_0; protected String objectIdVer_2; - private static final Predicate predicate_3 = path -> (!((String) path).contains("/" + TEMPERATURE_SENSOR) && ((String) path).contains("/" + DEVICE)); + private static final Predicate PREDICATE_3 = path -> (!((String) path).startsWith("/" + TEMPERATURE_SENSOR) && ((String) path).startsWith("/" + DEVICE)); protected String objectIdVer_3; protected String objectInstanceIdVer_3; protected String objectInstanceIdVer_5; protected String objectInstanceIdVer_9; protected String objectIdVer_19; - protected String objectIdVer_50 = "/50"; + protected final String OBJECT_ID_VER_50 = "/50"; protected String objectIdVer_3303; protected static AtomicInteger endpointSequence = new AtomicInteger(); + protected static String DEVICE_ENDPOINT_RPC_PREF = "deviceEndpointRpc"; + protected String idVer_3_0_9; + protected String idVer_19_0_0; - public AbstractRpcLwM2MIntegrationTest(){ + public AbstractRpcLwM2MIntegrationTest() { setResources(resources); } @Before - public void beforeTest() throws Exception { - setEndpoint("deviceEndpointRpc" + endpointSequence.incrementAndGet()); - init(); - createNewClient (SECURITY, COAP_CONFIG, true); + public void startInitRPC() throws Exception { + initRpc(); + } + private void initRpc () throws Exception { + String endpoint = DEVICE_ENDPOINT_RPC_PREF + endpointSequence.incrementAndGet(); + createNewClient(SECURITY_NO_SEC, COAP_CONFIG, true, endpoint, false, null); expectedObjects = ConcurrentHashMap.newKeySet(); expectedObjectIdVers = ConcurrentHashMap.newKeySet(); expectedInstances = ConcurrentHashMap.newKeySet(); expectedObjectIdVerInstances = ConcurrentHashMap.newKeySet(); - client.getClient().getObjectTree().getObjectEnablers().forEach((key, val) -> { + lwM2MTestClient.getLeshanClient().getObjectTree().getObjectEnablers().forEach((key, val) -> { if (key > 0) { String objectVerId = "/" + key; - if (!val.getObjectModel().version.equals("1.0")) { - objectVerId += ("_" + val.getObjectModel().version); - } + objectVerId += ("_" + val.getObjectModel().version); expectedObjects.add("/" + key); expectedObjectIdVers.add(objectVerId); String finalObjectVerId = objectVerId; @@ -103,102 +102,58 @@ public abstract class AbstractRpcLwM2MIntegrationTest extends AbstractLwM2MInteg }); } }); - String ver_Id_0 = client.getClient().getObjectTree().getModel().getObjectModel(objectId_0).version; - if ("1.0".equals(ver_Id_0)) { - objectIdVer_0 = "/" + objectId_0; - } - else { - objectIdVer_0 = "/" + objectId_0 + "_" + ver_Id_0; - } - objectIdVer_2 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).contains("/" + ACCESS_CONTROL)).findFirst().get(); - objectIdVer_3 = (String) expectedObjects.stream().filter(predicate_3).findFirst().get(); - objectIdVer_19 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).contains("/" + BINARY_APP_DATA_CONTAINER)).findFirst().get(); - objectIdVer_3303 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).contains("/" + TEMPERATURE_SENSOR)).findFirst().get(); - objectInstanceIdVer_1 = (String) expectedObjectIdVerInstances.stream().filter(path -> (!((String) path).contains("/" + BINARY_APP_DATA_CONTAINER) && ((String) path).contains("/" + SERVER))).findFirst().get(); - objectInstanceIdVer_3 = (String) expectedObjectIdVerInstances.stream().filter(predicate_3).findFirst().get(); - objectInstanceIdVer_5 = (String) expectedObjectIdVerInstances.stream().filter(path -> ((String) path).contains("/" + FIRMWARE)).findFirst().get(); - objectInstanceIdVer_9 = (String) expectedObjectIdVerInstances.stream().filter(path -> ((String) path).contains("/" + SOFTWARE_MANAGEMENT)).findFirst().get(); - - RPC_TRANSPORT_CONFIGURATION = "{\n" + - " \"type\": \"LWM2M\",\n" + - " \"observeAttr\": {\n" + - " \"keyName\": {\n" + - " \"" + objectIdVer_3 + "/" + objectInstanceId_0 + "/" + resourceId_9 + "\": \"" + resourceIdName_3_9 + "\",\n" + - " \"" + objectIdVer_3 + "/" + objectInstanceId_0 + "/" + resourceId_14 + "\": \"" + resourceIdName_3_14 + "\",\n" + - " \"" + objectIdVer_19 + "/" + objectInstanceId_0 + "/" + resourceId_0 + "\": \"" + resourceIdName_19_0_0 + "\",\n" + - " \"" + objectIdVer_19 + "/" + objectInstanceId_1 + "/" + resourceId_0 + "\": \"" + resourceIdName_19_1_0 + "\"\n" + - " },\n" + - " \"observe\": [\n" + - " \"" + objectIdVer_3 + "/" + objectInstanceId_0 + "/" + resourceId_9 + "\",\n" + - " \"" + objectIdVer_19 + "/" + objectInstanceId_0 + "/" + resourceId_0 + "\"\n" + - " ],\n" + - " \"attribute\": [\n" + - " ],\n" + - " \"telemetry\": [\n" + - " \"" + objectIdVer_3 + "/" + objectInstanceId_0 + "/" + resourceId_9 + "\",\n" + - " \"" + objectIdVer_3 + "/" + objectInstanceId_0 + "/" + resourceId_14 + "\",\n" + - " \"" + objectIdVer_19 + "/" + objectInstanceId_0 + "/" + resourceId_0 + "\",\n" + - " \"" + objectIdVer_19 + "/" + objectInstanceId_1 + "/" + resourceId_0 + "\"\n" + - " ],\n" + - " \"attributeLwm2m\": {}\n" + - " },\n" + - " \"bootstrapServerUpdateEnable\": true,\n" + - " \"bootstrap\": [\n" + - " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5687,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 111,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": true,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " },\n" + + String ver_Id_0 = lwM2MTestClient.getLeshanClient().getObjectTree().getModel().getObjectModel(OBJECT_ID_0).version; + objectIdVer_0 = "/" + OBJECT_ID_0 + "_" + ver_Id_0; + objectIdVer_2 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).startsWith("/" + ACCESS_CONTROL)).findFirst().get(); + objectIdVer_3 = (String) expectedObjectIdVers.stream().filter(PREDICATE_3).findFirst().get(); + objectIdVer_19 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).startsWith("/" + BINARY_APP_DATA_CONTAINER)).findFirst().get(); + objectIdVer_3303 = (String) expectedObjectIdVers.stream().filter(path -> ((String) path).startsWith("/" + TEMPERATURE_SENSOR)).findFirst().get(); + objectInstanceIdVer_1 = (String) expectedObjectIdVerInstances.stream().filter(path -> (!((String) path).startsWith("/" + BINARY_APP_DATA_CONTAINER) && ((String) path).startsWith("/" + SERVER))).findFirst().get(); + objectInstanceIdVer_3 = (String) expectedObjectIdVerInstances.stream().filter(PREDICATE_3).findFirst().get(); + objectInstanceIdVer_5 = (String) expectedObjectIdVerInstances.stream().filter(path -> ((String) path).startsWith("/" + FIRMWARE)).findFirst().get(); + objectInstanceIdVer_9 = (String) expectedObjectIdVerInstances.stream().filter(path -> ((String) path).startsWith("/" + SOFTWARE_MANAGEMENT)).findFirst().get(); + + idVer_3_0_9 = objectIdVer_3 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_9; + idVer_19_0_0 = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_0; + + OBSERVE_ATTRIBUTES_WITH_PARAMS_RPC = " {\n" + - " \"host\": \"0.0.0.0\",\n" + - " \"port\": 5685,\n" + - " \"binding\": \"U\",\n" + - " \"lifetime\": 300,\n" + - " \"securityMode\": \"NO_SEC\",\n" + - " \"shortServerId\": 123,\n" + - " \"notifIfDisabled\": true,\n" + - " \"serverPublicKey\": \"\",\n" + - " \"defaultMinPeriod\": 1,\n" + - " \"bootstrapServerIs\": false,\n" + - " \"clientHoldOffTime\": 1,\n" + - " \"bootstrapServerAccountTimeout\": 0\n" + - " }\n" + - " ],\n" + - " \"clientLwM2mSettings\": {\n" + - " \"edrxCycle\": null,\n" + - " \"powerMode\": \"DRX\",\n" + - " \"fwUpdateResource\": null,\n" + - " \"fwUpdateStrategy\": 1,\n" + - " \"psmActivityTimer\": null,\n" + - " \"swUpdateResource\": null,\n" + - " \"swUpdateStrategy\": 1,\n" + - " \"pagingTransmissionWindow\": null,\n" + - " \"clientOnlyObserveAfterConnect\": 1\n" + - " }\n" + - "}"; - createDeviceProfile(RPC_TRANSPORT_CONFIGURATION); - - NoSecClientCredential credentials = createNoSecClientCredentials(endpoint); - final Device device = createDevice(credentials); + " \"keyName\": {\n" + + " \"" + idVer_3_0_9 + "\": \"" + RESOURCE_ID_NAME_3_9 + "\",\n" + + " \"" + objectIdVer_3 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_14 + "\": \"" + RESOURCE_ID_NAME_3_14 + "\",\n" + + " \"" + idVer_19_0_0 + "\": \"" + RESOURCE_ID_NAME_19_0_0 + "\",\n" + + " \"" + objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_1 + "/" + RESOURCE_ID_0 + "\": \"" + RESOURCE_ID_NAME_19_1_0 + "\"\n" + + " },\n" + + " \"observe\": [\n" + + " \"" + idVer_3_0_9 + "\",\n" + + " \"" + idVer_19_0_0 + "\"\n" + + " ],\n" + + " \"attribute\": [\n" + + " \"" + objectIdVer_3 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_14 + "\"\n" + + " ],\n" + + " \"telemetry\": [\n" + + " \"" + idVer_3_0_9 + "\",\n" + + " \"" + idVer_19_0_0 + "\",\n" + + " \"" + objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_1 + "/" + RESOURCE_ID_0 + "\"\n" + + " ],\n" + + " \"attributeLwm2m\": {}\n" + + " }"; + + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITH_PARAMS_RPC, getBootstrapServerCredentialsNoSec(NONE)); + createDeviceProfile(transportConfiguration); + + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(endpoint)); + final Device device = createDevice(deviceCredentials, endpoint); deviceId = device.getId().getId().toString(); - client.start(); - } + lwM2MTestClient.start(true); + } protected String pathIdVerToObjectId(String pathIdVer) { - if (pathIdVer.contains("_")){ - String [] objVer = pathIdVer.split("/"); - objVer[1] = objVer[1].split("_")[0]; - return String.join("/", objVer); + if (pathIdVer.contains("_")) { + String[] objVer = pathIdVer.split("/"); + objVer[1] = objVer[1].split("_")[0]; + return String.join("/", objVer); } return pathIdVer; } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationCreateTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationCreateTest.java index 4ab0d68794..9d251259bf 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationCreateTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationCreateTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,10 @@ import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTes import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_12; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_12; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_0; public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTest { @@ -43,8 +43,8 @@ public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testCreateObjectInstanceWithInstanceIdByIdKey_Result_CREATED() throws Exception { - String expectedPath = objectIdVer_19 + "/" + objectInstanceId_12; - String expectedValue = "{\"" + resourceId_0 + "\":{\"0\":\"00AC\"}, \"1\":1}"; + String expectedPath = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_12; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"0\":\"00AC\"}, \"1\":1}"; String actualResult = sendRPCreateById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CREATED.getName(), rpcActualResult.get("result").asText()); @@ -60,12 +60,12 @@ public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testCreateObjectInstanceWithInstanceIdAlreadyExistsById_Result_BAD_REQUEST() throws Exception { - String expectedPath = objectIdVer_19 + "/" + objectInstanceId_0; - String expectedValue = "{\"" + resourceId_0 + "\":{\"0\":\"00AC\"}, \"1\":1}"; + String expectedPath = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_0; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"0\":\"00AC\"}, \"1\":1}"; String actualResult = sendRPCreateById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); - String expected = "instance " + objectInstanceId_0 + " already exists"; + String expected = "instance " + OBJECT_INSTANCE_ID_0 + " already exists"; String actual = rpcActualResult.get("error").asText(); assertTrue(actual.equals(expected)); } @@ -77,8 +77,8 @@ public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testCreateObjectInstanceWithInstanceIdMandatorySingleObjectById_Result_BAD_REQUEST() throws Exception { - String expectedPath = objectIdVer_3 + "/" + objectInstanceId_1; - String expectedValue = "{\"" + resourceId_0 + "\":{\"0\":\"00AC\"}}"; + String expectedPath = objectIdVer_3 + "/" + OBJECT_INSTANCE_ID_1; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"0\":\"00AC\"}}"; String actualResult = sendRPCreateById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); @@ -94,8 +94,8 @@ public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testCreateObjectInstanceWithInstanceIdSecurityObjectById_Result_BAD_REQUEST() throws Exception { - String expectedPath = objectIdVer_0 + "/" + objectInstanceId_1; - String expectedValue = "{\"" + resourceId_0 + "\":{\"2\":4}}"; + String expectedPath = objectIdVer_0 + "/" + OBJECT_INSTANCE_ID_1; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"2\":4}}"; String actualResult = sendRPCreateById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); @@ -113,8 +113,8 @@ public class RpcLwm2mIntegrationCreateTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testCreateObjectInstanceWithInstanceIdAbsentObjectById_Result_BAD_REQUEST() throws Exception { - String expectedPath = objectIdVer_50+ "/" + objectInstanceId_1; - String expectedValue = "{\"" + resourceId_0 + "\":{\"0\":\"00AC\"}}"; + String expectedPath = OBJECT_ID_VER_50 + "/" + OBJECT_INSTANCE_ID_1; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"0\":\"00AC\"}}"; String actualResult = sendRPCreateById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDeleteTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDeleteTest.java index 6f24d7176c..df5255fed5 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDeleteTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDeleteTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,9 @@ import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTes import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_12; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_12; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_7; public class RpcLwm2mIntegrationDeleteTest extends AbstractRpcLwM2MIntegrationTest { @@ -38,7 +38,7 @@ public class RpcLwm2mIntegrationDeleteTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testDeleteObjectInstanceIsSuchByIdKey_Result_DELETED() throws Exception { - String expectedPath = objectIdVer_3303 + "/" + objectInstanceId_12; + String expectedPath = objectIdVer_3303 + "/" + OBJECT_INSTANCE_ID_12; String actualResult = sendRPCDeleteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.DELETED.getName(), rpcActualResult.get("result").asText()); @@ -51,7 +51,7 @@ public class RpcLwm2mIntegrationDeleteTest extends AbstractRpcLwM2MIntegrationTe */ @Test public void testDeleteObjectInstanceIsNotSuchByIdKey_Result_NOT_FOUND() throws Exception { - String expectedPath = objectIdVer_19 + "/" + objectInstanceId_12; + String expectedPath = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_12; String actualResult = sendRPCDeleteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.NOT_FOUND.getName(), rpcActualResult.get("result").asText()); @@ -76,12 +76,12 @@ public class RpcLwm2mIntegrationDeleteTest extends AbstractRpcLwM2MIntegrationTe /** * delete resource - * Delete {"id":"/3/0/9"} + * Delete {"id":"/3/0/7"} * {"result":"METHOD_NOT_ALLOWED"} */ @Test public void testDeleteResourceByIdKey_Result_METHOD_NOT_ALLOWED() throws Exception { - String expectedPath = objectIdVer_3 + "/" + objectInstanceId_0 + resourceId_9; + String expectedPath = objectIdVer_3 + "/" + OBJECT_INSTANCE_ID_0 + RESOURCE_ID_7; String actualResult = sendRPCDeleteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.METHOD_NOT_ALLOWED.getName(), rpcActualResult.get("result").asText()); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDiscoverTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDiscoverTest.java index b8ca7be61f..5fd3c09d06 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDiscoverTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationDiscoverTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_2; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_2; public class RpcLwm2mIntegrationDiscoverTest extends AbstractRpcLwM2MIntegrationTest { @@ -52,8 +52,8 @@ public class RpcLwm2mIntegrationDiscoverTest extends AbstractRpcLwM2MIntegration Set actualObjects = ConcurrentHashMap.newKeySet(); Set actualInstances = ConcurrentHashMap.newKeySet(); rpcActualValue.forEach(node -> { - if (!node.get("url").asText().equals("/")) { - LwM2mPath path = new LwM2mPath(node.get("url").asText()); + if (!node.get("uriReference").asText().equals("/")) { + LwM2mPath path = new LwM2mPath(node.get("uriReference").asText()); actualObjects.add("/" + path.getObjectId()); if (path.isObjectInstance()) { actualInstances.add("/" + path.getObjectId() + "/" + path.getObjectInstanceId()); @@ -124,7 +124,7 @@ public class RpcLwm2mIntegrationDiscoverTest extends AbstractRpcLwM2MIntegration String expectedInstance = (String) expectedInstances.stream().findFirst().get(); String expectedObjectInstanceId = pathIdVerToObjectId(expectedInstance); LwM2mPath expectedPath = new LwM2mPath(expectedObjectInstanceId); - int expectedResource = client.getClient().getObjectTree().getObjectEnablers().get(expectedPath.getObjectId()).getObjectModel().resources.entrySet().stream().findAny().get().getKey(); + int expectedResource = lwM2MTestClient.getLeshanClient().getObjectTree().getObjectEnablers().get(expectedPath.getObjectId()).getObjectModel().resources.entrySet().stream().findAny().get().getKey(); String expected = expectedInstance + "/" + expectedResource; String actualResult = sendDiscover(expected); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -141,7 +141,7 @@ public class RpcLwm2mIntegrationDiscoverTest extends AbstractRpcLwM2MIntegration */ @Test public void testDiscoverObjectInstanceAbsentInObject_Return_NOT_FOUND() throws Exception { - String expected = objectIdVer_2 + "/" + objectInstanceId_0; + String expected = objectIdVer_2 + "/" + OBJECT_INSTANCE_ID_0; String actualResult = sendDiscover(expected); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.NOT_FOUND.getName(), rpcActualResult.get("result").asText()); @@ -152,7 +152,7 @@ public class RpcLwm2mIntegrationDiscoverTest extends AbstractRpcLwM2MIntegration */ @Test public void testDiscoverResourceAbsentInObject_Return_NOT_FOUND() throws Exception { - String expected = objectIdVer_2 + "/" + objectInstanceId_0 + "/" + resourceId_2; + String expected = objectIdVer_2 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_2; String actualResult = sendDiscover(expected); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.NOT_FOUND.getName(), rpcActualResult.get("result").asText()); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationExecuteTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationExecuteTest.java index 73ea0fb74c..073a9fa8ed 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationExecuteTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationExecuteTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,12 +25,12 @@ import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTes import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_2; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_3; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_4; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_8; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_2; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_3; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_4; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_8; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_9; public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationTest { @@ -43,7 +43,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteUpdateFWById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_5 + "/" + resourceId_2; + String expectedPath = objectInstanceIdVer_5 + "/" + RESOURCE_ID_2; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); @@ -56,7 +56,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteUpdateSWById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_9 + "/" + resourceId_4; + String expectedPath = objectInstanceIdVer_9 + "/" + RESOURCE_ID_4; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); @@ -69,7 +69,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteRebootById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_3 + "/" + resourceId_4; + String expectedPath = objectInstanceIdVer_3 + "/" + RESOURCE_ID_4; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); @@ -82,7 +82,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteRegistrationUpdateTriggerById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_1 + "/" + resourceId_8; + String expectedPath = objectInstanceIdVer_1 + "/" + RESOURCE_ID_8; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); @@ -96,7 +96,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteResourceWithParametersById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_3 + "/" + resourceId_4; + String expectedPath = objectInstanceIdVer_3 + "/" + RESOURCE_ID_4; Object expectedValue = 60; String actualResult = sendRPCExecuteWithValueById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -110,7 +110,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteBootstrapRequestTriggerById_Result_BAD_REQUEST_Error_NoBootstrapServerConfigured() throws Exception { - String expectedPath = objectInstanceIdVer_1 + "/" + resourceId_9; + String expectedPath = objectInstanceIdVer_1 + "/" + RESOURCE_ID_9; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); @@ -121,17 +121,16 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT /** * bad: resource operation not "E" - * Execute {"id":"5/0/3"} - * {"result":"BAD_REQUEST","error":"Resource with /5/0/3 is not executable."} + * Execute {"id":"5_1.0/0/3"} + * {"result":"BAD_REQUEST","error":"Resource with /5_1.0/0/3 is not executable."} */ @Test public void testExecuteResourceWithOperationNotExecuteById_Result_METHOD_NOT_ALLOWED() throws Exception { - String expectedPath = objectInstanceIdVer_5 + "/" + resourceId_3; + String expectedPath = objectInstanceIdVer_5 + "/" + RESOURCE_ID_3; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); - String expectedObjectId = pathIdVerToObjectId((String) expectedPath); - String expected = "Resource with " + expectedObjectId + " is not executable."; + String expected = "Resource with " + expectedPath + " is not executable."; String actual = rpcActualResult.get("error").asText(); assertTrue(actual.equals(expected)); } @@ -143,7 +142,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteNonExistingResourceOnNonExistingObjectById_Result_BAD_REQUEST() throws Exception { - String expectedPath = objectIdVer_50 + "/" + objectInstanceId_0 + "/" + resourceId_3; + String expectedPath = OBJECT_ID_VER_50 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_3; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); @@ -161,7 +160,7 @@ public class RpcLwm2mIntegrationExecuteTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testExecuteSecurityObjectById_Result_NOT_FOUND() throws Exception { - String expectedPath = objectIdVer_0 + "/" + objectInstanceId_0 + "/" + resourceId_3; + String expectedPath = objectIdVer_0 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_3; String actualResult = sendRPCExecuteById(expectedPath); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationObserveTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationObserveTest.java index 848a9563ed..77d6e6cfab 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationObserveTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationObserveTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,11 @@ import static org.eclipse.leshan.core.LwM2mId.ACCESS_CONTROL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.BINARY_APP_DATA_CONTAINER; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_3; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_3; +import static org.thingsboard.server.transport.lwm2m.utils.LwM2MTransportUtil.fromVersionedIdToObjectId; public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationTest { @@ -40,23 +40,42 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testObserveReadAllNothingObservation_Result_CONTENT_Value_Count_0() throws Exception { + String actualResultBefore = sendObserve("ObserveReadAll", null); + ObjectNode rpcActualResultBefore = JacksonUtil.fromString(actualResultBefore, ObjectNode.class); + assertEquals(ResponseCode.CONTENT.getName(), rpcActualResultBefore.get("result").asText()); + assertTrue(rpcActualResultBefore.get("value").asText().contains(fromVersionedIdToObjectId(idVer_3_0_9))); + assertTrue(rpcActualResultBefore.get("value").asText().contains(fromVersionedIdToObjectId(idVer_19_0_0))); String actualResult = sendObserve("ObserveCancelAll", null); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); - actualResult = sendObserve("ObserveReadAll", null); - rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); - assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); - assertEquals("[]", rpcActualResult.get("value").asText()); + assertEquals("2", rpcActualResult.get("value").asText()); + String actualResultAfter = sendObserve("ObserveReadAll", null); + ObjectNode rpcActualResultAfter = JacksonUtil.fromString(actualResultAfter, ObjectNode.class); + assertEquals(ResponseCode.CONTENT.getName(), rpcActualResultAfter.get("result").asText()); + String expectResultAfter = "[]"; + assertEquals( expectResultAfter, rpcActualResultAfter.get("value").asText()); } /** - * Observe {"id":"/3/0/9"} + * Observe {"id":"/3/0/0"} * @throws Exception */ @Test - public void testObserveSingleResource_Result_CONTENT_Value_SingleResource() throws Exception { - String expectedIdVer = objectInstanceIdVer_3 + "/" + resourceId_9; - String actualResult = sendObserve("Observe", expectedIdVer); + public void testObserveSingleResourceWithout_IdVer_1_0_Result_CONTENT_Value_SingleResource() throws Exception { + String expectedId = objectInstanceIdVer_3 + "/" + RESOURCE_ID_0; + String actualResult = sendObserve("Observe", fromVersionedIdToObjectId(expectedId)); + ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); + assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); + assertTrue(rpcActualResult.get("value").asText().contains("LwM2mSingleResource")); + } + /** + * Observe {"id":"/3_1.0/0/14"} + * @throws Exception + */ + @Test + public void testObserveSingleResourceWith_IdVer_1_0_Result_CONTENT_Value_SingleResource() throws Exception { + String expectedId = objectInstanceIdVer_3 + "/" + RESOURCE_ID_14; + String actualResult = sendObserve("Observe", expectedId); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); assertTrue(rpcActualResult.get("value").asText().contains("LwM2mSingleResource")); @@ -70,7 +89,7 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT public void testObserveWithBadVersion_Result_BadRequest_ErrorMsg_BadVersionMustBe1_0() throws Exception { String expectedInstance = (String) expectedInstances.stream().filter(path -> !((String)path).contains("_")).findFirst().get(); LwM2mPath expectedPath = new LwM2mPath(expectedInstance); - int expectedResource = client.getClient().getObjectTree().getObjectEnablers().get(expectedPath.getObjectId()).getObjectModel().resources.entrySet().stream().findAny().get().getKey(); + int expectedResource = lwM2MTestClient.getLeshanClient().getObjectTree().getObjectEnablers().get(expectedPath.getObjectId()).getObjectModel().resources.entrySet().stream().findAny().get().getKey(); String expectedId = "/" + expectedPath.getObjectId() + "_1.2" + "/" + expectedPath.getObjectInstanceId() + "/" + expectedResource; String actualResult = sendObserve("Observe", expectedId); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -87,7 +106,7 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT @Test public void testObserveNoImplementedInstanceOnDevice_Result_NotFound() throws Exception { String objectInstanceIdVer = (String) expectedObjectIdVers.stream().filter(path -> ((String)path).contains("/" + ACCESS_CONTROL)).findFirst().get(); - String expected = objectInstanceIdVer + "/" + objectInstanceId_0; + String expected = objectInstanceIdVer + "/" + OBJECT_INSTANCE_ID_0; String actualResult = sendObserve("Observe", expected); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.NOT_FOUND.getName(), rpcActualResult.get("result").asText()); @@ -100,11 +119,10 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testObserveNoImplementedResourceOnDeviceValueNull_Result_BadRequest() throws Exception { - String objectIdVer = (String) expectedObjectIdVers.stream().filter(path -> ((String)path).contains("/" + BINARY_APP_DATA_CONTAINER)).findFirst().get(); - String expected = objectIdVer + "/" + objectInstanceId_0 + "/" + resourceId_0; + String expected = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_3; String actualResult = sendObserve("Observe", expected); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); - String expectedValue = "values MUST NOT be null"; + String expectedValue = "value MUST NOT be null"; assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); assertEquals(expectedValue, rpcActualResult.get("error").asText()); } @@ -116,7 +134,7 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT */ @Test public void testObserveRSourceNotRead_Result_METHOD_NOT_ALLOWED() throws Exception { - String expectedId = objectInstanceIdVer_5 + "/" + resourceId_0; + String expectedId = objectInstanceIdVer_5 + "/" + RESOURCE_ID_0; sendObserve("Observe", expectedId); String actualResult = sendObserve("Observe", expectedId); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -125,14 +143,12 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT /** * Repeated request on Observe - * Observe {"id":"/3/0/0"} + * Observe {"id":"/3/0/9"} * @throws Exception */ @Test public void testObserveRepeatedRequestObserveOnDevice_Result_BAD_REQUEST_ErrorMsg_AlreadyRegistered() throws Exception { - String expectedId = objectInstanceIdVer_3 + "/" + resourceId_0; - sendObserve("Observe", expectedId); - String actualResult = sendObserve("Observe", expectedId); + String actualResult = sendObserve("Observe", idVer_3_0_9); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); String expected = "Observation is already registered!"; @@ -144,18 +160,18 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT * @throws Exception */ @Test - public void testObserveReadAll_Result_CONTENT_Value_Contains_Paths_Count_ObserveAll() throws Exception { - sendObserve("ObserveCancelAll", null); - String expectedId_0 = objectInstanceIdVer_3 + "/" + resourceId_0; - String expectedId_9 = objectInstanceIdVer_3 + "/" + resourceId_9; - sendObserve("Observe", expectedId_0); - sendObserve("Observe", expectedId_9); + public void testObserveReadAll_Result_CONTENT_Value_Contains_Paths_Count_ObserveReadAll() throws Exception { + String actualResultCancel = sendObserve("ObserveCancelAll", null); + ObjectNode rpcActualResultCancel = JacksonUtil.fromString(actualResultCancel, ObjectNode.class); + assertEquals(ResponseCode.CONTENT.getName(), rpcActualResultCancel.get("result").asText()); + sendObserve("Observe",idVer_19_0_0); + sendObserve("Observe", idVer_3_0_9); String actualResult = sendObserve("ObserveReadAll", null); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); String actualValues = rpcActualResult.get("value").asText(); - assertTrue(actualValues.contains(expectedId_0)); - assertTrue(actualValues.contains(expectedId_9)); + assertTrue(actualValues.contains(fromVersionedIdToObjectId(idVer_19_0_0))); + assertTrue(actualValues.contains(fromVersionedIdToObjectId(idVer_3_0_9))); assertEquals(2, actualValues.split(",").length); } @@ -167,11 +183,11 @@ public class RpcLwm2mIntegrationObserveTest extends AbstractRpcLwM2MIntegrationT @Test public void testObserveCancelOneResource_Result_CONTENT_Value_Count_1() throws Exception { sendObserve("ObserveCancelAll", null); - String expectedId_0 = objectInstanceIdVer_3 + "/" + resourceId_0; - String expectedId_3 = objectInstanceIdVer_5 + "/" + resourceId_3; - sendObserve("Observe", expectedId_0); - sendObserve("Observe", expectedId_3); - String actualResult = sendObserve("ObserveCancel", expectedId_0); + String expectedId_3_0_3 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_3; + String expectedId_5_0_3 = objectInstanceIdVer_5 + "/" + RESOURCE_ID_3; + sendObserve("Observe", expectedId_3_0_3); + sendObserve("Observe", expectedId_5_0_3); + String actualResult = sendObserve("ObserveCancel", expectedId_3_0_3); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); assertEquals("1", rpcActualResult.get("value").asText()); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationReadTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationReadTest.java index 9116659bc3..404bbdc545 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationReadTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationReadTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,18 +27,19 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.BINARY_APP_DATA_CONTAINER; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_19_0_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_19_1_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_3_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_3_9; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_11; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_2; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_19_0_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_19_0_3; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_19_1_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_3_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_3_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_11; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_2; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_9; public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest { @@ -96,11 +97,11 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest */ @Test public void testReadMultipleResourceById_Result_CONTENT_Value_IsLwM2mMultipleResource() throws Exception { - String expectedIdVer = objectInstanceIdVer_3 +"/" + resourceId_11 ; + String expectedIdVer = objectInstanceIdVer_3 +"/" + RESOURCE_ID_11; String actualResult = sendRPCById(expectedIdVer); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); - String expected = "LwM2mMultipleResource [id=" + resourceId_11 + ", values={"; + String expected = "LwM2mMultipleResource [id=" + RESOURCE_ID_11 + ", values={"; assertTrue(rpcActualResult.get("value").asText().contains(expected)); } @@ -109,11 +110,11 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest */ @Test public void testReadSingleResourceById_Result_CONTENT_Value_IsLwM2mSingleResource() throws Exception { - String expectedIdVer = objectInstanceIdVer_3 +"/" + resourceId_14 ; + String expectedIdVer = objectInstanceIdVer_3 +"/" + RESOURCE_ID_14; String actualResult = sendRPCById(expectedIdVer); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); - String expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value="; + String expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value="; assertTrue(rpcActualResult.get("value").asText().contains(expected)); } @@ -122,11 +123,11 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest */ @Test public void testReadSingleResourceByKey_Result_CONTENT_Value_IsLwM2mSingleResource() throws Exception { - String expectedKey = resourceIdName_3_14 ; + String expectedKey = RESOURCE_ID_NAME_3_14; String actualResult = sendRPCByKey(expectedKey); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); - String expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value="; + String expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value="; assertTrue(rpcActualResult.get("value").asText().contains(expected)); } @@ -137,16 +138,16 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest public void testReadCompositeSingleResourceByIds_Result_CONTENT_Value_IsObjectIsLwM2mSingleResourceIsLwM2mMultipleResource() throws Exception { String expectedIdVer_1 = (String) expectedObjectIdVers.stream().filter(path -> (!((String)path).contains("/" + BINARY_APP_DATA_CONTAINER) && ((String)path).contains("/" + SERVER))).findFirst().get(); String objectId_1 = pathIdVerToObjectId(expectedIdVer_1); - String expectedIdVer3_0_1 = objectInstanceIdVer_3 + "/" + resourceId_1; - String expectedIdVer3_0_11 = objectInstanceIdVer_3 + "/" + resourceId_11; + String expectedIdVer3_0_1 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_1; + String expectedIdVer3_0_11 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_11; String objectInstanceId_3 = pathIdVerToObjectId(objectInstanceIdVer_3); String expectedIds = "[\"" + expectedIdVer_1 + "\", \"" + expectedIdVer3_0_1 + "\", \"" + expectedIdVer3_0_11 + "\"]"; String actualResult = sendCompositeRPCByIds(expectedIds); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); String expected1 = objectId_1 + "=LwM2mObject [id=" + new LwM2mPath(objectId_1).getObjectId() + ", instances={"; - String expected3_0_1 = objectInstanceId_3 + "/" + resourceId_1 + "=LwM2mSingleResource [id=" + resourceId_1 + ", value="; - String expected3_0_11 = objectInstanceId_3 + "/" + resourceId_11 + "=LwM2mMultipleResource [id=" + resourceId_11 + ", values={"; + String expected3_0_1 = objectInstanceId_3 + "/" + RESOURCE_ID_1 + "=LwM2mSingleResource [id=" + RESOURCE_ID_1 + ", value="; + String expected3_0_11 = objectInstanceId_3 + "/" + RESOURCE_ID_11 + "=LwM2mMultipleResource [id=" + RESOURCE_ID_11 + ", values={"; String actualValues = rpcActualResult.get("value").asText(); assertTrue(actualValues.contains(expected1)); assertTrue(actualValues.contains(expected3_0_1)); @@ -159,8 +160,8 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest @Test public void testReadCompositeSingleResourceByIds_Result_CONTENT_Value_IsObjectInstanceIsLwM2mSingleResource() throws Exception { String expectedIdVer3_0 = objectInstanceIdVer_3; - String expectedIdVer1_0_1 = objectInstanceIdVer_1 + "/" + resourceId_1; - String expectedIdVer1_0_2 = objectInstanceIdVer_1 + "/" + resourceId_2; + String expectedIdVer1_0_1 = objectInstanceIdVer_1 + "/" + RESOURCE_ID_1; + String expectedIdVer1_0_2 = objectInstanceIdVer_1 + "/" + RESOURCE_ID_2; String expectedIds = "[\"" + expectedIdVer1_0_1 + "\", \"" + expectedIdVer1_0_2 + "\", \"" + expectedIdVer3_0 + "\"]"; String actualResult = sendCompositeRPCByIds(expectedIds); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -169,8 +170,8 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest LwM2mPath path = new LwM2mPath(objectInstanceId_3); String expected3_0 = objectInstanceId_3 + "=LwM2mObjectInstance [id=" + path.getObjectInstanceId() + ", resources={"; String objectInstanceId_1 = pathIdVerToObjectId(objectInstanceIdVer_1); - String expected1_0_1 = objectInstanceId_1 + "/" + resourceId_1 + "=LwM2mSingleResource [id=" + resourceId_1 + ", value="; - String expected1_0_2 = objectInstanceId_1 + "/" + resourceId_2 + "=null"; + String expected1_0_1 = objectInstanceId_1 + "/" + RESOURCE_ID_1 + "=LwM2mSingleResource [id=" + RESOURCE_ID_1 + ", value="; + String expected1_0_2 = objectInstanceId_1 + "/" + RESOURCE_ID_2 + "=null"; String actualValues = rpcActualResult.get("value").asText(); assertTrue(actualValues.contains(expected3_0)); assertTrue(actualValues.contains(expected1_0_1)); @@ -181,21 +182,22 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest * ReadComposite {"keys":["batteryLevel", "UtfOffset", "dataRead", "dataWrite"]} */ @Test - public void testReadCompositeSingleResourceByKeys_Result_CONTENT_Value_3_0_IsLwM2mSingleResource_19_0_0_AND_19_0_1_Null() throws Exception { - String expectedKey3_0_9 = resourceIdName_3_9; - String expectedKey3_0_14 = resourceIdName_3_14; - String expectedKey19_0_0 = resourceIdName_19_0_0; - String expectedKey19_1_0 = resourceIdName_19_1_0; + public void testReadCompositeSingleResourceByKeys_Result_CONTENT_Value_3_0_IsLwM2mSingleResource_19_0_0_AND_19_0_1__IsLwM2mMultipleResource() throws Exception { + String expectedKey3_0_9 = RESOURCE_ID_NAME_3_9; + String expectedKey3_0_14 = RESOURCE_ID_NAME_3_14; + String expectedKey19_0_0 = RESOURCE_ID_NAME_19_0_0; + String expectedKey19_1_0 = RESOURCE_ID_NAME_19_1_0; + String expectedKey19_X_0 = "=LwM2mMultipleResource [id=0, values={0=LwM2mResourceInstance [id=0, value=1Bytes, type=OPAQUE]"; String expectedKeys = "[\"" + expectedKey3_0_9 + "\", \"" + expectedKey3_0_14 + "\", \"" + expectedKey19_0_0 + "\", \"" + expectedKey19_1_0 + "\"]"; String actualResult = sendCompositeRPCByKeys(expectedKeys); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CONTENT.getName(), rpcActualResult.get("result").asText()); String objectInstanceId_3 = pathIdVerToObjectId(objectInstanceIdVer_3); String objectId_19 = pathIdVerToObjectId(objectIdVer_19); - String expected3_0_9 = objectInstanceId_3 + "/" + resourceId_9 + "=LwM2mSingleResource [id=" + resourceId_9 + ", value="; - String expected3_0_14 = objectInstanceId_3 + "/" + resourceId_14 + "=LwM2mSingleResource [id=" + resourceId_14 + ", value="; - String expected19_0_0 = objectId_19 + "/" + objectInstanceId_0 + "/" + resourceId_0 + "=null"; - String expected19_1_0 = objectId_19 + "/" + objectInstanceId_1 + "/" + resourceId_0 + "=null"; + String expected3_0_9 = objectInstanceId_3 + "/" + RESOURCE_ID_9 + "=LwM2mSingleResource [id=" + RESOURCE_ID_9 + ", value="; + String expected3_0_14 = objectInstanceId_3 + "/" + RESOURCE_ID_14 + "=LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value="; + String expected19_0_0 = objectId_19 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_0 + expectedKey19_X_0; + String expected19_1_0 = objectId_19 + "/" + OBJECT_INSTANCE_ID_1 + "/" + RESOURCE_ID_0 + expectedKey19_X_0; String actualValues = rpcActualResult.get("value").asText(); assertTrue(actualValues.contains(expected3_0_9)); assertTrue(actualValues.contains(expected3_0_14)); @@ -203,6 +205,23 @@ public class RpcLwm2mIntegrationReadTest extends AbstractRpcLwM2MIntegrationTest assertTrue(actualValues.contains(expected19_1_0)); } + /** + * ReadComposite {"keys":["batteryLevel", "UtfOffset", "dataDescription"]} + */ + @Test + public void testReadCompositeSingleResourceByKeys_Result_CONTENT_Value_3_0_IsLwM2mSingleResource_19_0_3_IsNotConfiguredInTheDeviceProfile() throws Exception { + String expectedKey3_0_9 = RESOURCE_ID_NAME_3_9; + String expectedKey3_0_14 = RESOURCE_ID_NAME_3_14; + String expectedKey19_0_3 = RESOURCE_ID_NAME_19_0_3; + String expectedKeys = "[\"" + expectedKey3_0_9 + "\", \"" + expectedKey3_0_14 + "\", \"" + expectedKey19_0_3 + "\"]"; + String actualResult = sendCompositeRPCByKeys(expectedKeys); + ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); + assertEquals(ResponseCode.BAD_REQUEST.getName(), rpcActualResult.get("result").asText()); + String actualValue = rpcActualResult.get("error").asText(); + String expectedValue = expectedKey19_0_3 + " is not configured in the device profile!"; + assertEquals(actualValue, expectedValue); + } + private String sendRPCById(String path) throws Exception { String setRpcRequest = "{\"method\": \"Read\", \"params\": {\"id\": \"" + path + "\"}}"; diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteAttributesTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteAttributesTest.java index ea23ab48b9..3bcc8bb63e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteAttributesTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteAttributesTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.thingsboard.server.transport.lwm2m.rpc.sql; import com.fasterxml.jackson.databind.node.ObjectNode; import org.eclipse.leshan.core.ResponseCode; -import org.eclipse.leshan.core.node.LwM2mPath; import org.junit.Test; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTest; @@ -25,13 +24,7 @@ import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTes import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_2; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_3; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_4; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_8; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_14; public class RpcLwm2mIntegrationWriteAttributesTest extends AbstractRpcLwM2MIntegrationTest { @@ -45,7 +38,7 @@ public class RpcLwm2mIntegrationWriteAttributesTest extends AbstractRpcLwM2MInte */ @Test public void testWriteAttributesResourceWithParametersById_Result_INTERNAL_SERVER_ERROR() throws Exception { - String expectedPath = objectInstanceIdVer_3 + "/" + resourceId_14; + String expectedPath = objectInstanceIdVer_3 + "/" + RESOURCE_ID_14; String expectedValue = "{\"pmax\":100, \"pmin\":10}"; String actualResult = sendRPCExecuteWithValueById(expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteTest.java index 1a92831a36..25bdcf74dc 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/rpc/sql/RpcLwm2mIntegrationWriteTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,16 +25,15 @@ import org.thingsboard.server.transport.lwm2m.rpc.AbstractRpcLwM2MIntegrationTes import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.BINARY_APP_DATA_CONTAINER; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_1; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.objectInstanceId_2; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceIdName_3_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_0; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_14; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_15; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceId_9; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.resourceInstanceId_2; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_INSTANCE_ID_2; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_NAME_3_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_0; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_14; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_15; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_9; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_INSTANCE_ID_2; public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTest { @@ -46,7 +45,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteReplaceValueSingleResourceById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_3 + "/" + resourceId_14; + String expectedPath = objectInstanceIdVer_3 + "/" + RESOURCE_ID_14; String expectedValue = "+12"; String actualResult = sendRPCWriteStringById("WriteReplace", expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -54,7 +53,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes actualResult = sendRPCReadById(expectedPath); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); String actualValues = rpcActualResult.get("value").asText(); - String expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value=" + expectedValue + ", type=STRING]"; + String expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value=" + expectedValue + ", type=STRING]"; assertTrue(actualValues.contains(expected)); } @@ -65,7 +64,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteReplaceValueSingleResourceByKey_Result_CHANGED() throws Exception { - String expectedKey = resourceIdName_3_14; + String expectedKey = RESOURCE_ID_NAME_3_14; String expectedValue = "+09"; String actualResult = sendRPCWriteByKey("WriteReplace", expectedKey, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -73,7 +72,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes actualResult = sendRPCReadByKey(expectedKey); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); String actualValues = rpcActualResult.get("value").asText(); - String expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value=" + expectedValue + ", type=STRING]"; + String expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value=" + expectedValue + ", type=STRING]"; assertTrue(actualValues.contains(expected)); } @@ -85,7 +84,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteReplaceValueMultipleResource_Result_CHANGED_Value_Multi_Instance_Resource_must_in_Json_format() throws Exception { - String expectedPath = objectIdVer_19 + "/" + objectInstanceId_0 + "/" + resourceId_0; + String expectedPath = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_0 + "/" + RESOURCE_ID_0; int resourceInstanceId0 = 0; int resourceInstanceId15 = 15; String expectedValue0 = "0000ad45675600"; @@ -115,7 +114,7 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteReplaceValueSingleResourceR_ById_Result_CHANGED() throws Exception { - String expectedPath = objectInstanceIdVer_3 + "/" + resourceId_9; + String expectedPath = objectInstanceIdVer_3 + "/" + RESOURCE_ID_9; Integer expectedValue = 90; String actualResult = sendRPCWriteObjectById("WriteReplace", expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); @@ -132,21 +131,21 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes String expectedPath = objectInstanceIdVer_3; String expectedValue14 = "+5"; String expectedValue15 = "Kiyv/Europe"; - String expectedValue = "{\"" + resourceId_14 + "\":\"" + expectedValue14 + "\",\"" + resourceId_15 + "\":\"" + expectedValue15 + "\"}"; + String expectedValue = "{\"" + RESOURCE_ID_14 + "\":\"" + expectedValue14 + "\",\"" + RESOURCE_ID_15 + "\":\"" + expectedValue15 + "\"}"; String actualResult = sendRPCWriteObjectById("WriteUpdate", expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); - String expectedPath14 = objectInstanceIdVer_3 + "/" + resourceId_14; - String expectedPath15 = objectInstanceIdVer_3 + "/" + resourceId_15; + String expectedPath14 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_14; + String expectedPath15 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_15; actualResult = sendRPCReadById(expectedPath14); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); String actualValues = rpcActualResult.get("value").asText(); - String expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value=" + expectedValue14 + ", type=STRING]"; + String expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value=" + expectedValue14 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); actualResult = sendRPCReadById(expectedPath15); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); actualValues = rpcActualResult.get("value").asText(); - expected = "LwM2mSingleResource [id=" + resourceId_15 + ", value=" + expectedValue15 + ", type=STRING]"; + expected = "LwM2mSingleResource [id=" + RESOURCE_ID_15 + ", value=" + expectedValue15 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); } @@ -157,17 +156,17 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteUpdateValueMultipleResourceById_Result_CHANGED() throws Exception { - String expectedPath = objectIdVer_19 + "/" + objectInstanceId_0; + String expectedPath = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_0; int resourceInstanceId0 = 0; int resourceInstanceId25 = 25; String expectedValue0 = "00ad45675600"; String expectedValue25 = "25ad45675600cdef"; - String expectedValue = "{\"" + resourceId_0 + "\":{\"" + resourceInstanceId0 + "\":\"" + expectedValue0 + "\", \"" + resourceInstanceId25 + "\":\"" + expectedValue25 + "\"}}"; + String expectedValue = "{\"" + RESOURCE_ID_0 + "\":{\"" + resourceInstanceId0 + "\":\"" + expectedValue0 + "\", \"" + resourceInstanceId25 + "\":\"" + expectedValue25 + "\"}}"; String actualResult = sendRPCWriteObjectById("WriteUpdate", expectedPath, expectedValue); ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); - String expectedPath0 = expectedPath + "/" + resourceId_0 + "/" + resourceInstanceId0; - String expectedPath25 =expectedPath + "/" + resourceId_0 + "/" + resourceInstanceId25; + String expectedPath0 = expectedPath + "/" + RESOURCE_ID_0 + "/" + resourceInstanceId0; + String expectedPath25 =expectedPath + "/" + RESOURCE_ID_0 + "/" + resourceInstanceId25; actualResult = sendRPCReadById(expectedPath0); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); String actualValues = rpcActualResult.get("value").asText(); @@ -188,11 +187,11 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes @Test public void testWriteCompositeValueSingleResourceResourceInstanceByIdKey_Result_CHANGED() throws Exception { int resourceInstanceId2 = 2; - String expectedPath19_1_0_2 = objectIdVer_19 + "/" + objectInstanceId_1 + "/" + resourceId_0 + "/" + resourceInstanceId2; + String expectedPath19_1_0_2 = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_1 + "/" + RESOURCE_ID_0 + "/" + resourceInstanceId2; String expectedValue19_1_0_2 = "00001234"; - String expectedKey3_0_14 = resourceIdName_3_14; + String expectedKey3_0_14 = RESOURCE_ID_NAME_3_14; String expectedValue3_0_14 = "+04"; - String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + resourceId_15; + String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_15; String expectedValue3_0_15 = "Kiyv/Europe"; String nodes = "{\"" + expectedPath19_1_0_2 + "\":\"" + expectedValue19_1_0_2 + "\", \"" + expectedKey3_0_14 + "\":\"" + expectedValue3_0_14 + "\", \"" + expectedPath3_0_15 + "\":\"" + expectedValue3_0_15 + "\"}"; @@ -207,12 +206,12 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes actualResult = sendRPCReadByKey(expectedKey3_0_14); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); actualValues = rpcActualResult.get("value").asText(); - expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value=" + expectedValue3_0_14 + ", type=STRING]"; + expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value=" + expectedValue3_0_14 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); actualResult = sendRPCReadById(expectedPath3_0_15); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); actualValues = rpcActualResult.get("value").asText(); - expected = "LwM2mSingleResource [id=" + resourceId_15 + ", value=" + expectedValue3_0_15 + ", type=STRING]"; + expected = "LwM2mSingleResource [id=" + RESOURCE_ID_15 + ", value=" + expectedValue3_0_15 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); } @@ -246,11 +245,11 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteCompositeCreateResourceInstanceUpdateSingleResourceByIdKey_Result_CHANGED() throws Exception { - String expectedPath19_1_0_2 = objectIdVer_19 + "/" + objectInstanceId_1 + "/" + resourceId_0 + "/" + resourceInstanceId_2; + String expectedPath19_1_0_2 = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_1 + "/" + RESOURCE_ID_0 + "/" + RESOURCE_INSTANCE_ID_2; String expectedValue19_1_0_2 = "00001234"; - String expectedKey3_0_14 = resourceIdName_3_14; + String expectedKey3_0_14 = RESOURCE_ID_NAME_3_14; String expectedValue3_0_14 = "+04"; - String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + resourceId_15; + String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_15; String expectedValue3_0_15 = "Kiyv/Europe"; String nodes = "{\"" + expectedPath19_1_0_2 + "\":\"" + expectedValue19_1_0_2 + "\", \"" + expectedKey3_0_14 + "\":\"" + expectedValue3_0_14 + "\", \"" + expectedPath3_0_15 + "\":\"" + expectedValue3_0_15 + "\"}"; @@ -260,17 +259,17 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes actualResult = sendRPCReadById(expectedPath19_1_0_2); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); String actualValues = rpcActualResult.get("value").asText(); - String expected = "LwM2mResourceInstance [id=" + resourceInstanceId_2 + ", value=" + expectedValue19_1_0_2.length()/2 + "Bytes, type=OPAQUE]"; + String expected = "LwM2mResourceInstance [id=" + RESOURCE_INSTANCE_ID_2 + ", value=" + expectedValue19_1_0_2.length()/2 + "Bytes, type=OPAQUE]"; assertTrue(actualValues.contains(expected)); actualResult = sendRPCReadByKey(expectedKey3_0_14); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); actualValues = rpcActualResult.get("value").asText(); - expected = "LwM2mSingleResource [id=" + resourceId_14 + ", value=" + expectedValue3_0_14 + ", type=STRING]"; + expected = "LwM2mSingleResource [id=" + RESOURCE_ID_14 + ", value=" + expectedValue3_0_14 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); actualResult = sendRPCReadById(expectedPath3_0_15); rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); actualValues = rpcActualResult.get("value").asText(); - expected = "LwM2mSingleResource [id=" + resourceId_15 + ", value=" + expectedValue3_0_15 + ", type=STRING]"; + expected = "LwM2mSingleResource [id=" + RESOURCE_ID_15 + ", value=" + expectedValue3_0_15 + ", type=STRING]"; assertTrue(actualValues.contains(expected)); } @@ -285,11 +284,11 @@ public class RpcLwm2mIntegrationWriteTest extends AbstractRpcLwM2MIntegrationTes */ @Test public void testWriteCompositeCreateObjectInstanceUpdateSingleResourceByIdKey_Result_BAD_REQUEST() throws Exception { - String expectedPath19_1_2_2 = objectIdVer_19 + "/" + objectInstanceId_2 + "/" + resourceId_0 + "/" + resourceInstanceId_2; + String expectedPath19_1_2_2 = objectIdVer_19 + "/" + OBJECT_INSTANCE_ID_2 + "/" + RESOURCE_ID_0 + "/" + RESOURCE_INSTANCE_ID_2; String expectedValue19_1_0_2 = "00001234"; - String expectedKey3_0_14 = resourceIdName_3_14; + String expectedKey3_0_14 = RESOURCE_ID_NAME_3_14; String expectedValue3_0_14 = "+04"; - String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + resourceId_15; + String expectedPath3_0_15 = objectInstanceIdVer_3 + "/" + RESOURCE_ID_15; String expectedValue3_0_15 = "Kiyv/Europe"; String nodes = "{\"" + expectedPath19_1_2_2 + "\":\"" + expectedValue19_1_0_2 + "\", \"" + expectedKey3_0_14 + "\":\"" + expectedValue3_0_14 + "\", \"" + expectedPath3_0_15 + "\":\"" + expectedValue3_0_15 + "\"}"; diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java index ea30b43436..e357b23afe 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/AbstractSecurityLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,153 +15,140 @@ */ package org.thingsboard.server.transport.lwm2m.security; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.codec.binary.Base64; +import org.eclipse.californium.elements.config.Configuration; +import org.eclipse.leshan.client.object.Security; +import org.eclipse.leshan.core.ResponseCode; import org.eclipse.leshan.core.util.Hex; +import org.junit.Assert; +import org.springframework.test.web.servlet.MvcResult; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MBootstrapClientCredentials; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode; import org.thingsboard.server.common.data.device.credentials.lwm2m.NoSecBootstrapClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.PSKBootstrapClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.PSKClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.RPKBootstrapClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.X509BootstrapClientCredential; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.AbstractLwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.LwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.PSKLwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.RPKLwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.device.profile.lwm2m.bootstrap.X509LwM2MBootstrapServerCredential; +import org.thingsboard.server.common.data.security.DeviceCredentials; +import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.lwm2m.AbstractLwM2MIntegrationTest; -import org.thingsboard.server.transport.lwm2m.client.LwM2MTestClient; +import org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState; +import org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType; import java.io.IOException; import java.io.InputStream; -import java.math.BigInteger; -import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; -import java.security.KeyFactory; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; -import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; -import java.security.spec.ECGenParameterSpec; -import java.security.spec.ECParameterSpec; -import java.security.spec.ECPoint; -import java.security.spec.ECPrivateKeySpec; -import java.security.spec.ECPublicKeySpec; -import java.security.spec.KeySpec; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.eclipse.leshan.client.object.Security.noSecBootstap; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_STARTED; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_DEREGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.OBJECT_ID_1; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.RESOURCE_ID_9; @DaoSqlTest +@Slf4j public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2MIntegrationTest { - protected final String pskIdentity; // client public key or id used for PSK - protected final String pskKey; // client private/secret key used for PSK - protected final PublicKey clientPublicKey; // client public key used for RPK - protected final PrivateKey clientPrivateKey; // client private key used for RPK - protected final PublicKey serverPublicKey; // server public key used for RPK - protected final PrivateKey serverPrivateKey; // server private key used for RPK - - // client private key used for X509 - protected final PrivateKey clientPrivateKeyFromCert; - // server private key used for X509 - protected final PrivateKey serverPrivateKeyFromCert; - // client certificate signed by rootCA with a good CN (CN start by leshan_integration_test) - protected final X509Certificate clientX509Cert; - // client certificate signed by rootCA but with bad CN (CN does not start by leshan_integration_test) - protected final X509Certificate clientX509CertWithBadCN; - // client certificate self-signed with a good CN (CN start by leshan_integration_test) - protected final X509Certificate clientX509CertSelfSigned; - // client certificate signed by another CA (not rootCA) with a good CN (CN start by leshan_integration_test) - protected final X509Certificate clientX509CertNotTrusted; - // server certificate signed by rootCA - protected final X509Certificate serverX509Cert; - // self-signed server certificate - protected final X509Certificate serverX509CertSelfSigned; - // rootCA used by the server - protected final X509Certificate rootCAX509Cert; - // certificates trustedby the server (should contain rootCA) - protected final Certificate[] trustedCertificates = new Certificate[1]; - - protected static final String ENDPOINT = "deviceAEndpoint"; - - protected LwM2MTestClient client; + protected final String CREDENTIALS_PATH = "lwm2m/credentials/"; // client public key or id used for PSK + // Get keys PSK + protected final String CLIENT_PSK_IDENTITY = "SOME_PSK_ID"; // client public key or id used for PSK + protected final String CLIENT_PSK_IDENTITY_BS = "SOME_PSK_ID_BS"; // client public key or id used for PSK + protected final String CLIENT_PSK_KEY = "73656372657450534b73656372657450"; // client private/secret key used for PSK + + // Server + protected static final String SERVER_JKS_FOR_TEST = "lwm2mserver"; + protected static final String SERVER_STORE_PWD = "server_ks_password"; + protected static final String SERVER_CERT_ALIAS = "server"; + protected static final String SERVER_CERT_ALIAS_BS = "bootstrap"; + protected final X509Certificate serverX509Cert; // server certificate signed by rootCA + protected final X509Certificate serverX509CertBs; // serverBs certificate signed by rootCA + protected final PublicKey serverPublicKeyFromCert; // server public key used for RPK + protected final PublicKey serverPublicKeyFromCertBs; // serverBs public key used for RPK + + // Client + protected static final String CLIENT_ENDPOINT_NO_SEC = "LwNoSec00000000"; + protected static final String CLIENT_ENDPOINT_NO_SEC_BS = "LwNoSecBs00000000"; + protected static final String CLIENT_ENDPOINT_PSK = "LwPsk00000000"; + protected static final String CLIENT_ENDPOINT_PSK_BS = "LwPskBs00000000"; + protected static final String CLIENT_ENDPOINT_RPK = "LwRpk00000000"; + protected static final String CLIENT_ENDPOINT_RPK_BS = "LwRpkBs00000000"; + protected static final String CLIENT_ENDPOINT_X509_TRUST = "LwX50900000000"; + protected static final String CLIENT_ENDPOINT_X509_TRUST_NO = "LwX509TrustNo"; + protected static final String CLIENT_JKS_FOR_TEST = "lwm2mclient"; + protected static final String CLIENT_STORE_PWD = "client_ks_password"; + protected static final String CLIENT_ALIAS_CERT_TRUST = "client_alias_00000000"; + protected static final String CLIENT_ALIAS_CERT_TRUST_NO = "client_alias_trust_no"; + + protected final X509Certificate clientX509CertTrust; // client certificate signed by intermediate, rootCA with a good CN ("host name") + protected final PrivateKey clientPrivateKeyFromCertTrust; // client private key used for X509 and RPK + protected final X509Certificate clientX509CertTrustNo; // client certificate signed by intermediate, rootCA with a good CN ("host name") + protected final PrivateKey clientPrivateKeyFromCertTrustNo; // client private key used for X509 and RPK + private final String[] RESOURCES_SECURITY = new String[]{"1.xml", "2.xml", "3.xml", "5.xml", "9.xml"}; + private final LwM2MBootstrapClientCredentials defaultBootstrapCredentials; - private final String[] resources = new String[]{"1.xml", "2.xml", "3.xml", "5.xml", "9.xml"}; public AbstractSecurityLwM2MIntegrationTest() { // create client credentials - setResources(this.resources); - setEndpoint(ENDPOINT); + setResources(this.RESOURCES_SECURITY); try { - // Get keys PSK - this.pskIdentity = "SOME_PSK_ID"; - this.pskKey = "73656372657450534b73656372657450"; - - // Get point values - byte[] publicX = Hex - .decodeHex("89c048261979208666f2bfb188be1968fc9021c416ce12828c06f4e314c167b5".toCharArray()); - byte[] publicY = Hex - .decodeHex("cbf1eb7587f08e01688d9ada4be859137ca49f79394bad9179326b3090967b68".toCharArray()); - byte[] privateS = Hex - .decodeHex("e67b68d2aaeb6550f19d98cade3ad62b39532e02e6b422e1f7ea189dabaea5d2".toCharArray()); - - // Get Elliptic Curve Parameter spec for secp256r1 - AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); - algoParameters.init(new ECGenParameterSpec("secp256r1")); - ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); - - // Create key specs - KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), - parameterSpec); - KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); - - // Get keys RPK - clientPublicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - clientPrivateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); - // Get certificates from key store - char[] clientKeyStorePwd = "client".toCharArray(); + char[] clientKeyStorePwd = CLIENT_STORE_PWD.toCharArray(); KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - try (InputStream clientKeyStoreFile = this.getClass().getClassLoader().getResourceAsStream("lwm2m/credentials/clientKeyStore.jks")) { + try (InputStream clientKeyStoreFile = this.getClass().getClassLoader().getResourceAsStream(CREDENTIALS_PATH + CLIENT_JKS_FOR_TEST + ".jks")) { clientKeyStore.load(clientKeyStoreFile, clientKeyStorePwd); } - - clientPrivateKeyFromCert = (PrivateKey) clientKeyStore.getKey("client", clientKeyStorePwd); - clientX509Cert = (X509Certificate) clientKeyStore.getCertificate("client"); - clientX509CertWithBadCN = (X509Certificate) clientKeyStore.getCertificate("client_bad_cn"); - clientX509CertSelfSigned = (X509Certificate) clientKeyStore.getCertificate("client_self_signed"); - clientX509CertNotTrusted = (X509Certificate) clientKeyStore.getCertificate("client_not_trusted"); + // Trust + clientPrivateKeyFromCertTrust = (PrivateKey) clientKeyStore.getKey(CLIENT_ALIAS_CERT_TRUST, clientKeyStorePwd); + clientX509CertTrust = (X509Certificate) clientKeyStore.getCertificate(CLIENT_ALIAS_CERT_TRUST); + // No trust + clientPrivateKeyFromCertTrustNo = (PrivateKey) clientKeyStore.getKey(CLIENT_ALIAS_CERT_TRUST_NO, clientKeyStorePwd); + clientX509CertTrustNo = (X509Certificate) clientKeyStore.getCertificate(CLIENT_ALIAS_CERT_TRUST_NO); } catch (GeneralSecurityException | IOException e) { throw new RuntimeException(e); } // create server credentials try { - // Get point values - byte[] publicX = Hex - .decodeHex("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73".toCharArray()); - byte[] publicY = Hex - .decodeHex("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a".toCharArray()); - byte[] privateS = Hex - .decodeHex("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400".toCharArray()); - - // Get Elliptic Curve Parameter spec for secp256r1 - AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC"); - algoParameters.init(new ECGenParameterSpec("secp256r1")); - ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class); - - // Create key specs - KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)), - parameterSpec); - KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec); - - // Get keys - serverPublicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec); - serverPrivateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec); - // Get certificates from key store - char[] serverKeyStorePwd = "server".toCharArray(); + char[] serverKeyStorePwd = SERVER_STORE_PWD.toCharArray(); KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - try (InputStream serverKeyStoreFile = this.getClass().getClassLoader().getResourceAsStream("lwm2m/credentials/serverKeyStore.jks")) { + try (InputStream serverKeyStoreFile = this.getClass().getClassLoader().getResourceAsStream(CREDENTIALS_PATH + SERVER_JKS_FOR_TEST + ".jks")) { serverKeyStore.load(serverKeyStoreFile, serverKeyStorePwd); } - serverPrivateKeyFromCert = (PrivateKey) serverKeyStore.getKey("server", serverKeyStorePwd); - rootCAX509Cert = (X509Certificate) serverKeyStore.getCertificate("rootCA"); - serverX509Cert = (X509Certificate) serverKeyStore.getCertificate("server"); - serverX509CertSelfSigned = (X509Certificate) serverKeyStore.getCertificate("server_self_signed"); - trustedCertificates[0] = serverX509Cert; + serverX509Cert = (X509Certificate) serverKeyStore.getCertificate(SERVER_CERT_ALIAS); + serverPublicKeyFromCert = serverX509Cert.getPublicKey(); + serverX509CertBs = (X509Certificate) serverKeyStore.getCertificate(SERVER_CERT_ALIAS_BS); + serverPublicKeyFromCertBs = serverX509CertBs.getPublicKey(); + } catch (GeneralSecurityException | IOException e) { throw new RuntimeException(e); } @@ -173,4 +160,248 @@ public abstract class AbstractSecurityLwM2MIntegrationTest extends AbstractLwM2M defaultBootstrapCredentials.setBootstrapServer(serverCredentials); defaultBootstrapCredentials.setLwm2mServer(serverCredentials); } + + public void basicTestConnectionBefore(String clientEndpoint, + String awaitAlias, + LwM2MProfileBootstrapConfigType type, + Set expectedStatuses, + LwM2MClientState finishState) throws Exception { + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsNoSec(type)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(clientEndpoint)); + this.basicTestConnection(noSecBootstap(URI_BS), + deviceCredentials, + COAP_CONFIG_BS, + clientEndpoint, + transportConfiguration, + awaitAlias, + expectedStatuses, + true, + finishState, + false); + } + + protected void basicTestConnection(Security security, + LwM2MDeviceCredentials deviceCredentials, + Configuration coapConfig, + String endpoint, + Lwm2mDeviceProfileTransportConfiguration transportConfiguration, + String awaitAlias, + Set expectedStatuses, + boolean isBootstrap, + LwM2MClientState finishState, + boolean isStartLw) throws Exception { + createNewClient(security, coapConfig, true, endpoint, isBootstrap, null); + createDeviceProfile(transportConfiguration); + final Device device = createDevice(deviceCredentials, endpoint); + device.getId().getId().toString(); + lwM2MTestClient.start(isStartLw); + await(awaitAlias) + .atMost(1000, TimeUnit.MILLISECONDS) + .until(() -> finishState.equals(lwM2MTestClient.getClientState())); + Assert.assertEquals(expectedStatuses, lwM2MTestClient.getClientStates()); + } + + + public void basicTestConnectionBootstrapRequestTriggerBefore(String clientEndpoint, String awaitAlias, LwM2MProfileBootstrapConfigType type) throws Exception { + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsNoSec(type)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(clientEndpoint)); + this.basicTestConnectionBootstrapRequestTrigger( + SECURITY_NO_SEC, + deviceCredentials, + COAP_CONFIG, + clientEndpoint, + transportConfiguration, + awaitAlias, + expectedStatusesRegistrationLwm2mSuccess, + expectedStatusesRegistrationBsSuccess, + false, + SECURITY_NO_SEC_BS); + } + + private void basicTestConnectionBootstrapRequestTrigger(Security security, + LwM2MDeviceCredentials deviceCredentials, + Configuration coapConfig, + String endpoint, + Lwm2mDeviceProfileTransportConfiguration transportConfiguration, + String awaitAlias, + Set expectedStatusesLwm2m, + Set expectedStatusesBs, + boolean isBootstrap, + Security securityBs) throws Exception { + createNewClient(security, coapConfig, true, endpoint, isBootstrap, securityBs); + createDeviceProfile(transportConfiguration); + final Device device = createDevice(deviceCredentials, endpoint); + String deviceId = device.getId().getId().toString(); + lwM2MTestClient.start(true); + await(awaitAlias) + .atMost(1000, TimeUnit.MILLISECONDS) + .until(() -> ON_REGISTRATION_SUCCESS.equals(lwM2MTestClient.getClientState())); + Assert.assertEquals(expectedStatusesLwm2m, lwM2MTestClient.getClientStates()); + + String executedPath = "/" + OBJECT_ID_1 + "_" + lwM2MTestClient.getLeshanClient().getObjectTree().getModel().getObjectModel(OBJECT_ID_1).version + + "/0/" + RESOURCE_ID_9; + String actualResult = sendRPCSecurityExecuteById(executedPath, deviceId, endpoint); + ObjectNode rpcActualResult = JacksonUtil.fromString(actualResult, ObjectNode.class); + assertEquals(ResponseCode.CHANGED.getName(), rpcActualResult.get("result").asText()); + expectedStatusesBs.add(ON_DEREGISTRATION_STARTED); + expectedStatusesBs.add(ON_DEREGISTRATION_SUCCESS); + await(awaitAlias) + .atMost(1000, TimeUnit.MILLISECONDS) + .until(() -> ON_REGISTRATION_SUCCESS.equals(lwM2MTestClient.getClientState())); + Assert.assertEquals(expectedStatusesBs, lwM2MTestClient.getClientStates()); + } + + protected List getBootstrapServerCredentialsSecure(LwM2MSecurityMode mode, LwM2MProfileBootstrapConfigType bootstrapConfigType) { + List bootstrap = new ArrayList<>(); + switch (bootstrapConfigType) { + case BOTH: + bootstrap.add(getBootstrapServerCredential(mode, false)); + bootstrap.add(getBootstrapServerCredential(mode, true)); + break; + case BOOTSTRAP_ONLY: + bootstrap.add(getBootstrapServerCredential(mode, true)); + break; + case LWM2M_ONLY: + bootstrap.add(getBootstrapServerCredential(mode, false)); + break; + case NONE: + } + return bootstrap; + } + + private AbstractLwM2MBootstrapServerCredential getBootstrapServerCredential(LwM2MSecurityMode mode, boolean isBootstrap) { + AbstractLwM2MBootstrapServerCredential bootstrapServerCredential; + switch (mode) { + case PSK: + bootstrapServerCredential = new PSKLwM2MBootstrapServerCredential(); + bootstrapServerCredential.setServerPublicKey(""); + break; + case RPK: + bootstrapServerCredential = new RPKLwM2MBootstrapServerCredential(); + if (isBootstrap) { + bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCertBs.getEncoded())); + } else { + bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverPublicKeyFromCert.getEncoded())); + } + break; + case X509: + bootstrapServerCredential = new X509LwM2MBootstrapServerCredential(); + try { + if (isBootstrap) { + bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509CertBs.getEncoded())); + } else { + bootstrapServerCredential.setServerPublicKey(Base64.encodeBase64String(serverX509Cert.getEncoded())); + } + } catch (CertificateEncodingException e) { + e.printStackTrace(); + } + break; + default: + throw new IllegalStateException("Unexpected value: " + mode); + } + bootstrapServerCredential.setShortServerId(isBootstrap ? shortServerIdBs : shortServerId); + bootstrapServerCredential.setBootstrapServerIs(isBootstrap); + bootstrapServerCredential.setHost(isBootstrap ? hostBs : host); + bootstrapServerCredential.setPort(isBootstrap ? securityPortBs : securityPort); + return bootstrapServerCredential; + } + + + protected LwM2MDeviceCredentials getDeviceCredentialsSecure(LwM2MClientCredential clientCredentials, + PrivateKey privateKey, + X509Certificate certificate, + LwM2MSecurityMode mode, + boolean privateKeyIsBad) { + LwM2MDeviceCredentials credentials = new LwM2MDeviceCredentials(); + credentials.setClient(clientCredentials); + LwM2MBootstrapClientCredentials bootstrapCredentials; + switch (mode) { + case PSK: + bootstrapCredentials = getBootstrapClientCredentialsPsk(clientCredentials); + break; + case RPK: + bootstrapCredentials = getBootstrapClientCredentialsRpk(certificate, privateKey, privateKeyIsBad); + break; + case X509: + bootstrapCredentials = getBootstrapClientCredentialsX509(certificate, privateKey, privateKeyIsBad); + break; + default: + throw new IllegalStateException("Unexpected value: " + mode); + } + credentials.setBootstrap(bootstrapCredentials); + return credentials; + } + + private LwM2MBootstrapClientCredentials getBootstrapClientCredentialsPsk(LwM2MClientCredential clientCredentials) { + LwM2MBootstrapClientCredentials bootstrapCredentials = new LwM2MBootstrapClientCredentials(); + PSKBootstrapClientCredential serverCredentials = new PSKBootstrapClientCredential(); + if (clientCredentials != null) { + serverCredentials.setClientSecretKey(((PSKClientCredential) clientCredentials).getKey()); + serverCredentials.setClientPublicKeyOrId(((PSKClientCredential) clientCredentials).getIdentity()); + } + bootstrapCredentials.setBootstrapServer(serverCredentials); + bootstrapCredentials.setLwm2mServer(serverCredentials); + return bootstrapCredentials; + } + + private LwM2MBootstrapClientCredentials getBootstrapClientCredentialsRpk(X509Certificate certificate, PrivateKey privateKey, boolean privateKeyIsBad) { + LwM2MBootstrapClientCredentials bootstrapCredentials = new LwM2MBootstrapClientCredentials(); + RPKBootstrapClientCredential serverCredentials = new RPKBootstrapClientCredential(); + if (certificate != null && certificate.getPublicKey() != null && privateKey != null) { + serverCredentials.setClientPublicKeyOrId(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); + if (privateKeyIsBad) { + serverCredentials.setClientSecretKey(Hex.encodeHexString(privateKey.getEncoded())); + } else { + serverCredentials.setClientSecretKey(Base64.encodeBase64String(privateKey.getEncoded())); + + } + } + bootstrapCredentials.setBootstrapServer(serverCredentials); + bootstrapCredentials.setLwm2mServer(serverCredentials); + return bootstrapCredentials; + } + + private LwM2MBootstrapClientCredentials getBootstrapClientCredentialsX509(X509Certificate certificate, PrivateKey privateKey, boolean privateKeyIsBad) { + LwM2MBootstrapClientCredentials bootstrapCredentials = new LwM2MBootstrapClientCredentials(); + X509BootstrapClientCredential serverCredentials = new X509BootstrapClientCredential(); + if (certificate != null) { + try { + serverCredentials.setClientPublicKeyOrId(Base64.encodeBase64String(certificate.getEncoded())); + if (privateKeyIsBad) { + serverCredentials.setClientSecretKey(Hex.encodeHexString(privateKey.getEncoded())); + } else { + serverCredentials.setClientSecretKey(Base64.encodeBase64String(privateKey.getEncoded())); + } + } catch (CertificateEncodingException e) { + log.error("Client`s certificate [{}] is bad. [{}]", certificate, e.getMessage()); + } + } + bootstrapCredentials.setBootstrapServer(serverCredentials); + bootstrapCredentials.setLwm2mServer(serverCredentials); + return bootstrapCredentials; + } + + protected MvcResult createDeviceWithMvcResult(LwM2MDeviceCredentials credentials, String endpoint) throws Exception { + Device device = new Device(); + device.setName(endpoint); + device.setDeviceProfileId(deviceProfile.getId()); + device.setTenantId(tenantId); + device = doPost("/api/device", device, Device.class); + Assert.assertNotNull(device); + + DeviceCredentials deviceCredentials = + doGet("/api/device/" + device.getId().getId().toString() + "/credentials", DeviceCredentials.class); + Assert.assertEquals(device.getId(), deviceCredentials.getDeviceId()); + deviceCredentials.setCredentialsType(DeviceCredentialsType.LWM2M_CREDENTIALS); + deviceCredentials.setCredentialsValue(JacksonUtil.toString(credentials)); + return doPost("/api/device/credentials", deviceCredentials).andReturn(); + } + + private String sendRPCSecurityExecuteById(String path, String deviceId, String endpoint) throws Exception { + log.info("endpoint1: [{}]", endpoint); + + + String setRpcRequest = "{\"method\": \"Execute\", \"params\": {\"id\": \"" + path + "\"}}"; + return doPostAsync("/api/plugins/rpc/twoway/" + deviceId, setRpcRequest, String.class, status().isOk()); + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/NoSecLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/NoSecLwM2MIntegrationTest.java index 0e86c6a438..203b1f56c7 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/NoSecLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/NoSecLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,21 +15,81 @@ */ package org.thingsboard.server.transport.lwm2m.security.sql; -import lombok.extern.slf4j.Slf4j; import org.junit.Test; -import org.thingsboard.server.common.data.device.credentials.lwm2m.NoSecClientCredential; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; import org.thingsboard.server.transport.lwm2m.security.AbstractSecurityLwM2MIntegrationTest; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURITY; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_BOOTSTRAP_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOOTSTRAP_ONLY; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOTH; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.LWM2M_ONLY; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; -@Slf4j public class NoSecLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTest { + //Lwm2m only @Test - public void testConnectAndObserveTelemetry() throws Exception { - NoSecClientCredential clientCredentials = createNoSecClientCredentials(ENDPOINT); - super.basicTestConnectionObserveTelemetry(SECURITY, clientCredentials, COAP_CONFIG, ENDPOINT); + public void testWithNoSecConnectLwm2mSuccessAndObserveTelemetry() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC; + LwM2MDeviceCredentials clientCredentials = getDeviceCredentialsNoSec(createNoSecClientCredentials(clientEndpoint)); + super.basicTestConnectionObserveTelemetry(SECURITY_NO_SEC, clientCredentials, COAP_CONFIG, clientEndpoint); } + // Bootstrap + Lwm2m + @Test + public void testWithNoSecConnectBsSuccess_UpdateTwoSectionsBootstrapAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS; + String awaitAlias = "await on client state (NoSecBS two section)"; + basicTestConnectionBefore(clientEndpoint, awaitAlias, BOTH, expectedStatusesRegistrationBsSuccess, ON_REGISTRATION_SUCCESS); + } + + @Test + public void testWithNoSecConnectBsSuccess_UpdateLwm2mSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS + LWM2M_ONLY.name(); + String awaitAlias = "await on client state (NoSecBS Lwm2m section)"; + basicTestConnectionBefore(clientEndpoint, awaitAlias, LWM2M_ONLY, expectedStatusesRegistrationBsSuccess, ON_REGISTRATION_SUCCESS); + } + + @Test + public void testWithNoSecConnectBsSuccess_UpdateBootstrapSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC + BOOTSTRAP_ONLY.name(); + String awaitAlias = "await on client state (NoSecBS Bootstrap section)"; + basicTestConnectionBefore(clientEndpoint, awaitAlias, BOOTSTRAP_ONLY, expectedStatusesBsSuccess, ON_BOOTSTRAP_SUCCESS); + } + + @Test + public void testWithNoSecConnectBsSuccess_UpdateNoneSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC + NONE.name(); + String awaitAlias = "await on client state (NoSecBS None section)"; + basicTestConnectionBefore(clientEndpoint, awaitAlias, NONE, expectedStatusesBsSuccess, ON_BOOTSTRAP_SUCCESS); + } + + @Test + public void testWithNoSecConnectLwm2mSuccessBootstrapRequestTriggerConnectBsSuccess_UpdateTwoSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS + "Trigger" + BOTH.name(); + String awaitAlias = "await on client state (NoSecBS Trigger Two section)"; + basicTestConnectionBootstrapRequestTriggerBefore(clientEndpoint, awaitAlias, BOTH); + } + + @Test + public void testWithNoSecConnectLwm2mSuccessBootstrapRequestTriggerConnectBsSuccess_UpdateBootstrapSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS + "Trigger" + BOOTSTRAP_ONLY.name(); + String awaitAlias = "await on client state (NoSecBS Trigger Bootstrap section)"; + basicTestConnectionBootstrapRequestTriggerBefore(clientEndpoint, awaitAlias, BOOTSTRAP_ONLY); + } + + @Test + public void testWithNoSecConnectLwm2mSuccessBootstrapRequestTriggerConnectBsSuccess_UpdateLwm2mSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS + "Trigger" + LWM2M_ONLY.name(); + String awaitAlias = "await on client state (NoSecBS Trigger Lwm2m section)"; + basicTestConnectionBootstrapRequestTriggerBefore(clientEndpoint, awaitAlias, LWM2M_ONLY); + } + + @Test + public void testWithNoSecConnectLwm2mSuccessBootstrapRequestTriggerConnectBsSuccess_UpdateNoneSectionAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_NO_SEC_BS + "Trigger" + NONE.name(); + String awaitAlias = "await on client state (NoSecBS Trigger None section)"; + basicTestConnectionBootstrapRequestTriggerBefore(clientEndpoint, awaitAlias, NONE); + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java index af9a668376..7eeb4b4090 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/PskLwm2mIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,28 +18,97 @@ package org.thingsboard.server.transport.lwm2m.security.sql; import org.eclipse.leshan.client.object.Security; import org.eclipse.leshan.core.util.Hex; import org.junit.Test; +import org.springframework.test.web.servlet.MvcResult; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; import org.thingsboard.server.common.data.device.credentials.lwm2m.PSKClientCredential; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.transport.lwm2m.security.AbstractSecurityLwM2MIntegrationTest; +import javax.servlet.http.HttpServletResponse; import java.nio.charset.StandardCharsets; import static org.eclipse.leshan.client.object.Security.psk; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_URI; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SHORT_SERVER_ID; +import static org.eclipse.leshan.client.object.Security.pskBootstrap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.PSK; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOTH; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; public class PskLwm2mIntegrationTest extends AbstractSecurityLwM2MIntegrationTest { + //Lwm2m only @Test - public void testConnectWithPSKAndObserveTelemetry() throws Exception { + public void testWithPskConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_PSK; + String identity = CLIENT_PSK_IDENTITY; + String keyPsk = CLIENT_PSK_KEY; PSKClientCredential clientCredentials = new PSKClientCredential(); - clientCredentials.setEndpoint(ENDPOINT); - clientCredentials.setKey(pskKey); - clientCredentials.setIdentity(pskIdentity); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setIdentity(identity); + clientCredentials.setKey(keyPsk); Security security = psk(SECURE_URI, - SHORT_SERVER_ID, - pskIdentity.getBytes(StandardCharsets.UTF_8), - Hex.decodeHex(pskKey.toCharArray())); - super.basicTestConnectionObserveTelemetry(security, clientCredentials, SECURE_COAP_CONFIG, ENDPOINT); + shortServerId, + identity.getBytes(StandardCharsets.UTF_8), + Hex.decodeHex(keyPsk.toCharArray())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); + this.basicTestConnection(security, + deviceCredentials, + COAP_CONFIG, + clientEndpoint, + transportConfiguration, + "await on client state (Psk_Lwm2m)", + expectedStatusesRegistrationLwm2mSuccess, + false, + ON_REGISTRATION_SUCCESS, + true); + } + + @Test + public void testWithPskConnectLwm2mBadPskKeyByLength_BAD_REQUEST() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_PSK; + String identity = CLIENT_PSK_IDENTITY + "_BadLength"; + String keyPsk = CLIENT_PSK_KEY + "05AC"; + PSKClientCredential clientCredentials = new PSKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setIdentity(identity); + clientCredentials.setKey(keyPsk); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, NONE)); + createDeviceProfile(transportConfiguration); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); + MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); + String msgExpected = "Key must be HexDec format: 32, 64, 128 characters!"; + assertTrue(result.getResponse().getContentAsString().contains(msgExpected)); + } + + + // Bootstrap + Lwm2m + @Test + public void testWithPskConnectBsSuccess_UpdateTwoSectionsBootstrapAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_PSK_BS; + String identity = CLIENT_PSK_IDENTITY_BS; + String keyPsk = CLIENT_PSK_KEY; + PSKClientCredential clientCredentials = new PSKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setIdentity(identity); + clientCredentials.setKey(keyPsk); + Security securityBs = pskBootstrap(SECURE_URI_BS, + identity.getBytes(StandardCharsets.UTF_8), + Hex.decodeHex(keyPsk.toCharArray())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(PSK, BOTH)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, null, null, PSK, false); + this.basicTestConnection(securityBs, + deviceCredentials, + COAP_CONFIG_BS, + clientEndpoint, + transportConfiguration, + "await on client state (PskBS two section)", + expectedStatusesRegistrationBsSuccess, + true, + ON_REGISTRATION_SUCCESS, + true); } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java index 9e74beaa6b..16c34550c2 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/RpkLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,30 +15,117 @@ */ package org.thingsboard.server.transport.lwm2m.security.sql; +import org.apache.commons.codec.binary.Base64; import org.eclipse.leshan.client.object.Security; +import org.eclipse.leshan.core.util.Hex; import org.junit.Test; +import org.springframework.test.web.servlet.MvcResult; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; import org.thingsboard.server.common.data.device.credentials.lwm2m.RPKClientCredential; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.transport.lwm2m.security.AbstractSecurityLwM2MIntegrationTest; -import org.apache.commons.codec.binary.Base64;; +import javax.servlet.http.HttpServletResponse; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; import static org.eclipse.leshan.client.object.Security.rpk; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_URI; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SHORT_SERVER_ID; +import static org.eclipse.leshan.client.object.Security.rpkBootstrap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.RPK; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOTH; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; public class RpkLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTest { + //Lwm2m only @Test - public void testConnectWithRPKAndObserveTelemetry() throws Exception { - RPKClientCredential rpkClientCredentials = new RPKClientCredential(); - rpkClientCredentials.setEndpoint(ENDPOINT); - rpkClientCredentials.setKey(new String(Base64.encodeBase64(clientPublicKey.getEncoded()))); - Security security = rpk(SECURE_URI, - SHORT_SERVER_ID, - clientPublicKey.getEncoded(), - clientPrivateKey.getEncoded(), + public void testWithRpkConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_RPK; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + RPKClientCredential clientCredentials = new RPKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setKey(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); + Security securityBs = rpk(SECURE_URI, + shortServerId, + certificate.getPublicKey().getEncoded(), + privateKey.getEncoded(), serverX509Cert.getPublicKey().getEncoded()); - super.basicTestConnectionObserveTelemetry(security, rpkClientCredentials, SECURE_COAP_CONFIG, ENDPOINT); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); + this.basicTestConnection(securityBs, + deviceCredentials, + COAP_CONFIG, + clientEndpoint, + transportConfiguration, + "await on client state (Rpk_Lwm2m)", + expectedStatusesRegistrationLwm2mSuccess, + false, + ON_REGISTRATION_SUCCESS, + true); + } + + @Test + public void testWithRpkValidationPublicKeyBase64format_BAD_REQUEST() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_RPK + "BadPublicKey"; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + RPKClientCredential clientCredentials = new RPKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setKey(Hex.encodeHexString(certificate.getPublicKey().getEncoded())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, false); + createDeviceProfile(transportConfiguration); + MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); + String msgExpected = "LwM2M client RPK key must be in standard [RFC7250] and support only EC algorithm and then encoded to Base64 format!"; + assertTrue(result.getResponse().getContentAsString().contains(msgExpected)); + } + + @Test + public void testWithRpkValidationPrivateKeyBase64format_BAD_REQUEST() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_RPK + "BadPrivateKey"; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + RPKClientCredential clientCredentials = new RPKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setKey(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, RPK, true); + createDeviceProfile(transportConfiguration); + MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); + String msgExpected = "Bootstrap server client RPK secret key must be in PKCS#8 format (DER encoding, standard [RFC5958]) and then encoded to Base64 format!"; + assertTrue(result.getResponse().getContentAsString().contains(msgExpected)); + } + + // Bootstrap + Lwm2m + @Test + public void testWithRpkConnectBsSuccess_UpdateTwoSectionsBootstrapAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_RPK_BS; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + RPKClientCredential clientCredentials = new RPKClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setKey(Base64.encodeBase64String(certificate.getPublicKey().getEncoded())); + Security securityBs = rpkBootstrap(SECURE_URI_BS, + certificate.getPublicKey().getEncoded(), + privateKey.getEncoded(), + serverX509CertBs.getPublicKey().getEncoded()); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(RPK, BOTH)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, clientPrivateKeyFromCertTrust, certificate, RPK, false); + this.basicTestConnection(securityBs, + deviceCredentials, + COAP_CONFIG_BS, + clientEndpoint, + transportConfiguration, + "await on client state (RpkBS two section)", + expectedStatusesRegistrationBsSuccess, + true, + ON_REGISTRATION_SUCCESS, + true); } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java index f55c21dcc2..57e26c060e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_NoTrustLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,29 +16,116 @@ package org.thingsboard.server.transport.lwm2m.security.sql; import org.eclipse.leshan.client.object.Security; +import org.eclipse.leshan.core.util.Hex; import org.junit.Test; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.util.Base64Utils; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; import org.thingsboard.server.common.data.device.credentials.lwm2m.X509ClientCredential; -import org.thingsboard.server.common.transport.util.SslUtil; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.transport.lwm2m.security.AbstractSecurityLwM2MIntegrationTest; +import javax.servlet.http.HttpServletResponse; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; + import static org.eclipse.leshan.client.object.Security.x509; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_URI; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SHORT_SERVER_ID; +import static org.eclipse.leshan.client.object.Security.x509Bootstrap; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.X509; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOTH; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; public class X509_NoTrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTest { + //Lwm2m only @Test - public void testConnectWithCertAndObserveTelemetry() throws Exception { - X509ClientCredential credentials = new X509ClientCredential(); - credentials.setEndpoint(ENDPOINT); - credentials.setCert(SslUtil.getCertificateString(clientX509CertNotTrusted)); + public void testWithX509NoTrustConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST_NO; + X509Certificate certificate = clientX509CertTrustNo; + PrivateKey privateKey = clientPrivateKeyFromCertTrustNo; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(Base64Utils.encodeToString(certificate.getEncoded())); Security security = x509(SECURE_URI, - SHORT_SERVER_ID, - clientX509CertNotTrusted.getEncoded(), - clientPrivateKeyFromCert.getEncoded(), + shortServerId, + certificate.getEncoded(), + privateKey.getEncoded(), serverX509Cert.getEncoded()); - super.basicTestConnectionObserveTelemetry(security, credentials, SECURE_COAP_CONFIG, ENDPOINT); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); + this.basicTestConnection(security, + deviceCredentials, + COAP_CONFIG, + clientEndpoint, + transportConfiguration, + "await on client state (X509_Trust_Lwm2m)", + expectedStatusesRegistrationLwm2mSuccess, + false, + ON_REGISTRATION_SUCCESS, + true); } + @Test + public void testWithX509NoTrustValidationPublicKeyBase64format_BAD_REQUEST() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST_NO + "BadPublicKey"; + X509Certificate certificate = clientX509CertTrustNo; + PrivateKey privateKey = clientPrivateKeyFromCertTrustNo; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(Hex.encodeHexString(certificate.getEncoded())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); + createDeviceProfile(transportConfiguration); + MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); + String msgExpected = "LwM2M client X509 certificate must be in DER-encoded X509v3 format and support only EC algorithm and then encoded to Base64 format!"; + assertTrue(result.getResponse().getContentAsString().contains(msgExpected)); + } + + @Test + public void testWithX509NoTrustValidationPrivateKeyBase64format_BAD_REQUEST() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST_NO + "BadPrivateKey"; + X509Certificate certificate = clientX509CertTrustNo; + PrivateKey privateKey = clientPrivateKeyFromCertTrustNo; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(Base64Utils.encodeToString(certificate.getEncoded())); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, true); + createDeviceProfile(transportConfiguration); + MvcResult result = createDeviceWithMvcResult(deviceCredentials, clientEndpoint); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, result.getResponse().getStatus()); + String msgExpected = "Bootstrap server client X509 secret key must be in PKCS#8 format (DER encoding, standard [RFC5958]) and then encoded to Base64 format!"; + assertTrue(result.getResponse().getContentAsString().contains(msgExpected)); + } + + // Bootstrap + Lwm2m + @Test + public void testWithX509NoTrustConnectBsSuccess_UpdateTwoSectionsBootstrapAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST_NO; + X509Certificate certificate = clientX509CertTrustNo; + PrivateKey privateKey = clientPrivateKeyFromCertTrustNo; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(Base64Utils.encodeToString(certificate.getEncoded())); + Security security = x509Bootstrap(SECURE_URI_BS, + certificate.getEncoded(), + privateKey.getEncoded(), + serverX509CertBs.getEncoded()); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); + this.basicTestConnection(security, + deviceCredentials, + COAP_CONFIG_BS, + clientEndpoint, + transportConfiguration, + "await on client state (X509NoTrust two section)", + expectedStatusesRegistrationBsSuccess, + true, + ON_REGISTRATION_SUCCESS, + true); + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java index 32d176d598..cd0cec1c16 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/security/sql/X509_TrustLwM2MIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,26 +17,75 @@ package org.thingsboard.server.transport.lwm2m.security.sql; import org.eclipse.leshan.client.object.Security; import org.junit.Test; +import org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MDeviceCredentials; import org.thingsboard.server.common.data.device.credentials.lwm2m.X509ClientCredential; +import org.thingsboard.server.common.data.device.profile.Lwm2mDeviceProfileTransportConfiguration; import org.thingsboard.server.transport.lwm2m.security.AbstractSecurityLwM2MIntegrationTest; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; + import static org.eclipse.leshan.client.object.Security.x509; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_COAP_CONFIG; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SECURE_URI; -import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.SHORT_SERVER_ID; +import static org.eclipse.leshan.client.object.Security.x509Bootstrap; +import static org.thingsboard.server.common.data.device.credentials.lwm2m.LwM2MSecurityMode.X509; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MClientState.ON_REGISTRATION_SUCCESS; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.BOTH; +import static org.thingsboard.server.transport.lwm2m.Lwm2mTestHelper.LwM2MProfileBootstrapConfigType.NONE; public class X509_TrustLwM2MIntegrationTest extends AbstractSecurityLwM2MIntegrationTest { + //Lwm2m only @Test - public void testConnectAndObserveTelemetry() throws Exception { - X509ClientCredential credentials = new X509ClientCredential(); - credentials.setEndpoint(ENDPOINT); + public void testWithX509TrustConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(""); Security security = x509(SECURE_URI, - SHORT_SERVER_ID, - clientX509Cert.getEncoded(), - clientPrivateKeyFromCert.getEncoded(), + shortServerId, + certificate.getEncoded(), + privateKey.getEncoded(), serverX509Cert.getEncoded()); - super.basicTestConnectionObserveTelemetry(security, credentials, SECURE_COAP_CONFIG, ENDPOINT); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, NONE)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); + this.basicTestConnection(security, + deviceCredentials, + COAP_CONFIG, + clientEndpoint, + transportConfiguration, + "await on client state (X509_Trust_Lwm2m)", + expectedStatusesRegistrationLwm2mSuccess, + false, + ON_REGISTRATION_SUCCESS, + true); } + // Bootstrap + Lwm2m + @Test + public void testWithX509TrustConnectBsSuccess_UpdateTwoSectionsBootstrapAndLm2m_ConnectLwm2mSuccess() throws Exception { + String clientEndpoint = CLIENT_ENDPOINT_X509_TRUST; + X509Certificate certificate = clientX509CertTrust; + PrivateKey privateKey = clientPrivateKeyFromCertTrust; + X509ClientCredential clientCredentials = new X509ClientCredential(); + clientCredentials.setEndpoint(clientEndpoint); + clientCredentials.setCert(""); + Security security = x509Bootstrap(SECURE_URI_BS, + certificate.getEncoded(), + privateKey.getEncoded(), + serverX509CertBs.getEncoded()); + Lwm2mDeviceProfileTransportConfiguration transportConfiguration = getTransportConfiguration(OBSERVE_ATTRIBUTES_WITHOUT_PARAMS, getBootstrapServerCredentialsSecure(X509, BOTH)); + LwM2MDeviceCredentials deviceCredentials = getDeviceCredentialsSecure(clientCredentials, privateKey, certificate, X509, false); + this.basicTestConnection(security, + deviceCredentials, + COAP_CONFIG_BS, + clientEndpoint, + transportConfiguration, + "await on client state (X509Trust two section)", + expectedStatusesRegistrationBsSuccess, + true, + ON_REGISTRATION_SUCCESS, + true); + } } diff --git a/application/src/test/java/org/thingsboard/server/transport/lwm2m/server/LwM2mTransportServerHelperTest.java b/application/src/test/java/org/thingsboard/server/transport/lwm2m/server/LwM2mTransportServerHelperTest.java index fabb2ba36f..d2b7fe141e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/lwm2m/server/LwM2mTransportServerHelperTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/lwm2m/server/LwM2mTransportServerHelperTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/AbstractMqttIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/AbstractMqttIntegrationTest.java index d815e85990..9fbdff3fa5 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/AbstractMqttIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/AbstractMqttIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,16 +22,15 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; -import org.junit.Assert; +import org.springframework.test.context.TestPropertySource; import org.springframework.util.StringUtils; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.DeviceProfileInfo; import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.DeviceProfileType; import org.thingsboard.server.common.data.DeviceTransportType; -import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.device.profile.AllowCreateNewDevicesDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration; import org.thingsboard.server.common.data.device.profile.DefaultDeviceProfileConfiguration; @@ -42,7 +41,6 @@ import org.thingsboard.server.common.data.device.profile.JsonTransportPayloadCon import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; -import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.transport.AbstractTransportIntegrationTest; @@ -51,187 +49,130 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +@TestPropertySource(properties = { + "transport.mqtt.enabled=true", + "js.evaluator=mock", +}) @Slf4j public abstract class AbstractMqttIntegrationTest extends AbstractTransportIntegrationTest { protected Device savedGateway; protected String gatewayAccessToken; - protected DeviceProfile deviceProfile; - - protected void processBeforeTest(String deviceName, String gatewayName, TransportPayloadType payloadType, String telemetryTopic, String attributesTopic) throws Exception { - this.processBeforeTest(deviceName, gatewayName, payloadType, telemetryTopic, attributesTopic, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); - } - - protected void processBeforeTest(String deviceName, String gatewayName, TransportPayloadType payloadType, String telemetryTopic, String attributesTopic, boolean enableCompatibilityWithJsonPayloadFormat, boolean useJsonPayloadFormatForDefaultDownlinkTopics) throws Exception { - this.processBeforeTest(deviceName, gatewayName, payloadType, telemetryTopic, attributesTopic, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, enableCompatibilityWithJsonPayloadFormat, useJsonPayloadFormatForDefaultDownlinkTopics); - } - - protected void processBeforeTest(String deviceName, - String gatewayName, - TransportPayloadType payloadType, - String telemetryTopic, - String attributesTopic, - String telemetryProtoSchema, - String attributesProtoSchema, - String rpcResponseProtoSchema, - String rpcRequestProtoSchema, - String provisionKey, - String provisionSecret, - DeviceProfileProvisionType provisionType, - boolean enableCompatibilityWithJsonPayloadFormat, - boolean useJsonPayloadFormatForDefaultDownlinkTopics) throws Exception { - loginSysAdmin(); - - Tenant tenant = new Tenant(); - tenant.setTitle("My tenant"); - savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedTenant); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant" + atomicInteger.getAndIncrement() + "@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); - - tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); - - Device device = new Device(); - device.setName(deviceName); - device.setType("default"); - - Device gateway = new Device(); - gateway.setName(gatewayName); - gateway.setType("default"); - ObjectNode additionalInfo = mapper.createObjectNode(); - additionalInfo.put("gateway", true); - gateway.setAdditionalInfo(additionalInfo); - - if (payloadType != null) { - DeviceProfile mqttDeviceProfile = createMqttDeviceProfile(payloadType, telemetryTopic, attributesTopic, telemetryProtoSchema, attributesProtoSchema, rpcResponseProtoSchema, rpcRequestProtoSchema, provisionKey, provisionSecret, provisionType, enableCompatibilityWithJsonPayloadFormat, useJsonPayloadFormatForDefaultDownlinkTopics); - deviceProfile = doPost("/api/deviceProfile", mqttDeviceProfile, DeviceProfile.class); - device.setType(deviceProfile.getName()); - device.setDeviceProfileId(deviceProfile.getId()); - gateway.setType(deviceProfile.getName()); - gateway.setDeviceProfileId(deviceProfile.getId()); + protected void processBeforeTest(MqttTestConfigProperties config) throws Exception { + loginTenantAdmin(); + deviceProfile = createMqttDeviceProfile(config); + assertNotNull(deviceProfile); + if (config.getDeviceName() != null) { + savedDevice = createDevice(config.getDeviceName(), deviceProfile.getName(), false); + DeviceCredentials deviceCredentials = + doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); + assertNotNull(deviceCredentials); + assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); + accessToken = deviceCredentials.getCredentialsId(); + assertNotNull(accessToken); } - - savedDevice = doPost("/api/device", device, Device.class); - - DeviceCredentials deviceCredentials = - doGet("/api/device/" + savedDevice.getId().getId().toString() + "/credentials", DeviceCredentials.class); - - savedGateway = doPost("/api/device", gateway, Device.class); - - DeviceCredentials gatewayCredentials = - doGet("/api/device/" + savedGateway.getId().getId().toString() + "/credentials", DeviceCredentials.class); - - assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); - accessToken = deviceCredentials.getCredentialsId(); - assertNotNull(accessToken); - - assertEquals(savedGateway.getId(), gatewayCredentials.getDeviceId()); - gatewayAccessToken = gatewayCredentials.getCredentialsId(); - assertNotNull(gatewayAccessToken); - - } - - protected void processAfterTest() throws Exception { - loginSysAdmin(); - if (savedTenant != null) { - doDelete("/api/tenant/" + savedTenant.getId().getId().toString()).andExpect(status().isOk()); + if (config.getGatewayName() != null) { + savedGateway = createDevice(config.getGatewayName(), deviceProfile.getName(), true); + DeviceCredentials gatewayCredentials = + doGet("/api/device/" + savedGateway.getId().getId().toString() + "/credentials", DeviceCredentials.class); + assertNotNull(gatewayCredentials); + assertEquals(savedGateway.getId(), gatewayCredentials.getDeviceId()); + gatewayAccessToken = gatewayCredentials.getCredentialsId(); + assertNotNull(gatewayAccessToken); } } - protected MqttAsyncClient getMqttAsyncClient(String accessToken) throws MqttException { - String clientId = MqttAsyncClient.generateClientId(); - MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, clientId, new MemoryPersistence()); - - MqttConnectOptions options = new MqttConnectOptions(); - options.setUserName(accessToken); - client.connect(options).waitForCompletion(); - return client; - } - - protected void publishMqttMsg(MqttAsyncClient client, byte[] payload, String topic) throws MqttException { - MqttMessage message = new MqttMessage(); - message.setPayload(payload); - client.publish(topic, message); - } - - protected DeviceProfile createMqttDeviceProfile(TransportPayloadType transportPayloadType, - String telemetryTopic, String attributesTopic, - String telemetryProtoSchema, String attributesProtoSchema, - String rpcResponseProtoSchema, String rpcRequestProtoSchema, - String provisionKey, String provisionSecret, - DeviceProfileProvisionType provisionType, - boolean enableCompatibilityWithJsonPayloadFormat, - boolean useJsonPayloadFormatForDefaultDownlinkTopics) { - DeviceProfile deviceProfile = new DeviceProfile(); - deviceProfile.setName(transportPayloadType.name()); - deviceProfile.setType(DeviceProfileType.DEFAULT); - deviceProfile.setTransportType(DeviceTransportType.MQTT); - deviceProfile.setProvisionType(provisionType); - deviceProfile.setProvisionDeviceKey(provisionKey); - deviceProfile.setDescription(transportPayloadType.name() + " Test"); - DeviceProfileData deviceProfileData = new DeviceProfileData(); - DefaultDeviceProfileConfiguration configuration = new DefaultDeviceProfileConfiguration(); - MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = new MqttDeviceProfileTransportConfiguration(); - if (!StringUtils.isEmpty(telemetryTopic)) { - mqttDeviceProfileTransportConfiguration.setDeviceTelemetryTopic(telemetryTopic); - } - if (!StringUtils.isEmpty(attributesTopic)) { - mqttDeviceProfileTransportConfiguration.setDeviceAttributesTopic(attributesTopic); - } - TransportPayloadTypeConfiguration transportPayloadTypeConfiguration; - if (TransportPayloadType.JSON.equals(transportPayloadType)) { - transportPayloadTypeConfiguration = new JsonTransportPayloadConfiguration(); + protected DeviceProfile createMqttDeviceProfile(MqttTestConfigProperties config) throws Exception { + TransportPayloadType transportPayloadType = config.getTransportPayloadType(); + if (transportPayloadType == null) { + DeviceProfileInfo defaultDeviceProfileInfo = doGet("/api/deviceProfileInfo/default", DeviceProfileInfo.class); + return doGet("/api/deviceProfile/" + defaultDeviceProfileInfo.getId().getId(), DeviceProfile.class); } else { - ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = new ProtoTransportPayloadConfiguration(); - if (StringUtils.isEmpty(telemetryProtoSchema)) { - telemetryProtoSchema = DEVICE_TELEMETRY_PROTO_SCHEMA; + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName(transportPayloadType.name()); + deviceProfile.setType(DeviceProfileType.DEFAULT); + deviceProfile.setTransportType(DeviceTransportType.MQTT); + DeviceProfileProvisionType provisionType = config.getProvisionType() != null ? + config.getProvisionType() : DeviceProfileProvisionType.DISABLED; + deviceProfile.setProvisionType(provisionType); + deviceProfile.setProvisionDeviceKey(config.getProvisionKey()); + deviceProfile.setDescription(transportPayloadType.name() + " Test"); + DeviceProfileData deviceProfileData = new DeviceProfileData(); + DefaultDeviceProfileConfiguration configuration = new DefaultDeviceProfileConfiguration(); + MqttDeviceProfileTransportConfiguration mqttDeviceProfileTransportConfiguration = new MqttDeviceProfileTransportConfiguration(); + if (StringUtils.hasLength(config.getTelemetryTopicFilter())) { + mqttDeviceProfileTransportConfiguration.setDeviceTelemetryTopic(config.getTelemetryTopicFilter()); } - if (StringUtils.isEmpty(attributesProtoSchema)) { - attributesProtoSchema = DEVICE_ATTRIBUTES_PROTO_SCHEMA; + if (StringUtils.hasLength(config.getAttributesTopicFilter())) { + mqttDeviceProfileTransportConfiguration.setDeviceAttributesTopic(config.getAttributesTopicFilter()); } - if (StringUtils.isEmpty(rpcResponseProtoSchema)) { - rpcResponseProtoSchema = DEVICE_RPC_RESPONSE_PROTO_SCHEMA; + mqttDeviceProfileTransportConfiguration.setSendAckOnValidationException(config.isSendAckOnValidationException()); + TransportPayloadTypeConfiguration transportPayloadTypeConfiguration; + if (TransportPayloadType.JSON.equals(transportPayloadType)) { + transportPayloadTypeConfiguration = new JsonTransportPayloadConfiguration(); + } else { + ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = new ProtoTransportPayloadConfiguration(); + String telemetryProtoSchema = config.getTelemetryProtoSchema(); + String attributesProtoSchema = config.getAttributesProtoSchema(); + String rpcResponseProtoSchema = config.getRpcResponseProtoSchema(); + String rpcRequestProtoSchema = config.getRpcRequestProtoSchema(); + protoTransportPayloadConfiguration.setDeviceTelemetryProtoSchema( + telemetryProtoSchema != null ? telemetryProtoSchema : DEVICE_TELEMETRY_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceAttributesProtoSchema( + attributesProtoSchema != null ? attributesProtoSchema : DEVICE_ATTRIBUTES_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceRpcResponseProtoSchema( + rpcResponseProtoSchema != null ? rpcResponseProtoSchema : DEVICE_RPC_RESPONSE_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setDeviceRpcRequestProtoSchema( + rpcRequestProtoSchema != null ? rpcRequestProtoSchema : DEVICE_RPC_REQUEST_PROTO_SCHEMA + ); + protoTransportPayloadConfiguration.setEnableCompatibilityWithJsonPayloadFormat( + config.isEnableCompatibilityWithJsonPayloadFormat() + ); + protoTransportPayloadConfiguration.setUseJsonPayloadFormatForDefaultDownlinkTopics( + config.isEnableCompatibilityWithJsonPayloadFormat() && + config.isUseJsonPayloadFormatForDefaultDownlinkTopics() + ); + transportPayloadTypeConfiguration = protoTransportPayloadConfiguration; } - if (StringUtils.isEmpty(rpcRequestProtoSchema)) { - rpcRequestProtoSchema = DEVICE_RPC_REQUEST_PROTO_SCHEMA; + mqttDeviceProfileTransportConfiguration.setTransportPayloadTypeConfiguration(transportPayloadTypeConfiguration); + deviceProfileData.setTransportConfiguration(mqttDeviceProfileTransportConfiguration); + DeviceProfileProvisionConfiguration provisionConfiguration; + switch (provisionType) { + case ALLOW_CREATE_NEW_DEVICES: + provisionConfiguration = new AllowCreateNewDevicesDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; + case CHECK_PRE_PROVISIONED_DEVICES: + provisionConfiguration = new CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; + case DISABLED: + default: + provisionConfiguration = new DisabledDeviceProfileProvisionConfiguration(config.getProvisionSecret()); + break; } - protoTransportPayloadConfiguration.setDeviceTelemetryProtoSchema(telemetryProtoSchema); - protoTransportPayloadConfiguration.setDeviceAttributesProtoSchema(attributesProtoSchema); - protoTransportPayloadConfiguration.setDeviceRpcResponseProtoSchema(rpcResponseProtoSchema); - protoTransportPayloadConfiguration.setDeviceRpcRequestProtoSchema(rpcRequestProtoSchema); - protoTransportPayloadConfiguration.setEnableCompatibilityWithJsonPayloadFormat(enableCompatibilityWithJsonPayloadFormat); - protoTransportPayloadConfiguration.setUseJsonPayloadFormatForDefaultDownlinkTopics(enableCompatibilityWithJsonPayloadFormat && useJsonPayloadFormatForDefaultDownlinkTopics); - transportPayloadTypeConfiguration = protoTransportPayloadConfiguration; + deviceProfileData.setProvisionConfiguration(provisionConfiguration); + deviceProfileData.setConfiguration(configuration); + deviceProfile.setProfileData(deviceProfileData); + deviceProfile.setDefault(false); + deviceProfile.setDefaultRuleChainId(null); + return doPost("/api/deviceProfile", deviceProfile, DeviceProfile.class); } - mqttDeviceProfileTransportConfiguration.setTransportPayloadTypeConfiguration(transportPayloadTypeConfiguration); - deviceProfileData.setTransportConfiguration(mqttDeviceProfileTransportConfiguration); - DeviceProfileProvisionConfiguration provisionConfiguration; - switch (provisionType) { - case ALLOW_CREATE_NEW_DEVICES: - provisionConfiguration = new AllowCreateNewDevicesDeviceProfileProvisionConfiguration(provisionSecret); - break; - case CHECK_PRE_PROVISIONED_DEVICES: - provisionConfiguration = new CheckPreProvisionedDevicesDeviceProfileProvisionConfiguration(provisionSecret); - break; - case DISABLED: - default: - provisionConfiguration = new DisabledDeviceProfileProvisionConfiguration(provisionSecret); - break; + } + + protected Device createDevice(String name, String type, boolean gateway) throws Exception { + Device device = new Device(); + device.setName(name); + device.setType(type); + if (gateway) { + ObjectNode additionalInfo = mapper.createObjectNode(); + additionalInfo.put("gateway", true); + device.setAdditionalInfo(additionalInfo); } - deviceProfileData.setProvisionConfiguration(provisionConfiguration); - deviceProfileData.setConfiguration(configuration); - deviceProfile.setProfileData(deviceProfileData); - deviceProfile.setDefault(false); - deviceProfile.setDefaultRuleChainId(null); - return deviceProfile; + return doPost("/api/device", device, Device.class); } protected TransportProtos.PostAttributeMsg getPostAttributeMsg(List expectedKeys) { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestCallback.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestCallback.java new file mode 100644 index 0000000000..18815d1c38 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestCallback.java @@ -0,0 +1,88 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.mqtt; + +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.internal.wire.MqttWireMessage; + +import java.util.concurrent.CountDownLatch; + +@Slf4j +@Data +public class MqttTestCallback implements MqttCallback { + + protected CountDownLatch subscribeLatch; + protected final CountDownLatch deliveryLatch; + protected int qoS; + protected byte[] payloadBytes; + protected String awaitSubTopic; + protected boolean pubAckReceived; + + public MqttTestCallback() { + this.subscribeLatch = new CountDownLatch(1); + this.deliveryLatch = new CountDownLatch(1); + } + + public MqttTestCallback(int subscribeCount) { + this.subscribeLatch = new CountDownLatch(subscribeCount); + this.deliveryLatch = new CountDownLatch(1); + } + + public MqttTestCallback(String awaitSubTopic) { + this.subscribeLatch = new CountDownLatch(1); + this.deliveryLatch = new CountDownLatch(1); + this.awaitSubTopic = awaitSubTopic; + } + + @Override + public void connectionLost(Throwable throwable) { + log.warn("connectionLost: ", throwable); + deliveryLatch.countDown(); + } + + @Override + public void messageArrived(String requestTopic, MqttMessage mqttMessage) { + if (awaitSubTopic == null) { + log.warn("messageArrived on topic: {}", requestTopic); + qoS = mqttMessage.getQos(); + payloadBytes = mqttMessage.getPayload(); + subscribeLatch.countDown(); + } else { + messageArrivedOnAwaitSubTopic(requestTopic, mqttMessage); + } + } + + protected void messageArrivedOnAwaitSubTopic(String requestTopic, MqttMessage mqttMessage) { + log.warn("messageArrived on topic: {}, awaitSubTopic: {}", requestTopic, awaitSubTopic); + if (awaitSubTopic.equals(requestTopic)) { + qoS = mqttMessage.getQos(); + payloadBytes = mqttMessage.getPayload(); + subscribeLatch.countDown(); + } + } + + @Override + public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { + log.warn("delivery complete: {}", iMqttDeliveryToken.getResponse()); + pubAckReceived = iMqttDeliveryToken.getResponse().getType() == MqttWireMessage.MESSAGE_TYPE_PUBACK; + deliveryLatch.countDown(); + + } +} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestClient.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestClient.java new file mode 100644 index 0000000000..96846f8678 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestClient.java @@ -0,0 +1,126 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.mqtt; + +import io.netty.handler.codec.mqtt.MqttQoS; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.IMqttToken; +import org.eclipse.paho.client.mqttv3.MqttAsyncClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; +import org.thingsboard.server.common.data.StringUtils; + +import java.util.concurrent.TimeUnit; + +public class MqttTestClient { + + private static final String MQTT_URL = "tcp://localhost:1883"; + private static final int TIMEOUT = 30; // seconds + private static final long TIMEOUT_MS = TimeUnit.SECONDS.toMillis(TIMEOUT); + + private final MqttAsyncClient client; + + public void setCallback(MqttTestCallback callback) { + client.setCallback(callback); + } + + public MqttTestClient() throws MqttException { + this.client = createClient(); + } + + public MqttTestClient(String clientId) throws MqttException { + this.client = createClient(clientId); + } + + public void connectAndWait(String userName, String password) throws MqttException { + IMqttToken connect = connect(userName, password); + connect.waitForCompletion(TIMEOUT_MS); + } + + public void connectAndWait(String userName) throws MqttException { + connectAndWait(userName, null); + } + + public void connectAndWait() throws MqttException { + connectAndWait(null, null); + } + + private IMqttToken connect(String userName, String password) throws MqttException { + if (client == null) { + throw new RuntimeException("Failed to connect! MqttAsyncClient is not initialized!"); + } + MqttConnectOptions options = new MqttConnectOptions(); + if (StringUtils.isNotEmpty(userName)) { + options.setUserName(userName); + } + if (StringUtils.isNotEmpty(password)) { + options.setPassword(password.toCharArray()); + } + return client.connect(options); + } + + public void disconnectAndWait() throws MqttException { + disconnect().waitForCompletion(TIMEOUT_MS); + } + + public IMqttToken disconnect() throws MqttException { + return client.disconnect(); + } + + public void disconnectForcibly() throws MqttException { + client.disconnectForcibly(TIMEOUT_MS); + } + + public void publishAndWait(String topic, byte[] payload) throws MqttException { + publish(topic, payload).waitForCompletion(TIMEOUT_MS); + } + + public IMqttDeliveryToken publish(String topic, byte[] payload) throws MqttException { + MqttMessage message = new MqttMessage(); + message.setPayload(payload); + return client.publish(topic, message); + } + + public void subscribeAndWait(String topic, MqttQoS qoS) throws MqttException { + subscribe(topic, qoS).waitForCompletion(TIMEOUT_MS); + } + + public IMqttToken subscribe(String topic, MqttQoS qoS) throws MqttException { + return client.subscribe(topic, qoS.value()); + } + + public void enableManualAcks() { + client.setManualAcks(true); + } + + public void messageArrivedComplete(MqttMessage mqttMessage) throws MqttException { + client.messageArrivedComplete(mqttMessage.getId(), mqttMessage.getQos()); + } + + private MqttAsyncClient createClient(String clientId) throws MqttException { + if (StringUtils.isEmpty(clientId)) { + clientId = MqttAsyncClient.generateClientId(); + } + return new MqttAsyncClient(MQTT_URL, clientId, new MemoryPersistence()); + } + + private MqttAsyncClient createClient() throws MqttException { + return createClient(null); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestConfigProperties.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestConfigProperties.java new file mode 100644 index 0000000000..bc535b424b --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/MqttTestConfigProperties.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.mqtt; + +import lombok.Builder; +import lombok.Data; +import org.thingsboard.server.common.data.DeviceProfileProvisionType; +import org.thingsboard.server.common.data.TransportPayloadType; + +@Data +@Builder +public class MqttTestConfigProperties { + + String deviceName; + String gatewayName; + + TransportPayloadType transportPayloadType; + + String telemetryTopicFilter; + String attributesTopicFilter; + + String telemetryProtoSchema; + String attributesProtoSchema; + String rpcResponseProtoSchema; + String rpcRequestProtoSchema; + + boolean enableCompatibilityWithJsonPayloadFormat; + boolean useJsonPayloadFormatForDefaultDownlinkTopics; + boolean sendAckOnValidationException; + + DeviceProfileProvisionType provisionType; + String provisionKey; + String provisionSecret; + +} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/AbstractMqttAttributesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/AbstractMqttAttributesIntegrationTest.java index 8d2dce0bb9..6d030aca9f 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/AbstractMqttAttributesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/AbstractMqttAttributesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,35 +22,44 @@ import com.google.protobuf.InvalidProtocolBufferException; import com.squareup.wire.schema.internal.parser.ProtoFileElement; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttCallback; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.springframework.test.context.TestPropertySource; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.query.DeviceTypeFilter; +import org.thingsboard.server.common.data.query.EntityData; +import org.thingsboard.server.common.data.query.EntityKey; +import org.thingsboard.server.common.data.query.EntityKeyType; +import org.thingsboard.server.common.data.query.SingleEntityFilter; import org.thingsboard.server.gen.transport.TransportApiProtos; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.service.telemetry.cmd.v2.EntityDataUpdate; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_ATTRIBUTES_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_CONNECT_TOPIC; +import static org.thingsboard.server.common.data.query.EntityKeyType.CLIENT_ATTRIBUTE; +import static org.thingsboard.server.common.data.query.EntityKeyType.SHARED_ATTRIBUTE; @Slf4j public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqttIntegrationTest { @@ -60,11 +69,11 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt "package test;\n" + "\n" + "message PostAttributes {\n" + - " string attribute1 = 1;\n" + - " bool attribute2 = 2;\n" + - " double attribute3 = 3;\n" + - " int32 attribute4 = 4;\n" + - " JsonObject attribute5 = 5;\n" + + " string clientStr = 1;\n" + + " bool clientBool = 2;\n" + + " double clientDbl = 3;\n" + + " int32 clientLong = 4;\n" + + " JsonObject clientJson = 5;\n" + "\n" + " message JsonObject {\n" + " int32 someNumber = 6;\n" + @@ -76,25 +85,20 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt " }\n" + "}"; - protected static final String POST_ATTRIBUTES_PAYLOAD = "{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73," + - "\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}"; + private static final String CLIENT_ATTRIBUTES_PAYLOAD = "{\"clientStr\":\"value1\",\"clientBool\":true,\"clientDbl\":42.0,\"clientLong\":73," + + "\"clientJson\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}"; - private static final String RESPONSE_ATTRIBUTES_PAYLOAD_DELETED = "{\"deleted\":[\"attribute5\"]}"; + private static final String SHARED_ATTRIBUTES_PAYLOAD = "{\"sharedStr\":\"value1\",\"sharedBool\":true,\"sharedDbl\":42.0,\"sharedLong\":73," + + "\"sharedJson\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}"; - protected void processBeforeTest(String deviceName, String gatewayName, TransportPayloadType payloadType, String telemetryTopic, String attributesTopic) throws Exception { - super.processBeforeTest(deviceName, gatewayName, payloadType, telemetryTopic, attributesTopic); - } - - protected void processAfterTest() throws Exception { - super.processAfterTest(); - } + private static final String SHARED_ATTRIBUTES_DELETED_RESPONSE = "{\"deleted\":[\"sharedJson\"]}"; - protected List getTsKvProtoList() { - TransportProtos.TsKvProto tsKvProtoAttribute1 = getTsKvProto("attribute1", "value1", TransportProtos.KeyValueType.STRING_V); - TransportProtos.TsKvProto tsKvProtoAttribute2 = getTsKvProto("attribute2", "true", TransportProtos.KeyValueType.BOOLEAN_V); - TransportProtos.TsKvProto tsKvProtoAttribute3 = getTsKvProto("attribute3", "42.0", TransportProtos.KeyValueType.DOUBLE_V); - TransportProtos.TsKvProto tsKvProtoAttribute4 = getTsKvProto("attribute4", "73", TransportProtos.KeyValueType.LONG_V); - TransportProtos.TsKvProto tsKvProtoAttribute5 = getTsKvProto("attribute5", "{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}", TransportProtos.KeyValueType.JSON_V); + private List getTsKvProtoList(String attributePrefix) { + TransportProtos.TsKvProto tsKvProtoAttribute1 = getTsKvProto(attributePrefix + "Str", "value1", TransportProtos.KeyValueType.STRING_V); + TransportProtos.TsKvProto tsKvProtoAttribute2 = getTsKvProto(attributePrefix + "Bool", "true", TransportProtos.KeyValueType.BOOLEAN_V); + TransportProtos.TsKvProto tsKvProtoAttribute3 = getTsKvProto(attributePrefix + "Dbl", "42.0", TransportProtos.KeyValueType.DOUBLE_V); + TransportProtos.TsKvProto tsKvProtoAttribute4 = getTsKvProto(attributePrefix + "Long", "73", TransportProtos.KeyValueType.LONG_V); + TransportProtos.TsKvProto tsKvProtoAttribute5 = getTsKvProto(attributePrefix + "Json", "{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}", TransportProtos.KeyValueType.JSON_V); List tsKvProtoList = new ArrayList<>(); tsKvProtoList.add(tsKvProtoAttribute1); tsKvProtoList.add(tsKvProtoAttribute2); @@ -111,118 +115,56 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt return tsKvProtoBuilder.build(); } - protected TestMqttCallback getTestMqttCallback() { - CountDownLatch latch = new CountDownLatch(1); - return new TestMqttCallback(latch); - } - - protected static class TestMqttCallback implements MqttCallback { - - private final CountDownLatch latch; - private Integer qoS; - private byte[] payloadBytes; - - TestMqttCallback(CountDownLatch latch) { - this.latch = latch; - } - - public int getQoS() { - return qoS; - } - - public byte[] getPayloadBytes() { - return payloadBytes; - } - - public CountDownLatch getLatch() { - return latch; - } - - @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - qoS = mqttMessage.getQos(); - payloadBytes = mqttMessage.getPayload(); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - - } - } - // subscribe to attributes updates from server methods protected void processJsonTestSubscribeToAttributesUpdates(String attrSubTopic) throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(accessToken); - - TestMqttCallback onUpdateCallback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback onUpdateCallback = new MqttTestCallback(); client.setCallback(onUpdateCallback); + client.subscribeAndWait(attrSubTopic, MqttQoS.AT_MOST_ONCE); - client.subscribe(attrSubTopic, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); - - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - onUpdateCallback.getLatch().await(3, TimeUnit.SECONDS); + doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + onUpdateCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); - validateUpdateAttributesJsonResponse(onUpdateCallback); + validateUpdateAttributesJsonResponse(onUpdateCallback, SHARED_ATTRIBUTES_PAYLOAD); - TestMqttCallback onDeleteCallback = getTestMqttCallback(); + MqttTestCallback onDeleteCallback = new MqttTestCallback(); client.setCallback(onDeleteCallback); - - doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=attribute5", String.class); - onDeleteCallback.getLatch().await(3, TimeUnit.SECONDS); - - validateDeleteAttributesJsonResponse(onDeleteCallback); + doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=sharedJson", String.class); + onDeleteCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + validateUpdateAttributesJsonResponse(onDeleteCallback, SHARED_ATTRIBUTES_DELETED_RESPONSE); + client.disconnect(); } protected void processProtoTestSubscribeToAttributesUpdates(String attrSubTopic) throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(accessToken); - - TestMqttCallback onUpdateCallback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback onUpdateCallback = new MqttTestCallback(); client.setCallback(onUpdateCallback); + client.subscribeAndWait(attrSubTopic, MqttQoS.AT_MOST_ONCE); - client.subscribe(attrSubTopic, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); - - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - onUpdateCallback.getLatch().await(3, TimeUnit.SECONDS); - + doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + onUpdateCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); validateUpdateAttributesProtoResponse(onUpdateCallback); - TestMqttCallback onDeleteCallback = getTestMqttCallback(); + MqttTestCallback onDeleteCallback = new MqttTestCallback(); client.setCallback(onDeleteCallback); - - doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=attribute5", String.class); - onDeleteCallback.getLatch().await(3, TimeUnit.SECONDS); - + doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=sharedJson", String.class); + onDeleteCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); validateDeleteAttributesProtoResponse(onDeleteCallback); + client.disconnect(); } - protected void validateUpdateAttributesJsonResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateUpdateAttributesJsonResponse(MqttTestCallback callback, String expectedResponse) { assertNotNull(callback.getPayloadBytes()); - String response = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); - assertEquals(JacksonUtil.toJsonNode(POST_ATTRIBUTES_PAYLOAD), JacksonUtil.toJsonNode(response)); + assertEquals(JacksonUtil.toJsonNode(expectedResponse), JacksonUtil.fromBytes(callback.getPayloadBytes())); } - protected void validateDeleteAttributesJsonResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { - assertNotNull(callback.getPayloadBytes()); - String response = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); - assertEquals(JacksonUtil.toJsonNode(RESPONSE_ATTRIBUTES_PAYLOAD_DELETED), JacksonUtil.toJsonNode(response)); - } - - protected void validateUpdateAttributesProtoResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateUpdateAttributesProtoResponse(MqttTestCallback callback) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); - List tsKvProtoList = getTsKvProtoList(); + List tsKvProtoList = getTsKvProtoList("shared"); attributeUpdateNotificationMsgBuilder.addAllSharedUpdated(tsKvProtoList); TransportProtos.AttributeUpdateNotificationMsg expectedAttributeUpdateNotificationMsg = attributeUpdateNotificationMsgBuilder.build(); @@ -235,134 +177,99 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt assertTrue(actualSharedUpdatedList.containsAll(expectedSharedUpdatedList)); } - protected void validateDeleteAttributesProtoResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateDeleteAttributesProtoResponse(MqttTestCallback callback) throws InvalidProtocolBufferException { assertNotNull(callback.getPayloadBytes()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); - attributeUpdateNotificationMsgBuilder.addSharedDeleted("attribute5"); + attributeUpdateNotificationMsgBuilder.addSharedDeleted("sharedJson"); TransportProtos.AttributeUpdateNotificationMsg expectedAttributeUpdateNotificationMsg = attributeUpdateNotificationMsgBuilder.build(); TransportProtos.AttributeUpdateNotificationMsg actualAttributeUpdateNotificationMsg = TransportProtos.AttributeUpdateNotificationMsg.parseFrom(callback.getPayloadBytes()); assertEquals(expectedAttributeUpdateNotificationMsg.getSharedDeletedList().size(), actualAttributeUpdateNotificationMsg.getSharedDeletedList().size()); - assertEquals("attribute5", actualAttributeUpdateNotificationMsg.getSharedDeletedList().get(0)); + assertEquals("sharedJson", actualAttributeUpdateNotificationMsg.getSharedDeletedList().get(0)); } protected void processJsonGatewayTestSubscribeToAttributesUpdates() throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - - TestMqttCallback onUpdateCallback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback onUpdateCallback = new MqttTestCallback(); client.setCallback(onUpdateCallback); - Device device = new Device(); - device.setName("Gateway Device Subscribe to attribute updates"); - device.setType("default"); + String deviceName = "Gateway Device Subscribe to attribute updates"; + byte[] connectPayloadBytes = getJsonConnectPayloadBytes(deviceName, deviceProfile.getTransportType().name()); - byte[] connectPayloadBytes = getJsonConnectPayloadBytes(); + client.publishAndWait(GATEWAY_CONNECT_TOPIC, connectPayloadBytes); - publishMqttMsg(client, connectPayloadBytes, MqttTopics.GATEWAY_CONNECT_TOPIC); - - Device savedDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + "Gateway Device Subscribe to attribute updates", Device.class), + Device savedDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), 20, 100); assertNotNull(savedDevice); - client.subscribe(MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); + client.subscribeAndWait(GATEWAY_ATTRIBUTES_TOPIC, MqttQoS.AT_MOST_ONCE); - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - onUpdateCallback.getLatch().await(3, TimeUnit.SECONDS); + doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + onUpdateCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); - validateJsonGatewayUpdateAttributesResponse(onUpdateCallback); + validateJsonGatewayUpdateAttributesResponse(onUpdateCallback, deviceName, SHARED_ATTRIBUTES_PAYLOAD); - TestMqttCallback onDeleteCallback = getTestMqttCallback(); + MqttTestCallback onDeleteCallback = new MqttTestCallback(); client.setCallback(onDeleteCallback); - doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=attribute5", String.class); - onDeleteCallback.getLatch().await(3, TimeUnit.SECONDS); - - validateJsonGatewayDeleteAttributesResponse(onDeleteCallback); + doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=sharedJson", String.class); + onDeleteCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + validateJsonGatewayUpdateAttributesResponse(onDeleteCallback, deviceName, SHARED_ATTRIBUTES_DELETED_RESPONSE); + client.disconnect(); } protected void processProtoGatewayTestSubscribeToAttributesUpdates() throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - - TestMqttCallback onUpdateCallback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback onUpdateCallback = new MqttTestCallback(); client.setCallback(onUpdateCallback); - - Device device = new Device(); - device.setName("Gateway Device Subscribe to attribute updates"); - device.setType("default"); - - byte[] connectPayloadBytes = getProtoConnectPayloadBytes(); - - publishMqttMsg(client, connectPayloadBytes, MqttTopics.GATEWAY_CONNECT_TOPIC); - - Device savedDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + "Gateway Device Subscribe to attribute updates", Device.class), + String deviceName = "Gateway Device Subscribe to attribute updates"; + byte[] connectPayloadBytes = getProtoConnectPayloadBytes(deviceName, TransportPayloadType.PROTOBUF.name()); + client.publishAndWait(GATEWAY_CONNECT_TOPIC, connectPayloadBytes); + Device device = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), 20, 100); - - assertNotNull(savedDevice); - - client.subscribe(MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); - - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - onUpdateCallback.getLatch().await(3, TimeUnit.SECONDS); - - validateProtoGatewayUpdateAttributesResponse(onUpdateCallback); - - TestMqttCallback onDeleteCallback = getTestMqttCallback(); + assertNotNull(device); + client.subscribeAndWait(GATEWAY_ATTRIBUTES_TOPIC, MqttQoS.AT_MOST_ONCE); + doPostAsync("/api/plugins/telemetry/DEVICE/" + device.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + validateProtoGatewayUpdateAttributesResponse(onUpdateCallback, deviceName); + MqttTestCallback onDeleteCallback = new MqttTestCallback(); client.setCallback(onDeleteCallback); - - doDelete("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/SHARED_SCOPE?keys=attribute5", String.class); - onDeleteCallback.getLatch().await(3, TimeUnit.SECONDS); - - validateProtoGatewayDeleteAttributesResponse(onDeleteCallback); - - } - - protected void validateJsonGatewayUpdateAttributesResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { - assertNotNull(callback.getPayloadBytes()); - String s = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); - assertEquals(getJsonResponseGatewayAttributesUpdatedPayload(), s); + doDelete("/api/plugins/telemetry/DEVICE/" + device.getId().getId() + "/SHARED_SCOPE?keys=sharedJson", String.class); + validateProtoGatewayDeleteAttributesResponse(onDeleteCallback, deviceName); + client.disconnect(); } - protected void validateJsonGatewayDeleteAttributesResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateJsonGatewayUpdateAttributesResponse(MqttTestCallback callback, String deviceName, String expectResultData) { assertNotNull(callback.getPayloadBytes()); - String s = new String(callback.getPayloadBytes(), StandardCharsets.UTF_8); - assertEquals(s, getJsonResponseGatewayAttributesDeletedPayload()); + assertEquals(JacksonUtil.toJsonNode(getGatewayAttributesResponseJson(deviceName, expectResultData)), JacksonUtil.fromBytes(callback.getPayloadBytes())); } - protected byte[] getJsonConnectPayloadBytes() { - String connectPayload = "{\"device\": \"Gateway Device Subscribe to attribute updates\", \"type\": \"" + TransportPayloadType.JSON.name() + "\"}"; + protected byte[] getJsonConnectPayloadBytes(String deviceName, String deviceType) { + String connectPayload = "{\"device\":\"" + deviceName + "\", \"type\": \"" + deviceType + "\"}"; return connectPayload.getBytes(); } - private static String getJsonResponseGatewayAttributesUpdatedPayload() { - return "{\"device\":\"" + "Gateway Device Subscribe to attribute updates" + "\"," + - "\"data\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}}"; - } - - private static String getJsonResponseGatewayAttributesDeletedPayload() { - return "{\"device\":\"" + "Gateway Device Subscribe to attribute updates" + "\",\"data\":{\"deleted\":[\"attribute5\"]}}"; + private static String getGatewayAttributesResponseJson(String deviceName, String expectResultData) { + return "{\"device\":\"" + deviceName + "\"," + "\"data\":" + expectResultData + "}"; } - protected void validateProtoGatewayUpdateAttributesResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateProtoGatewayUpdateAttributesResponse(MqttTestCallback callback, String deviceName) throws InvalidProtocolBufferException, InterruptedException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertNotNull(callback.getPayloadBytes()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); - List tsKvProtoList = getTsKvProtoList(); + List tsKvProtoList = getTsKvProtoList("shared"); attributeUpdateNotificationMsgBuilder.addAllSharedUpdated(tsKvProtoList); TransportProtos.AttributeUpdateNotificationMsg expectedAttributeUpdateNotificationMsg = attributeUpdateNotificationMsgBuilder.build(); TransportApiProtos.GatewayAttributeUpdateNotificationMsg.Builder gatewayAttributeUpdateNotificationMsgBuilder = TransportApiProtos.GatewayAttributeUpdateNotificationMsg.newBuilder(); - gatewayAttributeUpdateNotificationMsgBuilder.setDeviceName("Gateway Device Subscribe to attribute updates"); + gatewayAttributeUpdateNotificationMsgBuilder.setDeviceName(deviceName); gatewayAttributeUpdateNotificationMsgBuilder.setNotificationMsg(expectedAttributeUpdateNotificationMsg); TransportApiProtos.GatewayAttributeUpdateNotificationMsg expectedGatewayAttributeUpdateNotificationMsg = gatewayAttributeUpdateNotificationMsgBuilder.build(); @@ -375,17 +282,17 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt assertEquals(expectedSharedUpdatedList.size(), actualSharedUpdatedList.size()); assertTrue(actualSharedUpdatedList.containsAll(expectedSharedUpdatedList)); - } - protected void validateProtoGatewayDeleteAttributesResponse(TestMqttCallback callback) throws InvalidProtocolBufferException { + protected void validateProtoGatewayDeleteAttributesResponse(MqttTestCallback callback, String deviceName) throws InvalidProtocolBufferException, InterruptedException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertNotNull(callback.getPayloadBytes()); TransportProtos.AttributeUpdateNotificationMsg.Builder attributeUpdateNotificationMsgBuilder = TransportProtos.AttributeUpdateNotificationMsg.newBuilder(); - attributeUpdateNotificationMsgBuilder.addSharedDeleted("attribute5"); + attributeUpdateNotificationMsgBuilder.addSharedDeleted("sharedJson"); TransportProtos.AttributeUpdateNotificationMsg attributeUpdateNotificationMsg = attributeUpdateNotificationMsgBuilder.build(); TransportApiProtos.GatewayAttributeUpdateNotificationMsg.Builder gatewayAttributeUpdateNotificationMsgBuilder = TransportApiProtos.GatewayAttributeUpdateNotificationMsg.newBuilder(); - gatewayAttributeUpdateNotificationMsgBuilder.setDeviceName("Gateway Device Subscribe to attribute updates"); + gatewayAttributeUpdateNotificationMsgBuilder.setDeviceName(deviceName); gatewayAttributeUpdateNotificationMsgBuilder.setNotificationMsg(attributeUpdateNotificationMsg); TransportApiProtos.GatewayAttributeUpdateNotificationMsg expectedGatewayAttributeUpdateNotificationMsg = gatewayAttributeUpdateNotificationMsgBuilder.build(); @@ -397,118 +304,190 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt TransportProtos.AttributeUpdateNotificationMsg actualAttributeUpdateNotificationMsg = actualGatewayAttributeUpdateNotificationMsg.getNotificationMsg(); assertEquals(expectedAttributeUpdateNotificationMsg.getSharedDeletedList().size(), actualAttributeUpdateNotificationMsg.getSharedDeletedList().size()); - assertEquals("attribute5", actualAttributeUpdateNotificationMsg.getSharedDeletedList().get(0)); - + assertEquals("sharedJson", actualAttributeUpdateNotificationMsg.getSharedDeletedList().get(0)); } - protected byte[] getProtoConnectPayloadBytes() { - TransportApiProtos.ConnectMsg connectProto = getConnectProto(); - return connectProto.toByteArray(); - } - - private TransportApiProtos.ConnectMsg getConnectProto() { - TransportApiProtos.ConnectMsg.Builder builder = TransportApiProtos.ConnectMsg.newBuilder(); - builder.setDeviceName("Gateway Device Subscribe to attribute updates"); - builder.setDeviceType(TransportPayloadType.PROTOBUF.name()); - return builder.build(); + private byte[] getProtoConnectPayloadBytes(String deviceName, String deviceType) { + TransportApiProtos.ConnectMsg connectMsg = TransportApiProtos.ConnectMsg.newBuilder() + .setDeviceName(deviceName) + .setDeviceType(deviceType) + .build(); + return connectMsg.toByteArray(); } // request attributes from server methods protected void processJsonTestRequestAttributesValuesFromTheServer(String attrPubTopic, String attrSubTopic, String attrReqTopicPrefix) throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(accessToken); - - postJsonAttributesAndSubscribeToTopic(savedDevice, client, attrPubTopic, attrSubTopic); - - Thread.sleep(5000); - - TestMqttCallback callback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + SingleEntityFilter dtf = new SingleEntityFilter(); + dtf.setSingleEntity(savedDevice.getId()); + String clientKeysStr = "clientStr,clientBool,clientDbl,clientLong,clientJson"; + String sharedKeysStr = "sharedStr,sharedBool,sharedDbl,sharedLong,sharedJson"; + List clientKeysList = List.of(clientKeysStr.split(",")); + List sharedKeysList = List.of(sharedKeysStr.split(",")); + List csKeys = getEntityKeys(clientKeysList, CLIENT_ATTRIBUTE); + List shKeys = getEntityKeys(sharedKeysList, SHARED_ATTRIBUTE); + List keys = new ArrayList<>(); + keys.addAll(csKeys); + keys.addAll(shKeys); + getWsClient().subscribeLatestUpdate(keys, dtf); + getWsClient().registerWaitForUpdate(2); + doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", + SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + client.publishAndWait(attrPubTopic, CLIENT_ATTRIBUTES_PAYLOAD.getBytes()); + client.subscribeAndWait(attrSubTopic, MqttQoS.AT_MOST_ONCE); + String update = getWsClient().waitForUpdate(); + assertThat(update).as("ws update received").isNotBlank(); + MqttTestCallback callback = new MqttTestCallback(attrSubTopic.replace("+", "1")); client.setCallback(callback); - - validateJsonResponse(client, callback.getLatch(), callback, attrReqTopicPrefix); + String payloadStr = "{\"clientKeys\":\"" + clientKeysStr + "\", \"sharedKeys\":\"" + sharedKeysStr + "\"}"; + client.publishAndWait(attrReqTopicPrefix + "1", payloadStr.getBytes()); + String expectedResponse = "{\"client\":" + CLIENT_ATTRIBUTES_PAYLOAD + ",\"shared\":" + SHARED_ATTRIBUTES_PAYLOAD + "}"; + validateJsonResponse(callback, expectedResponse); + client.disconnect(); } protected void processProtoTestRequestAttributesValuesFromTheServer(String attrPubTopic, String attrSubTopic, String attrReqTopicPrefix) throws Exception { - - MqttAsyncClient client = getMqttAsyncClient(accessToken); - - postProtoAttributesAndSubscribeToTopic(savedDevice, client, attrPubTopic, attrSubTopic); - - Thread.sleep(5000); - - TestMqttCallback callback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + DeviceTypeFilter dtf = new DeviceTypeFilter(savedDevice.getType(), savedDevice.getName()); + String clientKeysStr = "clientStr,clientBool,clientDbl,clientLong,clientJson"; + String sharedKeysStr = "sharedStr,sharedBool,sharedDbl,sharedLong,sharedJson"; + List clientKeysList = List.of(clientKeysStr.split(",")); + List sharedKeysList = List.of(sharedKeysStr.split(",")); + List csKeys = getEntityKeys(clientKeysList, CLIENT_ATTRIBUTE); + List shKeys = getEntityKeys(sharedKeysList, SHARED_ATTRIBUTE); + List keys = new ArrayList<>(); + keys.addAll(csKeys); + keys.addAll(shKeys); + getWsClient().subscribeLatestUpdate(keys, dtf); + getWsClient().registerWaitForUpdate(2); + doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + client.publishAndWait(attrPubTopic, getAttributesProtoPayloadBytes()); + client.subscribeAndWait(attrSubTopic, MqttQoS.AT_MOST_ONCE); + String update = getWsClient().waitForUpdate(); + assertThat(update).as("ws update received").isNotBlank(); + MqttTestCallback callback = new MqttTestCallback(attrSubTopic.replace("+", "1")); client.setCallback(callback); - - validateProtoResponse(client, callback.getLatch(), callback, attrReqTopicPrefix); + TransportApiProtos.AttributesRequest.Builder attributesRequestBuilder = TransportApiProtos.AttributesRequest.newBuilder(); + attributesRequestBuilder.setClientKeys(clientKeysStr); + attributesRequestBuilder.setSharedKeys(sharedKeysStr); + TransportApiProtos.AttributesRequest attributesRequest = attributesRequestBuilder.build(); + client.publishAndWait(attrReqTopicPrefix + "1", attributesRequest.toByteArray()); + validateProtoResponse(callback, getExpectedAttributeResponseMsg()); + client.disconnect(); } protected void processJsonTestGatewayRequestAttributesValuesFromTheServer() throws Exception { + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + String deviceName = "Gateway Device Request Attributes"; + String postClientAttributes = "{\"" + deviceName + "\":" + CLIENT_ATTRIBUTES_PAYLOAD + "}"; + client.publishAndWait(GATEWAY_ATTRIBUTES_TOPIC, postClientAttributes.getBytes()); - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - - postJsonGatewayDeviceClientAttributes(client); - - Device savedDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + "Gateway Device Request Attributes", Device.class), + Device device = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), 20, 100); - - assertNotNull(savedDevice); - - Thread.sleep(2000); - - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - - Thread.sleep(5000); - - client.subscribe(MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, MqttQoS.AT_LEAST_ONCE.value()).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - - TestMqttCallback clientAttributesCallback = getTestMqttCallback(); + assertNotNull(device); + + SingleEntityFilter dtf = new SingleEntityFilter(); + dtf.setSingleEntity(device.getId()); + String clientKeysStr = "clientStr,clientBool,clientDbl,clientLong,clientJson"; + String sharedKeysStr = "sharedStr,sharedBool,sharedDbl,sharedLong,sharedJson"; + List clientKeysList = List.of(clientKeysStr.split(",")); + List sharedKeysList = List.of(sharedKeysStr.split(",")); + List csKeys = getEntityKeys(clientKeysList, CLIENT_ATTRIBUTE); + List shKeys = getEntityKeys(sharedKeysList, SHARED_ATTRIBUTE); + List keys = new ArrayList<>(); + keys.addAll(csKeys); + keys.addAll(shKeys); + EntityDataUpdate initUpdate = getWsClient().subscribeLatestUpdate(keys, dtf); + assertNotNull(initUpdate); + PageData data = initUpdate.getData(); + assertNotNull(data); + assertFalse(data.getData().isEmpty()); + getWsClient().registerWaitForUpdate(); + + doPostAsync("/api/plugins/telemetry/DEVICE/" + device.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + String update = getWsClient().waitForUpdate(); + assertThat(update).as("ws update received").isNotBlank(); + + client.subscribeAndWait(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, MqttQoS.AT_LEAST_ONCE); + + MqttTestCallback clientAttributesCallback = new MqttTestCallback(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC); client.setCallback(clientAttributesCallback); - validateJsonClientResponseGateway(client, clientAttributesCallback); + String csKeysStr = "[\"clientStr\", \"clientBool\", \"clientDbl\", \"clientLong\", \"clientJson\"]"; + String csRequestPayloadStr = "{\"id\": 1, \"device\": \"" + deviceName + "\", \"client\": true, \"keys\": " + csKeysStr + "}"; + client.publishAndWait(GATEWAY_ATTRIBUTES_REQUEST_TOPIC, csRequestPayloadStr.getBytes()); + validateJsonResponseGateway(clientAttributesCallback, deviceName, CLIENT_ATTRIBUTES_PAYLOAD); - TestMqttCallback sharedAttributesCallback = getTestMqttCallback(); + MqttTestCallback sharedAttributesCallback = new MqttTestCallback(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC); client.setCallback(sharedAttributesCallback); - validateJsonSharedResponseGateway(client, sharedAttributesCallback); + String shKeysStr = "[\"sharedStr\", \"sharedBool\", \"sharedDbl\", \"sharedLong\", \"sharedJson\"]"; + String shRequestPayloadStr = "{\"id\": 1, \"device\": \"" + deviceName + "\", \"client\": false, \"keys\": " + shKeysStr + "}"; + client.publishAndWait(GATEWAY_ATTRIBUTES_REQUEST_TOPIC, shRequestPayloadStr.getBytes()); + validateJsonResponseGateway(sharedAttributesCallback, deviceName, SHARED_ATTRIBUTES_PAYLOAD); + + client.disconnect(); } protected void processProtoTestGatewayRequestAttributesValuesFromTheServer() throws Exception { + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + String deviceName = "Gateway Device Request Attributes"; + String clientKeysStr = "clientStr,clientBool,clientDbl,clientLong,clientJson"; + List clientKeysList = List.of(clientKeysStr.split(",")); + client.publishAndWait(GATEWAY_ATTRIBUTES_TOPIC, getProtoGatewayDeviceClientAttributesPayload(deviceName, clientKeysList)); - postProtoGatewayDeviceClientAttributes(client); - - Device savedDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + "Gateway Device Request Attributes", Device.class), + Device device = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), 20, 100); - - assertNotNull(savedDevice); - - Thread.sleep(2000); - - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - - Thread.sleep(5000); - - client.subscribe(MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, MqttQoS.AT_LEAST_ONCE.value()).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - - TestMqttCallback clientAttributesCallback = getTestMqttCallback(); + assertNotNull(device); + + SingleEntityFilter dtf = new SingleEntityFilter(); + dtf.setSingleEntity(device.getId()); + String sharedKeysStr = "sharedStr,sharedBool,sharedDbl,sharedLong,sharedJson"; + List sharedKeysList = List.of(sharedKeysStr.split(",")); + List csKeys = getEntityKeys(clientKeysList, CLIENT_ATTRIBUTE); + List shKeys = getEntityKeys(sharedKeysList, SHARED_ATTRIBUTE); + List keys = new ArrayList<>(); + keys.addAll(csKeys); + keys.addAll(shKeys); + EntityDataUpdate initUpdate = getWsClient().subscribeLatestUpdate(keys, dtf); + assertNotNull(initUpdate); + PageData data = initUpdate.getData(); + assertNotNull(data); + assertFalse(data.getData().isEmpty()); + getWsClient().registerWaitForUpdate(); + + doPostAsync("/api/plugins/telemetry/DEVICE/" + device.getId().getId() + "/attributes/SHARED_SCOPE", SHARED_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + String update = getWsClient().waitForUpdate(); + assertThat(update).as("ws update received").isNotBlank(); + + client.subscribeAndWait(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, MqttQoS.AT_LEAST_ONCE); + + MqttTestCallback clientAttributesCallback = new MqttTestCallback(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC); client.setCallback(clientAttributesCallback); - validateProtoClientResponseGateway(client, clientAttributesCallback); + TransportApiProtos.GatewayAttributesRequestMsg gatewayAttributesRequestMsg = getGatewayAttributesRequestMsg(deviceName, clientKeysList, true); + client.publishAndWait(GATEWAY_ATTRIBUTES_REQUEST_TOPIC, gatewayAttributesRequestMsg.toByteArray()); + validateProtoClientResponseGateway(clientAttributesCallback, deviceName); - TestMqttCallback sharedAttributesCallback = getTestMqttCallback(); + MqttTestCallback sharedAttributesCallback = new MqttTestCallback(GATEWAY_ATTRIBUTES_RESPONSE_TOPIC); client.setCallback(sharedAttributesCallback); - validateProtoSharedResponseGateway(client, sharedAttributesCallback); + gatewayAttributesRequestMsg = getGatewayAttributesRequestMsg(deviceName, sharedKeysList, false); + client.publishAndWait(GATEWAY_ATTRIBUTES_REQUEST_TOPIC, gatewayAttributesRequestMsg.toByteArray()); + validateProtoSharedResponseGateway(sharedAttributesCallback, deviceName); + + client.disconnect(); } - protected void postJsonAttributesAndSubscribeToTopic(Device savedDevice, MqttAsyncClient client, String attrPubTopic, String attrSubTopic) throws Exception { - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); - client.publish(attrPubTopic, new MqttMessage(POST_ATTRIBUTES_PAYLOAD.getBytes())).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - client.subscribe(attrSubTopic, MqttQoS.AT_MOST_ONCE.value()).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); + private List getEntityKeys(List keys, EntityKeyType scope) { + return keys.stream().map(key -> new EntityKey(scope, key)).collect(Collectors.toList()); } - protected void postProtoAttributesAndSubscribeToTopic(Device savedDevice, MqttAsyncClient client, String attrPubTopic, String attrSubTopic) throws Exception { - doPostAsync("/api/plugins/telemetry/DEVICE/" + savedDevice.getId().getId() + "/attributes/SHARED_SCOPE", AbstractMqttAttributesIntegrationTest.POST_ATTRIBUTES_PAYLOAD, String.class, status().isOk()); + private byte[] getAttributesProtoPayloadBytes() { DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); assertTrue(transportConfiguration instanceof MqttDeviceProfileTransportConfiguration); MqttDeviceProfileTransportConfiguration mqttTransportConfiguration = (MqttDeviceProfileTransportConfiguration) transportConfiguration; @@ -538,64 +517,39 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt Descriptors.Descriptor postAttributesMsgDescriptor = postAttributesBuilder.getDescriptorForType(); assertNotNull(postAttributesMsgDescriptor); DynamicMessage postAttributesMsg = postAttributesBuilder - .setField(postAttributesMsgDescriptor.findFieldByName("attribute1"), "value1") - .setField(postAttributesMsgDescriptor.findFieldByName("attribute2"), true) - .setField(postAttributesMsgDescriptor.findFieldByName("attribute3"), 42.0) - .setField(postAttributesMsgDescriptor.findFieldByName("attribute4"), 73) - .setField(postAttributesMsgDescriptor.findFieldByName("attribute5"), jsonObject) + .setField(postAttributesMsgDescriptor.findFieldByName("clientStr"), "value1") + .setField(postAttributesMsgDescriptor.findFieldByName("clientBool"), true) + .setField(postAttributesMsgDescriptor.findFieldByName("clientDbl"), 42.0) + .setField(postAttributesMsgDescriptor.findFieldByName("clientLong"), 73) + .setField(postAttributesMsgDescriptor.findFieldByName("clientJson"), jsonObject) .build(); - byte[] payload = postAttributesMsg.toByteArray(); - client.publish(attrPubTopic, new MqttMessage(payload)); - client.subscribe(attrSubTopic, MqttQoS.AT_MOST_ONCE.value()); + return postAttributesMsg.toByteArray(); } - protected void postJsonGatewayDeviceClientAttributes(MqttAsyncClient client) throws Exception { - String postClientAttributes = "{\"" + "Gateway Device Request Attributes" + "\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}}"; - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, new MqttMessage(postClientAttributes.getBytes())).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - } - - protected void postProtoGatewayDeviceClientAttributes(MqttAsyncClient client) throws Exception { - String keys = "attribute1,attribute2,attribute3,attribute4,attribute5"; - List expectedKeys = Arrays.asList(keys.split(",")); - TransportProtos.PostAttributeMsg postAttributeMsg = getPostAttributeMsg(expectedKeys); + protected byte[] getProtoGatewayDeviceClientAttributesPayload(String deviceName, List clientKeysList) { + TransportProtos.PostAttributeMsg postAttributeMsg = getPostAttributeMsg(clientKeysList); TransportApiProtos.AttributesMsg.Builder attributesMsgBuilder = TransportApiProtos.AttributesMsg.newBuilder(); - attributesMsgBuilder.setDeviceName("Gateway Device Request Attributes"); + attributesMsgBuilder.setDeviceName(deviceName); attributesMsgBuilder.setMsg(postAttributeMsg); TransportApiProtos.AttributesMsg attributesMsg = attributesMsgBuilder.build(); TransportApiProtos.GatewayAttributesMsg.Builder gatewayAttributeMsgBuilder = TransportApiProtos.GatewayAttributesMsg.newBuilder(); gatewayAttributeMsgBuilder.addMsg(attributesMsg); - byte[] bytes = gatewayAttributeMsgBuilder.build().toByteArray(); - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, new MqttMessage(bytes)); + return gatewayAttributeMsgBuilder.build().toByteArray(); } - protected void validateJsonResponse(MqttAsyncClient client, CountDownLatch latch, TestMqttCallback callback, String attrReqTopicPrefix) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String keys = "attribute1,attribute2,attribute3,attribute4,attribute5"; - String payloadStr = "{\"clientKeys\":\"" + keys + "\", \"sharedKeys\":\"" + keys + "\"}"; - MqttMessage mqttMessage = new MqttMessage(); - mqttMessage.setPayload(payloadStr.getBytes()); - client.publish(attrReqTopicPrefix + "1", mqttMessage).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - latch.await(1, TimeUnit.MINUTES); + protected void validateJsonResponse(MqttTestCallback callback, String expectedResponse) throws InterruptedException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); - String expectedRequestPayload = "{\"client\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}},\"shared\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}}"; - assertEquals(JacksonUtil.toJsonNode(expectedRequestPayload), JacksonUtil.toJsonNode(new String(callback.getPayloadBytes(), StandardCharsets.UTF_8))); + assertEquals(JacksonUtil.toJsonNode(expectedResponse), JacksonUtil.fromBytes(callback.getPayloadBytes())); } - protected void validateProtoResponse(MqttAsyncClient client, CountDownLatch latch, TestMqttCallback callback, String attrReqTopic) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String keys = "attribute1,attribute2,attribute3,attribute4,attribute5"; - TransportApiProtos.AttributesRequest.Builder attributesRequestBuilder = TransportApiProtos.AttributesRequest.newBuilder(); - attributesRequestBuilder.setClientKeys(keys); - attributesRequestBuilder.setSharedKeys(keys); - TransportApiProtos.AttributesRequest attributesRequest = attributesRequestBuilder.build(); - MqttMessage mqttMessage = new MqttMessage(); - mqttMessage.setPayload(attributesRequest.toByteArray()); - client.publish(attrReqTopic + "1", mqttMessage); - latch.await(3, TimeUnit.SECONDS); + protected void validateProtoResponse(MqttTestCallback callback, TransportProtos.GetAttributeResponseMsg expectedResponse) throws InterruptedException, InvalidProtocolBufferException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); - TransportProtos.GetAttributeResponseMsg expectedAttributesResponse = getExpectedAttributeResponseMsg(); TransportProtos.GetAttributeResponseMsg actualAttributesResponse = TransportProtos.GetAttributeResponseMsg.parseFrom(callback.getPayloadBytes()); - assertEquals(expectedAttributesResponse.getRequestId(), actualAttributesResponse.getRequestId()); - List expectedClientKeyValueProtos = expectedAttributesResponse.getClientAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); - List expectedSharedKeyValueProtos = expectedAttributesResponse.getSharedAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); + assertEquals(expectedResponse.getRequestId(), actualAttributesResponse.getRequestId()); + List expectedClientKeyValueProtos = expectedResponse.getClientAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); + List expectedSharedKeyValueProtos = expectedResponse.getSharedAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); List actualClientKeyValueProtos = actualAttributesResponse.getClientAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); List actualSharedKeyValueProtos = actualAttributesResponse.getSharedAttributeListList().stream().map(TransportProtos.TsKvProto::getKv).collect(Collectors.toList()); assertTrue(actualClientKeyValueProtos.containsAll(expectedClientKeyValueProtos)); @@ -604,42 +558,25 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt private TransportProtos.GetAttributeResponseMsg getExpectedAttributeResponseMsg() { TransportProtos.GetAttributeResponseMsg.Builder result = TransportProtos.GetAttributeResponseMsg.newBuilder(); - List tsKvProtoList = getTsKvProtoList(); - result.addAllClientAttributeList(tsKvProtoList); - result.addAllSharedAttributeList(tsKvProtoList); + List csTsKvProtoList = getTsKvProtoList("client"); + List shTsKvProtoList = getTsKvProtoList("shared"); + result.addAllClientAttributeList(csTsKvProtoList); + result.addAllSharedAttributeList(shTsKvProtoList); result.setRequestId(1); return result.build(); } - protected void validateJsonClientResponseGateway(MqttAsyncClient client, TestMqttCallback callback) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String payloadStr = "{\"id\": 1, \"device\": \"" + "Gateway Device Request Attributes" + "\", \"client\": true, \"keys\": [\"attribute1\", \"attribute2\", \"attribute3\", \"attribute4\", \"attribute5\"]}"; - MqttMessage mqttMessage = new MqttMessage(); - mqttMessage.setPayload(payloadStr.getBytes()); - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC, mqttMessage).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - callback.getLatch().await(1, TimeUnit.MINUTES); - assertEquals(MqttQoS.AT_LEAST_ONCE.value(), callback.getQoS()); - String expectedRequestPayload = "{\"id\":1,\"device\":\"" + "Gateway Device Request Attributes" + "\",\"values\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}}"; - assertEquals(JacksonUtil.toJsonNode(expectedRequestPayload), JacksonUtil.toJsonNode(new String(callback.getPayloadBytes(), StandardCharsets.UTF_8))); - } - - protected void validateJsonSharedResponseGateway(MqttAsyncClient client, TestMqttCallback callback) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String payloadStr = "{\"id\": 1, \"device\": \"" + "Gateway Device Request Attributes" + "\", \"client\": false, \"keys\": [\"attribute1\", \"attribute2\", \"attribute3\", \"attribute4\", \"attribute5\"]}"; - MqttMessage mqttMessage = new MqttMessage(); - mqttMessage.setPayload(payloadStr.getBytes()); - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC, mqttMessage).waitForCompletion(TimeUnit.MINUTES.toMillis(1)); - callback.getLatch().await(1, TimeUnit.MINUTES); + protected void validateJsonResponseGateway(MqttTestCallback callback, String deviceName, String expectedValues) throws InterruptedException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertEquals(MqttQoS.AT_LEAST_ONCE.value(), callback.getQoS()); - String expectedRequestPayload = "{\"id\":1,\"device\":\"" + "Gateway Device Request Attributes" + "\",\"values\":{\"attribute1\":\"value1\",\"attribute2\":true,\"attribute3\":42.0,\"attribute4\":73,\"attribute5\":{\"someNumber\":42,\"someArray\":[1,2,3],\"someNestedObject\":{\"key\":\"value\"}}}}"; - assertEquals(JacksonUtil.toJsonNode(expectedRequestPayload), JacksonUtil.toJsonNode(new String(callback.getPayloadBytes(), StandardCharsets.UTF_8))); + String expectedRequestPayload = "{\"id\":1,\"device\":\"" + deviceName + "\",\"values\":" + expectedValues + "}"; + assertEquals(JacksonUtil.toJsonNode(expectedRequestPayload), JacksonUtil.fromBytes(callback.getPayloadBytes())); } - protected void validateProtoClientResponseGateway(MqttAsyncClient client, AbstractMqttAttributesIntegrationTest.TestMqttCallback callback) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String keys = "attribute1,attribute2,attribute3,attribute4,attribute5"; - TransportApiProtos.GatewayAttributesRequestMsg gatewayAttributesRequestMsg = getGatewayAttributesRequestMsg(keys, true); - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC, new MqttMessage(gatewayAttributesRequestMsg.toByteArray())); - callback.getLatch().await(3, TimeUnit.SECONDS); + protected void validateProtoClientResponseGateway(MqttTestCallback callback, String deviceName) throws InterruptedException, InvalidProtocolBufferException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertEquals(MqttQoS.AT_LEAST_ONCE.value(), callback.getQoS()); - TransportApiProtos.GatewayAttributeResponseMsg expectedGatewayAttributeResponseMsg = getExpectedGatewayAttributeResponseMsg(true); + TransportApiProtos.GatewayAttributeResponseMsg expectedGatewayAttributeResponseMsg = getExpectedGatewayAttributeResponseMsg(deviceName, true); TransportApiProtos.GatewayAttributeResponseMsg actualGatewayAttributeResponseMsg = TransportApiProtos.GatewayAttributeResponseMsg.parseFrom(callback.getPayloadBytes()); assertEquals(expectedGatewayAttributeResponseMsg.getDeviceName(), actualGatewayAttributeResponseMsg.getDeviceName()); @@ -652,13 +589,10 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt assertTrue(actualClientKeyValueProtos.containsAll(expectedClientKeyValueProtos)); } - protected void validateProtoSharedResponseGateway(MqttAsyncClient client, AbstractMqttAttributesIntegrationTest.TestMqttCallback callback) throws MqttException, InterruptedException, InvalidProtocolBufferException { - String keys = "attribute1,attribute2,attribute3,attribute4,attribute5"; - TransportApiProtos.GatewayAttributesRequestMsg gatewayAttributesRequestMsg = getGatewayAttributesRequestMsg(keys, false); - client.publish(MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC, new MqttMessage(gatewayAttributesRequestMsg.toByteArray())); - callback.getLatch().await(3, TimeUnit.SECONDS); + protected void validateProtoSharedResponseGateway(MqttTestCallback callback, String deviceName) throws InterruptedException, InvalidProtocolBufferException { + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); assertEquals(MqttQoS.AT_LEAST_ONCE.value(), callback.getQoS()); - TransportApiProtos.GatewayAttributeResponseMsg expectedGatewayAttributeResponseMsg = getExpectedGatewayAttributeResponseMsg(false); + TransportApiProtos.GatewayAttributeResponseMsg expectedGatewayAttributeResponseMsg = getExpectedGatewayAttributeResponseMsg(deviceName, false); TransportApiProtos.GatewayAttributeResponseMsg actualGatewayAttributeResponseMsg = TransportApiProtos.GatewayAttributeResponseMsg.parseFrom(callback.getPayloadBytes()); assertEquals(expectedGatewayAttributeResponseMsg.getDeviceName(), actualGatewayAttributeResponseMsg.getDeviceName()); @@ -672,27 +606,26 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt assertTrue(actualSharedKeyValueProtos.containsAll(expectedSharedKeyValueProtos)); } - private TransportApiProtos.GatewayAttributeResponseMsg getExpectedGatewayAttributeResponseMsg(boolean client) { + private TransportApiProtos.GatewayAttributeResponseMsg getExpectedGatewayAttributeResponseMsg(String deviceName, boolean client) { TransportApiProtos.GatewayAttributeResponseMsg.Builder gatewayAttributeResponseMsg = TransportApiProtos.GatewayAttributeResponseMsg.newBuilder(); TransportProtos.GetAttributeResponseMsg.Builder getAttributeResponseMsgBuilder = TransportProtos.GetAttributeResponseMsg.newBuilder(); - List tsKvProtoList = getTsKvProtoList(); if (client) { - getAttributeResponseMsgBuilder.addAllClientAttributeList(tsKvProtoList); + getAttributeResponseMsgBuilder.addAllClientAttributeList(getTsKvProtoList("client")); } else { - getAttributeResponseMsgBuilder.addAllSharedAttributeList(tsKvProtoList); + getAttributeResponseMsgBuilder.addAllSharedAttributeList(getTsKvProtoList("shared")); } getAttributeResponseMsgBuilder.setRequestId(1); TransportProtos.GetAttributeResponseMsg getAttributeResponseMsg = getAttributeResponseMsgBuilder.build(); - gatewayAttributeResponseMsg.setDeviceName("Gateway Device Request Attributes"); + gatewayAttributeResponseMsg.setDeviceName(deviceName); gatewayAttributeResponseMsg.setResponseMsg(getAttributeResponseMsg); return gatewayAttributeResponseMsg.build(); } - private TransportApiProtos.GatewayAttributesRequestMsg getGatewayAttributesRequestMsg(String keys, boolean client) { + private TransportApiProtos.GatewayAttributesRequestMsg getGatewayAttributesRequestMsg(String deviceName, List keysList, boolean client) { return TransportApiProtos.GatewayAttributesRequestMsg.newBuilder() + .setDeviceName(deviceName) + .addAllKeys(keysList) .setClient(client) - .addAllKeys(Arrays.asList(keys.split(","))) - .setDeviceName("Gateway Device Request Attributes") .setId(1).build(); } } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java similarity index 57% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java index b905d91a17..2231cb89eb 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,62 +16,93 @@ package org.thingsboard.server.transport.mqtt.attributes.request; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Test; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; import java.util.ArrayList; import java.util.List; @Slf4j -public abstract class AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesIntegrationTest { - - @After - public void afterTest() throws Exception { - processAfterTest(); - } +@DaoSqlTest +public class MqttAttributesRequestBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Test public void testRequestAttributesValuesFromTheServerWithEnabledJsonCompatibility() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, true, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); processJsonTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerOnShortTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerGatewayWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", TransportPayloadType.PROTOBUF, null, null, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .gatewayName("Gateway Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); processProtoTestGatewayRequestAttributesValuesFromTheServer(); } @Test public void testRequestAttributesValuesFromTheServerOnShortJsonTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", TransportPayloadType.PROTOBUF, null, null, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); processJsonTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX); } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestIntegrationTest.java similarity index 77% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestIntegrationTest.java index 9bb6b45507..c4da6b3184 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,24 @@ package org.thingsboard.server.transport.mqtt.attributes.request; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; @Slf4j -public abstract class AbstractMqttAttributesRequestJsonIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesRequestIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Request attribute values from the server json", "Gateway Test Request attribute values from the server json", TransportPayloadType.JSON, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server") + .gatewayName("Gateway Test Request attribute values from the server") + .build(); + processBeforeTest(configProperties); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestJsonIntegrationTest.java similarity index 51% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestJsonIntegrationTest.java index ea3c797b27..a27c9391fd 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,53 +15,27 @@ */ package org.thingsboard.server.transport.mqtt.attributes.request; -import com.github.os72.protobuf.dynamic.DynamicSchema; -import com.google.protobuf.Descriptors; -import com.google.protobuf.DynamicMessage; -import com.google.protobuf.InvalidProtocolBufferException; -import com.squareup.wire.schema.internal.parser.ProtoFileElement; -import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; -import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; +import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.MqttTopics; -import org.thingsboard.common.util.JacksonUtil; -import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; -import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; -import org.thingsboard.server.gen.transport.TransportApiProtos; -import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @Slf4j -public abstract class AbstractMqttAttributesRequestIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesRequestJsonIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Request attribute values from the server", "Gateway Test Request attribute values from the server", null, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server json") + .gatewayName("Gateway Test Request attribute values from the server json") + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestProtoIntegrationTest.java similarity index 64% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestProtoIntegrationTest.java index 327819a8c5..d330cdbbaf 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/AbstractMqttAttributesRequestProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/MqttAttributesRequestProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,55 +16,71 @@ package org.thingsboard.server.transport.mqtt.attributes.request; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Test; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; import java.util.ArrayList; import java.util.List; @Slf4j -public abstract class AbstractMqttAttributesRequestProtoIntegrationTest extends AbstractMqttAttributesIntegrationTest { - - @After - public void afterTest() throws Exception { - processAfterTest(); - } +@DaoSqlTest +public class MqttAttributesRequestProtoIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Test public void testRequestAttributesValuesFromTheServer() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerOnShortTopic() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerOnShortProtoTopic() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", - TransportPayloadType.PROTOBUF, null, null, null, ATTRIBUTES_SCHEMA_STR, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesProtoSchema(ATTRIBUTES_SCHEMA_STR) + .build(); + processBeforeTest(configProperties); processProtoTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX); } @Test public void testRequestAttributesValuesFromTheServerGateway() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", TransportPayloadType.PROTOBUF, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .gatewayName("Gateway Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); processProtoTestGatewayRequestAttributesValuesFromTheServer(); } @Test public void testRequestAttributesValuesFromTheServerOnShortJsonTopic() throws Exception { - super.processBeforeTest("Test Request attribute values from the server proto", "Gateway Test Request attribute values from the server proto", TransportPayloadType.PROTOBUF, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Request attribute values from the server proto") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); processJsonTestRequestAttributesValuesFromTheServer(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX); } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java deleted file mode 100644 index 166d2d7b14..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestBackwardCompatibilityIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.request.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.request.AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest; - -@DaoSqlTest -public class MqttAttributesRequestBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesRequestBackwardCompatibilityIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestIntegrationTest.java deleted file mode 100644 index f56faeacac..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.request.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.request.AbstractMqttAttributesRequestIntegrationTest; - -@DaoSqlTest -public class MqttAttributesRequestIntegrationTest extends AbstractMqttAttributesRequestIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestJsonIntegrationTest.java deleted file mode 100644 index dbadaa4f1c..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestJsonIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.request.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.request.AbstractMqttAttributesRequestJsonIntegrationTest; - -@DaoSqlTest -public class MqttAttributesRequestJsonIntegrationTest extends AbstractMqttAttributesRequestJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestProtoIntegrationTest.java deleted file mode 100644 index e1b58b9a5b..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/request/sql/MqttAttributesRequestProtoIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.request.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.request.AbstractMqttAttributesRequestProtoIntegrationTest; - -@DaoSqlTest -public class MqttAttributesRequestProtoIntegrationTest extends AbstractMqttAttributesRequestProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java deleted file mode 100644 index a54bbe3688..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.updates; - -import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Test; -import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; -import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; - -@Slf4j -public abstract class AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesIntegrationTest { - - @After - public void afterTest() throws Exception { - processAfterTest(); - } - - @Test - public void testSubscribeToAttributesUpdatesFromServerWithEnabledJsonCompatibility() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, false); - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); - } - - @Test - public void testSubscribeToAttributesUpdatesFromServerWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, true); - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); - } - - @Test - public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, true); - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC); - } - - @Test - public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortJsonTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, true); - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); - } - - @Test - public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, true); - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC); - } - - @Test - public void testProtoSubscribeToAttributesUpdatesFromTheServerGatewayWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null, true, false); - processProtoGatewayTestSubscribeToAttributesUpdates(); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java new file mode 100644 index 0000000000..05253cd969 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java @@ -0,0 +1,104 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.mqtt.attributes.updates; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; +import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; + +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; + +@Slf4j +@DaoSqlTest +public class MqttAttributesUpdatesBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesIntegrationTest { + + @Test + public void testSubscribeToAttributesUpdatesFromServerWithEnabledJsonCompatibility() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + processBeforeTest(configProperties); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_TOPIC); + } + + @Test + public void testSubscribeToAttributesUpdatesFromServerWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_TOPIC); + } + + @Test + public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_TOPIC); + } + + @Test + public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortJsonTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); + } + + @Test + public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC); + } + + @Test + public void testProtoSubscribeToAttributesUpdatesFromTheServerGatewayWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .gatewayName("Gateway Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + super.processBeforeTest(configProperties); + processProtoGatewayTestSubscribeToAttributesUpdates(); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesIntegrationTest.java similarity index 54% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesIntegrationTest.java index 6973f7db8f..01a33c5b5c 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,39 +16,44 @@ package org.thingsboard.server.transport.mqtt.attributes.updates; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; + @Slf4j -public abstract class AbstractMqttAttributesUpdatesIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesUpdatesIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.JSON, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .gatewayName("Gateway Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServer() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_TOPIC); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServerOnShortTopic() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_TOPIC); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServerOnShortJsonTopic() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesJsonIntegrationTest.java similarity index 54% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesJsonIntegrationTest.java index 02dbe8e8a8..f35ce1e084 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,39 +16,44 @@ package org.thingsboard.server.transport.mqtt.attributes.updates; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; + @Slf4j -public abstract class AbstractMqttAttributesUpdatesJsonIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesUpdatesJsonIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.JSON, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .gatewayName("Gateway Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServer() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_TOPIC); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServerOnShortTopic() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_TOPIC); } @Test public void testJsonSubscribeToAttributesUpdatesFromTheServerOnShortJsonTopic() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesProtoIntegrationTest.java similarity index 52% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesProtoIntegrationTest.java index 5c0bc631bb..dc7e92a128 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/AbstractMqttAttributesUpdatesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/MqttAttributesUpdatesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,55 +15,51 @@ */ package org.thingsboard.server.transport.mqtt.attributes.updates; -import com.google.protobuf.InvalidProtocolBufferException; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; -import org.thingsboard.server.gen.transport.TransportApiProtos; -import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import org.thingsboard.server.transport.mqtt.attributes.AbstractMqttAttributesIntegrationTest; -import java.util.List; -import java.util.stream.Collectors; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; @Slf4j -public abstract class AbstractMqttAttributesUpdatesProtoIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesUpdatesProtoIntegrationTest extends AbstractMqttAttributesIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Subscribe to attribute updates", "Gateway Test Subscribe to attribute updates", TransportPayloadType.PROTOBUF, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Subscribe to attribute updates") + .gatewayName("Gateway Test Subscribe to attribute updates") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); } @Test public void testProtoSubscribeToAttributesUpdatesFromTheServer() throws Exception { - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_TOPIC); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_TOPIC); } @Test public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortTopic() throws Exception { - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_TOPIC); } @Test public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortJsonTopic() throws Exception { - processJsonTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); + processJsonTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC); } @Test public void testProtoSubscribeToAttributesUpdatesFromTheServerOnShortProtoTopic() throws Exception { - processProtoTestSubscribeToAttributesUpdates(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC); + processProtoTestSubscribeToAttributesUpdates(DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java deleted file mode 100644 index 94b0284ece..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesBackwardCompatibilityIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.updates.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.updates.AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest; - -@DaoSqlTest -public class MqttAttributesUpdatesBackwardCompatibilityIntegrationTest extends AbstractMqttAttributesUpdatesBackwardCompatibilityIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesIntegrationTest.java deleted file mode 100644 index fcc3dd0e92..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.updates.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.updates.AbstractMqttAttributesUpdatesIntegrationTest; - -@DaoSqlTest -public class MqttAttributesUpdatesIntegrationTest extends AbstractMqttAttributesUpdatesIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesJsonIntegrationTest.java deleted file mode 100644 index 51aaeb60d6..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesJsonIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.updates.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.updates.AbstractMqttAttributesUpdatesJsonIntegrationTest; - -@DaoSqlTest -public class MqttAttributesUpdatesJsonIntegrationTest extends AbstractMqttAttributesUpdatesJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesProtoIntegrationTest.java deleted file mode 100644 index 0139c7c547..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/attributes/updates/sql/MqttAttributesUpdatesProtoIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.attributes.updates.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.attributes.updates.AbstractMqttAttributesUpdatesProtoIntegrationTest; - -@DaoSqlTest -public class MqttAttributesUpdatesProtoIntegrationTest extends AbstractMqttAttributesUpdatesProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimBackwardCompatibilityDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimBackwardCompatibilityDeviceTest.java similarity index 66% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimBackwardCompatibilityDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimBackwardCompatibilityDeviceTest.java index 2c0fa6c877..e7670b5170 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimBackwardCompatibilityDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimBackwardCompatibilityDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,23 +16,29 @@ package org.thingsboard.server.transport.mqtt.claim; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; @Slf4j -public abstract class AbstractMqttClaimBackwardCompatibilityDeviceTest extends AbstractMqttClaimDeviceTest { +@DaoSqlTest +public class MqttClaimBackwardCompatibilityDeviceTest extends MqttClaimDeviceTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Claim device", "Test Claim gateway", TransportPayloadType.PROTOBUF, null, null, true, true); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Claim device") + .gatewayName("Test Claim gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } - @After - public void afterTest() throws Exception { super.afterTest(); } - @Test public void testGatewayClaimingDevice() throws Exception { processTestGatewayClaimingDevice("Test claiming gateway device Proto", false); diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimDeviceTest.java similarity index 83% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimDeviceTest.java index 996e460f22..df3ac12e45 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,30 @@ package org.thingsboard.server.transport.mqtt.claim; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.ClaimRequest; import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.User; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.dao.device.claim.ClaimResponse; import org.thingsboard.server.dao.device.claim.ClaimResult; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportApiProtos; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_CLAIM_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_CLAIM_TOPIC; @Slf4j -public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegrationTest { +@DaoSqlTest +public class MqttClaimDeviceTest extends AbstractMqttIntegrationTest { protected static final String CUSTOMER_USER_PASSWORD = "customerUser123!"; @@ -46,21 +48,25 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio @Before public void beforeTest() throws Exception { - super.processBeforeTest("Test Claim device", "Test Claim gateway", null, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Claim device") + .gatewayName("Test Claim gateway") + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } protected void createCustomerAndUser() throws Exception { Customer customer = new Customer(); - customer.setTenantId(savedTenant.getId()); + customer.setTenantId(tenantId); customer.setTitle("Test Claiming Customer"); savedCustomer = doPost("/api/customer", customer, Customer.class); assertNotNull(savedCustomer); - assertEquals(savedTenant.getId(), savedCustomer.getTenantId()); + assertEquals(tenantId, savedCustomer.getTenantId()); User user = new User(); user.setAuthority(Authority.CUSTOMER_USER); - user.setTenantId(savedTenant.getId()); + user.setTenantId(tenantId); user.setCustomerId(savedCustomer.getId()); user.setEmail("customer@thingsboard.org"); @@ -69,11 +75,6 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio assertEquals(customerAdmin.getCustomerId(), savedCustomer.getId()); } - @After - public void afterTest() throws Exception { - super.processAfterTest(); - } - @Test public void testClaimingDevice() throws Exception { processTestClaimingDevice(false); @@ -96,7 +97,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio protected void processTestClaimingDevice(boolean emptyPayload) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); byte[] payloadBytes; byte[] failurePayloadBytes; if (emptyPayload) { @@ -109,8 +111,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio validateClaimResponse(emptyPayload, client, payloadBytes, failurePayloadBytes); } - protected void validateClaimResponse(boolean emptyPayload, MqttAsyncClient client, byte[] payloadBytes, byte[] failurePayloadBytes) throws Exception { - client.publish(MqttTopics.DEVICE_CLAIM_TOPIC, new MqttMessage(failurePayloadBytes)); + protected void validateClaimResponse(boolean emptyPayload, MqttTestClient client, byte[] payloadBytes, byte[] failurePayloadBytes) throws Exception { + client.publishAndWait(DEVICE_CLAIM_TOPIC, failurePayloadBytes); loginUser(customerAdmin.getName(), CUSTOMER_USER_PASSWORD); ClaimRequest claimRequest; @@ -128,7 +130,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio assertEquals(claimResponse, ClaimResponse.FAILURE); - client.publish(MqttTopics.DEVICE_CLAIM_TOPIC, new MqttMessage(payloadBytes)); + client.publishAndWait(DEVICE_CLAIM_TOPIC, payloadBytes); + client.disconnect(); ClaimResult claimResult = doExecuteWithRetriesAndInterval( () -> doPostClaimAsync("/api/customer/device/" + savedDevice.getName() + "/claim", claimRequest, ClaimResult.class, status().isOk()), @@ -145,8 +148,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio assertEquals(claimResponse, ClaimResponse.CLAIMED); } - protected void validateGatewayClaimResponse(String deviceName, boolean emptyPayload, MqttAsyncClient client, byte[] failurePayloadBytes, byte[] payloadBytes) throws Exception { - client.publish(MqttTopics.GATEWAY_CLAIM_TOPIC, new MqttMessage(failurePayloadBytes)); + protected void validateGatewayClaimResponse(String deviceName, boolean emptyPayload, MqttTestClient client, byte[] failurePayloadBytes, byte[] payloadBytes) throws Exception { + client.publishAndWait(GATEWAY_CLAIM_TOPIC, failurePayloadBytes); Device savedDevice = doExecuteWithRetriesAndInterval( () -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), @@ -167,7 +170,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio ClaimResponse claimResponse = doPostClaimAsync("/api/customer/device/" + deviceName + "/claim", claimRequest, ClaimResponse.class, status().isBadRequest()); assertEquals(claimResponse, ClaimResponse.FAILURE); - client.publish(MqttTopics.GATEWAY_CLAIM_TOPIC, new MqttMessage(payloadBytes)); + client.publishAndWait(GATEWAY_CLAIM_TOPIC, payloadBytes); + client.disconnect(); ClaimResult claimResult = doExecuteWithRetriesAndInterval( () -> doPostClaimAsync("/api/customer/device/" + deviceName + "/claim", claimRequest, ClaimResult.class, status().isOk()), @@ -186,7 +190,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio } protected void processTestGatewayClaimingDevice(String deviceName, boolean emptyPayload) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); byte[] failurePayloadBytes; byte[] payloadBytes; String failurePayload; @@ -204,7 +209,8 @@ public abstract class AbstractMqttClaimDeviceTest extends AbstractMqttIntegratio } protected void processProtoTestGatewayClaimDevice(String deviceName, boolean emptyPayload) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); byte[] failurePayloadBytes; byte[] payloadBytes; if (emptyPayload) { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimJsonDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimJsonDeviceTest.java similarity index 72% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimJsonDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimJsonDeviceTest.java index 97e177aef5..05d4974f9d 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimJsonDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimJsonDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,27 @@ package org.thingsboard.server.transport.mqtt.claim; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; @Slf4j -public abstract class AbstractMqttClaimJsonDeviceTest extends AbstractMqttClaimDeviceTest { +@DaoSqlTest +public class MqttClaimJsonDeviceTest extends MqttClaimDeviceTest { @Before public void beforeTest() throws Exception { - super.processBeforeTest("Test Claim device", "Test Claim gateway", TransportPayloadType.JSON, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Claim device") + .gatewayName("Test Claim gateway") + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } - @After - public void afterTest() throws Exception { - super.afterTest(); - } - @Test public void testClaimingDevice() throws Exception { processTestClaimingDevice(false); diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimProtoDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimProtoDeviceTest.java similarity index 78% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimProtoDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimProtoDeviceTest.java index 5dc5bcf8be..89c8c5f231 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/AbstractMqttClaimProtoDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/MqttClaimProtoDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,29 @@ package org.thingsboard.server.transport.mqtt.claim; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportApiProtos; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; @Slf4j -public abstract class AbstractMqttClaimProtoDeviceTest extends AbstractMqttClaimDeviceTest { +@DaoSqlTest +public class MqttClaimProtoDeviceTest extends MqttClaimDeviceTest { @Before public void beforeTest() throws Exception { - processBeforeTest("Test Claim device", "Test Claim gateway", TransportPayloadType.PROTOBUF, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Claim device") + .gatewayName("Test Claim gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); createCustomerAndUser(); } - @After - public void afterTest() throws Exception { super.afterTest(); } - @Test public void testClaimingDevice() throws Exception { processTestClaimingDevice(false); @@ -56,7 +60,8 @@ public abstract class AbstractMqttClaimProtoDeviceTest extends AbstractMqttClaim } protected void processTestClaimingDevice(boolean emptyPayload) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); byte[] payloadBytes; if (emptyPayload) { payloadBytes = getClaimDevice(0, emptyPayload).toByteArray(); diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceBackwardCompatibilityTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceBackwardCompatibilityTest.java deleted file mode 100644 index 3135aa951c..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/claim/sql/MqttClaimDeviceBackwardCompatibilityTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.claim.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.claim.AbstractMqttClaimBackwardCompatibilityDeviceTest; -import org.thingsboard.server.transport.mqtt.claim.AbstractMqttClaimDeviceTest; - -@DaoSqlTest -public class MqttClaimDeviceBackwardCompatibilityTest extends AbstractMqttClaimBackwardCompatibilityDeviceTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/sql/BasicMqttCredentialsTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/BasicMqttCredentialsTest.java similarity index 67% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/sql/BasicMqttCredentialsTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/BasicMqttCredentialsTest.java index 6bb8949f73..8ef02a63dc 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/sql/BasicMqttCredentialsTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/credentials/BasicMqttCredentialsTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,31 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.mqtt.credentials.sql; +package org.thingsboard.server.transport.mqtt.credentials; import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.lang3.RandomStringUtils; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttConnectOptions; -import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttSecurityException; -import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; -import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.StringUtils; -import org.thingsboard.server.common.data.Tenant; -import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.device.credentials.BasicMqttCredentials; -import org.thingsboard.server.common.data.device.profile.MqttTopics; -import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestClient; import java.util.Arrays; import java.util.HashSet; @@ -48,6 +38,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_TOPIC; @DaoSqlTest public class BasicMqttCredentialsTest extends AbstractMqttIntegrationTest { @@ -68,21 +59,7 @@ public class BasicMqttCredentialsTest extends AbstractMqttIntegrationTest { @Before public void before() throws Exception { - loginSysAdmin(); - - Tenant tenant = new Tenant(); - tenant.setTitle("My tenant"); - savedTenant = doPost("/api/tenant", tenant, Tenant.class); - Assert.assertNotNull(savedTenant); - - tenantAdmin = new User(); - tenantAdmin.setAuthority(Authority.TENANT_ADMIN); - tenantAdmin.setTenantId(savedTenant.getId()); - tenantAdmin.setEmail("tenant" + atomicInteger.getAndIncrement() + "@thingsboard.org"); - tenantAdmin.setFirstName("Joe"); - tenantAdmin.setLastName("Downs"); - - tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); + loginTenantAdmin(); BasicMqttCredentials credValue = new BasicMqttCredentials(); credValue.setClientId(CLIENT_ID); @@ -112,33 +89,51 @@ public class BasicMqttCredentialsTest extends AbstractMqttIntegrationTest { @Test public void testCorrectCredentials() throws Exception { // Check that correct devices receive telemetry - testTelemetryIsDelivered(accessTokenDevice, getMqttAsyncClient(null, USER_NAME1, null)); - testTelemetryIsDelivered(clientIdDevice, getMqttAsyncClient(CLIENT_ID, null, null)); - testTelemetryIsDelivered(clientIdAndUserNameDevice1, getMqttAsyncClient(CLIENT_ID, USER_NAME1, null)); - testTelemetryIsDelivered(clientIdAndUserNameAndPasswordDevice2, getMqttAsyncClient(CLIENT_ID, USER_NAME2, PASSWORD)); + MqttTestClient mqttTestClient1 = new MqttTestClient(); + mqttTestClient1.connectAndWait(USER_NAME1); + + MqttTestClient mqttTestClient2 = new MqttTestClient(CLIENT_ID); + mqttTestClient2.connectAndWait(); + + MqttTestClient mqttTestClient3 = new MqttTestClient(CLIENT_ID); + mqttTestClient3.connectAndWait(USER_NAME1); + + MqttTestClient mqttTestClient4 = new MqttTestClient(CLIENT_ID); + mqttTestClient4.connectAndWait(USER_NAME2, PASSWORD); + + // Also correct. Random clientId and password, but matches access token + MqttTestClient mqttTestClient5 = new MqttTestClient(RandomStringUtils.randomAlphanumeric(10)); + mqttTestClient5.connectAndWait(USER_NAME2, RandomStringUtils.randomAlphanumeric(10)); + + testTelemetryIsDelivered(accessTokenDevice, mqttTestClient1); + testTelemetryIsDelivered(clientIdDevice, mqttTestClient2); + testTelemetryIsDelivered(clientIdAndUserNameDevice1, mqttTestClient3); + testTelemetryIsDelivered(clientIdAndUserNameAndPasswordDevice2, mqttTestClient4); // Also correct. Random clientId and password, but matches access token - testTelemetryIsDelivered(accessToken2Device, getMqttAsyncClient(RandomStringUtils.randomAlphanumeric(10), USER_NAME2, RandomStringUtils.randomAlphanumeric(10))); + testTelemetryIsDelivered(accessToken2Device, mqttTestClient5); } @Test(expected = MqttSecurityException.class) public void testCorrectClientIdAndUserNameButWrongPassword() throws Exception { // Not correct. Correct clientId and username, but wrong password - testTelemetryIsNotDelivered(clientIdAndUserNameAndPasswordDevice3, getMqttAsyncClient(CLIENT_ID, USER_NAME3, "WRONG PASSWORD")); + MqttTestClient mqttTestClient = new MqttTestClient(CLIENT_ID); + mqttTestClient.connectAndWait(USER_NAME3, "WRONG PASSWORD"); + testTelemetryIsNotDelivered(clientIdAndUserNameAndPasswordDevice3, mqttTestClient); } - private void testTelemetryIsDelivered(Device device, MqttAsyncClient client) throws Exception { + private void testTelemetryIsDelivered(Device device, MqttTestClient client) throws Exception { testTelemetryIsDelivered(device, client, true); } - private void testTelemetryIsNotDelivered(Device device, MqttAsyncClient client) throws Exception { + private void testTelemetryIsNotDelivered(Device device, MqttTestClient client) throws Exception { testTelemetryIsDelivered(device, client, false); } - private void testTelemetryIsDelivered(Device device, MqttAsyncClient client, boolean ok) throws Exception { + private void testTelemetryIsDelivered(Device device, MqttTestClient client, boolean ok) throws Exception { String randomKey = RandomStringUtils.randomAlphanumeric(10); List expectedKeys = Arrays.asList(randomKey); - publishMqttMsg(client, JacksonUtil.toString(JacksonUtil.newObjectNode().put(randomKey, true)).getBytes(), MqttTopics.DEVICE_TELEMETRY_TOPIC); + client.publishAndWait(DEVICE_TELEMETRY_TOPIC, JacksonUtil.toString(JacksonUtil.newObjectNode().put(randomKey, true)).getBytes()); String deviceId = device.getId().getId().toString(); @@ -165,29 +160,7 @@ public class BasicMqttCredentialsTest extends AbstractMqttIntegrationTest { } else { assertNull(actualKeys); } - client.disconnect().waitForCompletion(); - } - - @After - public void after() throws Exception { - processAfterTest(); - } - - protected MqttAsyncClient getMqttAsyncClient(String clientId, String username, String password) throws MqttException { - if (StringUtils.isEmpty(clientId)) { - clientId = MqttAsyncClient.generateClientId(); - } - MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, clientId, new MemoryPersistence()); - - MqttConnectOptions options = new MqttConnectOptions(); - if (StringUtils.isNotEmpty(username)) { - options.setUserName(username); - } - if (StringUtils.isNotEmpty(password)) { - options.setPassword(password.toCharArray()); - } - client.connect(options).waitForCompletion(); - return client; + client.disconnect(); } private Device createDevice(String deviceName, BasicMqttCredentials clientIdCredValue) throws Exception { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionJsonDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionJsonDeviceTest.java similarity index 50% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionJsonDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionJsonDeviceTest.java index 3ae3bea89a..0a06f99209 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionJsonDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionJsonDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,36 +15,36 @@ */ package org.thingsboard.server.transport.mqtt.provision; -import com.google.gson.JsonObject; +import com.fasterxml.jackson.databind.JsonNode; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttCallback; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.credentials.BasicMqttCredentials; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.msg.EncryptionUtil; -import org.thingsboard.server.common.transport.util.JsonUtils; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.provision.ProvisionResponseStatus; -import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC; + @Slf4j -public abstract class AbstractMqttProvisionJsonDeviceTest extends AbstractMqttIntegrationTest { +@DaoSqlTest +public class MqttProvisionJsonDeviceTest extends AbstractMqttIntegrationTest { @Autowired DeviceCredentialsService deviceCredentialsService; @@ -52,11 +52,6 @@ public abstract class AbstractMqttProvisionJsonDeviceTest extends AbstractMqttIn @Autowired DeviceService deviceService; - @After - public void afterTest() throws Exception { - super.processAfterTest(); - } - @Test public void testProvisioningDisabledDevice() throws Exception { processTestProvisioningDisabledDevice(); @@ -94,62 +89,96 @@ public abstract class AbstractMqttProvisionJsonDeviceTest extends AbstractMqttIn protected void processTestProvisioningDisabledDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); - byte[] result = createMqttClientAndPublish().getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - Assert.assertEquals("Provision data was not found!", response.get("errorMsg").getAsString()); - Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.get("status").getAsString()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.DISABLED) + .build(); + super.processBeforeTest(configProperties); + byte[] result = createMqttClientAndPublish(); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("errorMsg")); + Assert.assertTrue(response.hasNonNull("status")); + Assert.assertEquals("Provision data was not found!", response.get("errorMsg").asText()); + Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.get("status").asText()); } protected void processTestProvisioningCreateNewDeviceWithoutCredentials() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); - byte[] result = createMqttClientAndPublish().getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); + byte[] result = createMqttClientAndPublish(); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("credentialsType")); + Assert.assertTrue(response.hasNonNull("status")); + + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").asText()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").asText()); } protected void processTestProvisioningCreateNewDeviceWithAccessToken() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); String requestCredentials = ",\"credentialsType\": \"ACCESS_TOKEN\",\"token\": \"test_token\""; - byte[] result = createMqttClientAndPublish(requestCredentials).getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); + byte[] result = createMqttClientAndPublish(requestCredentials); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("credentialsType")); + Assert.assertTrue(response.hasNonNull("status")); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").asText()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), "ACCESS_TOKEN"); Assert.assertEquals(deviceCredentials.getCredentialsId(), "test_token"); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").asText()); } protected void processTestProvisioningCreateNewDeviceWithCert() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); String requestCredentials = ",\"credentialsType\": \"X509_CERTIFICATE\",\"hash\": \"testHash\""; - byte[] result = createMqttClientAndPublish(requestCredentials).getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); + byte[] result = createMqttClientAndPublish(requestCredentials); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("credentialsType")); + Assert.assertTrue(response.hasNonNull("status")); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").asText()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), "X509_CERTIFICATE"); String cert = EncryptionUtil.certTrimNewLines(deviceCredentials.getCredentialsValue()); @@ -158,23 +187,32 @@ public abstract class AbstractMqttProvisionJsonDeviceTest extends AbstractMqttIn Assert.assertEquals(deviceCredentials.getCredentialsId(), sha3Hash); Assert.assertEquals(deviceCredentials.getCredentialsValue(), "testHash"); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").asText()); } protected void processTestProvisioningCreateNewDeviceWithMqttBasic() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); String requestCredentials = ",\"credentialsType\": \"MQTT_BASIC\",\"clientId\": \"test_clientId\",\"username\": \"test_username\",\"password\": \"test_password\""; - byte[] result = createMqttClientAndPublish(requestCredentials).getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); + byte[] result = createMqttClientAndPublish(requestCredentials); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("credentialsType")); + Assert.assertTrue(response.hasNonNull("status")); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").asText()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), "MQTT_BASIC"); Assert.assertEquals(deviceCredentials.getCredentialsId(), EncryptionUtil.getSha3Hash("|", "test_clientId", "test_username")); @@ -184,88 +222,61 @@ public abstract class AbstractMqttProvisionJsonDeviceTest extends AbstractMqttIn mqttCredentials.setPassword("test_password"); Assert.assertEquals(deviceCredentials.getCredentialsValue(), JacksonUtil.toString(mqttCredentials)); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").asText()); } protected void processTestProvisioningCheckPreProvisionedDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES, false, false); - byte[] result = createMqttClientAndPublish().getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), savedDevice.getId()); - - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").getAsString()); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").getAsString()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); + byte[] result = createMqttClientAndPublish(); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("credentialsType")); + Assert.assertTrue(response.hasNonNull("status")); + + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); + + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.get("credentialsType").asText()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.get("status").asText()); } protected void processTestProvisioningWithBadKeyDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.JSON, null, null, null, null, null, null, "testProvisionKeyOrig", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES, false, false); - byte[] result = createMqttClientAndPublish().getPayloadBytes(); - JsonObject response = JsonUtils.parse(new String(result)).getAsJsonObject(); - Assert.assertEquals("Provision data was not found!", response.get("errorMsg").getAsString()); - Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.get("status").getAsString()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.JSON) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKeyOrig") + .provisionSecret("testProvisionSecret") + .build(); + super.processBeforeTest(configProperties); + byte[] result = createMqttClientAndPublish(); + JsonNode response = JacksonUtil.fromBytes(result); + Assert.assertTrue(response.hasNonNull("errorMsg")); + Assert.assertTrue(response.hasNonNull("status")); + Assert.assertEquals("Provision data was not found!", response.get("errorMsg").asText()); + Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.get("status").asText()); } - protected TestMqttCallback createMqttClientAndPublish() throws Exception { + protected byte[] createMqttClientAndPublish() throws Exception { return createMqttClientAndPublish(""); } - protected TestMqttCallback createMqttClientAndPublish(String deviceCredentials) throws Exception { + protected byte[] createMqttClientAndPublish(String deviceCredentials) throws Exception { String provisionRequestMsg = createTestProvisionMessage(deviceCredentials); - MqttAsyncClient client = getMqttAsyncClient("provision"); - TestMqttCallback onProvisionCallback = getTestMqttCallback(); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait("provision"); + MqttTestCallback onProvisionCallback = new MqttTestCallback(DEVICE_PROVISION_RESPONSE_TOPIC); client.setCallback(onProvisionCallback); - client.subscribe(MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - Thread.sleep(2000); - client.publish(MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC, new MqttMessage(provisionRequestMsg.getBytes())); - onProvisionCallback.getLatch().await(3, TimeUnit.SECONDS); - return onProvisionCallback; - } - - - protected TestMqttCallback getTestMqttCallback() { - CountDownLatch latch = new CountDownLatch(1); - return new TestMqttCallback(latch); - } - - - protected static class TestMqttCallback implements MqttCallback { - - private final CountDownLatch latch; - private Integer qoS; - private byte[] payloadBytes; - - TestMqttCallback(CountDownLatch latch) { - this.latch = latch; - } - - public int getQoS() { - return qoS; - } - - public byte[] getPayloadBytes() { - return payloadBytes; - } - - public CountDownLatch getLatch() { - return latch; - } - - @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - qoS = mqttMessage.getQos(); - payloadBytes = mqttMessage.getPayload(); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - - } + client.subscribe(DEVICE_PROVISION_RESPONSE_TOPIC, MqttQoS.AT_MOST_ONCE); + client.publishAndWait(DEVICE_PROVISION_REQUEST_TOPIC, provisionRequestMsg.getBytes()); + onProvisionCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + client.disconnect(); + return onProvisionCallback.getPayloadBytes(); } protected String createTestProvisionMessage(String deviceCredentials) { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionProtoDeviceTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionProtoDeviceTest.java similarity index 60% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionProtoDeviceTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionProtoDeviceTest.java index 27477a287a..9e61b69ebf 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/AbstractMqttProvisionProtoDeviceTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/MqttProvisionProtoDeviceTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,26 +17,21 @@ package org.thingsboard.server.transport.mqtt.provision; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttCallback; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.credentials.BasicMqttCredentials; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.msg.EncryptionUtil; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.provision.ProvisionResponseStatus; -import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportProtos.CredentialsDataProto; import org.thingsboard.server.gen.transport.TransportProtos.CredentialsType; import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceCredentialsMsg; @@ -46,12 +41,18 @@ import org.thingsboard.server.gen.transport.TransportProtos.ValidateBasicMqttCre import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceTokenRequestMsg; import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceX509CertRequestMsg; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC; + @Slf4j -public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttIntegrationTest { +@DaoSqlTest +public class MqttProvisionProtoDeviceTest extends AbstractMqttIntegrationTest { @Autowired DeviceCredentialsService deviceCredentialsService; @@ -59,11 +60,6 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI @Autowired DeviceService deviceService; - @After - public void afterTest() throws Exception { - super.processAfterTest(); - } - @Test public void testProvisioningDisabledDevice() throws Exception { processTestProvisioningDisabledDevice(); @@ -101,37 +97,59 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI protected void processTestProvisioningDisabledDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); - ProvisionDeviceResponseMsg result = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish().getPayloadBytes()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.DISABLED) + .build(); + processBeforeTest(configProperties); + ProvisionDeviceResponseMsg result = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish()); Assert.assertNotNull(result); - Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), result.getStatus().toString()); + Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), result.getStatus().name()); } protected void processTestProvisioningCreateNewDeviceWithoutCredentials() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish().getPayloadBytes()); - - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish()); + + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().toString()); + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().name()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().name()); } protected void processTestProvisioningCreateNewDeviceWithAccessToken() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null,null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); - CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder().setValidateDeviceTokenRequestMsg(ValidateDeviceTokenRequestMsg.newBuilder().setToken("test_token").build()).build(); - - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.ACCESS_TOKEN, requestCredentials)).getPayloadBytes()); - - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); + CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder() + .setValidateDeviceTokenRequestMsg(ValidateDeviceTokenRequestMsg.newBuilder().setToken("test_token").build()) + .build(); + + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom( + createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.ACCESS_TOKEN, requestCredentials))); + + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(deviceCredentials.getCredentialsType(), DeviceCredentialsType.ACCESS_TOKEN); @@ -140,16 +158,27 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI } protected void processTestProvisioningCreateNewDeviceWithCert() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); - CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder().setValidateDeviceX509CertRequestMsg(ValidateDeviceX509CertRequestMsg.newBuilder().setHash("testHash").build()).build(); - - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.X509_CERTIFICATE, requestCredentials)).getPayloadBytes()); - - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); + CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder() + .setValidateDeviceX509CertRequestMsg( + ValidateDeviceX509CertRequestMsg.newBuilder().setHash("testHash").build()) + .build(); + + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom( + createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.X509_CERTIFICATE, requestCredentials))); + + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(deviceCredentials.getCredentialsType(), DeviceCredentialsType.X509_CERTIFICATE); @@ -164,7 +193,14 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI } protected void processTestProvisioningCreateNewDeviceWithMqttBasic() throws Exception { - super.processBeforeTest("Test Provision device3", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device3") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.ALLOW_CREATE_NEW_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); CredentialsDataProto requestCredentials = CredentialsDataProto.newBuilder().setValidateBasicMqttCredRequestMsg( ValidateBasicMqttCredRequestMsg.newBuilder() .setClientId("test_clientId") @@ -173,13 +209,14 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI .build() ).build(); - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.MQTT_BASIC, requestCredentials)).getPayloadBytes()); + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom( + createMqttClientAndPublish(createTestsProvisionMessage(CredentialsType.MQTT_BASIC, requestCredentials))); - Device createdDevice = deviceService.findDeviceByTenantIdAndName(savedTenant.getTenantId(), "Test Provision device"); + Device createdDevice = deviceService.findDeviceByTenantIdAndName(tenantId, "Test Provision device"); Assert.assertNotNull(createdDevice); - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), createdDevice.getId()); + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, createdDevice.getId()); Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); Assert.assertEquals(deviceCredentials.getCredentialsType(), DeviceCredentialsType.MQTT_BASIC); @@ -195,81 +232,50 @@ public abstract class AbstractMqttProvisionProtoDeviceTest extends AbstractMqttI } protected void processTestProvisioningCheckPreProvisionedDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, "testProvisionKey", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES, false, false); - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish().getPayloadBytes()); - - DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(savedTenant.getTenantId(), savedDevice.getId()); - - Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().toString()); - Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().toString()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKey") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish()); + + DeviceCredentials deviceCredentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, savedDevice.getId()); + + Assert.assertEquals(deviceCredentials.getCredentialsType().name(), response.getCredentialsType().name()); + Assert.assertEquals(ProvisionResponseStatus.SUCCESS.name(), response.getStatus().name()); } protected void processTestProvisioningWithBadKeyDevice() throws Exception { - super.processBeforeTest("Test Provision device", "Test Provision gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, "testProvisionKeyOrig", "testProvisionSecret", DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES, false, false); - ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish().getPayloadBytes()); - Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.getStatus().toString()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Provision device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .provisionType(DeviceProfileProvisionType.CHECK_PRE_PROVISIONED_DEVICES) + .provisionKey("testProvisionKeyOrig") + .provisionSecret("testProvisionSecret") + .build(); + processBeforeTest(configProperties); + ProvisionDeviceResponseMsg response = ProvisionDeviceResponseMsg.parseFrom(createMqttClientAndPublish()); + Assert.assertEquals(ProvisionResponseStatus.NOT_FOUND.name(), response.getStatus().name()); } - protected TestMqttCallback createMqttClientAndPublish() throws Exception { + protected byte[] createMqttClientAndPublish() throws Exception { byte[] provisionRequestMsg = createTestProvisionMessage(); return createMqttClientAndPublish(provisionRequestMsg); } - protected TestMqttCallback createMqttClientAndPublish(byte[] provisionRequestMsg) throws Exception { - MqttAsyncClient client = getMqttAsyncClient("provision"); - TestMqttCallback onProvisionCallback = getTestMqttCallback(); + protected byte[] createMqttClientAndPublish(byte[] provisionRequestMsg) throws Exception { + MqttTestClient client = new MqttTestClient(); + client.connectAndWait("provision"); + MqttTestCallback onProvisionCallback = new MqttTestCallback(DEVICE_PROVISION_RESPONSE_TOPIC); client.setCallback(onProvisionCallback); - client.subscribe(MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - Thread.sleep(2000); - client.publish(MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC, new MqttMessage(provisionRequestMsg)); - onProvisionCallback.getLatch().await(3, TimeUnit.SECONDS); - return onProvisionCallback; - } - - - protected TestMqttCallback getTestMqttCallback() { - CountDownLatch latch = new CountDownLatch(1); - return new TestMqttCallback(latch); - } - - - protected static class TestMqttCallback implements MqttCallback { - - private final CountDownLatch latch; - private Integer qoS; - private byte[] payloadBytes; - - TestMqttCallback(CountDownLatch latch) { - this.latch = latch; - } - - public int getQoS() { - return qoS; - } - - public byte[] getPayloadBytes() { - return payloadBytes; - } - - public CountDownLatch getLatch() { - return latch; - } - - @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - qoS = mqttMessage.getQos(); - payloadBytes = mqttMessage.getPayload(); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - - } + client.subscribe(DEVICE_PROVISION_RESPONSE_TOPIC, MqttQoS.AT_MOST_ONCE); + client.publishAndWait(DEVICE_PROVISION_REQUEST_TOPIC, provisionRequestMsg); + onProvisionCallback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + client.disconnect(); + return onProvisionCallback.getPayloadBytes(); } protected byte[] createTestsProvisionMessage(CredentialsType credentialsType, CredentialsDataProto credentialsData) throws Exception { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceJsonTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceJsonTest.java deleted file mode 100644 index 5cb9ae345a..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceJsonTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.provision.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.provision.AbstractMqttProvisionJsonDeviceTest; - -@DaoSqlTest -public class MqttProvisionDeviceJsonTest extends AbstractMqttProvisionJsonDeviceTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceProtoTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceProtoTest.java deleted file mode 100644 index 1e32fab350..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/provision/sql/MqttProvisionDeviceProtoTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.provision.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.provision.AbstractMqttProvisionProtoDeviceTest; - -@DaoSqlTest -public class MqttProvisionDeviceProtoTest extends AbstractMqttProvisionProtoDeviceTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcBackwardCompatibilityIntegrationTest.java deleted file mode 100644 index f8b3949b60..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcBackwardCompatibilityIntegrationTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.rpc; - -import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; -import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; - -@Slf4j -public abstract class AbstractMqttServerSideRpcBackwardCompatibilityIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { - - @After - public void afterTest() throws Exception { - super.processAfterTest(); - } - - @Test - public void testServerMqttOneWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); - } - - @Test - public void testServerMqttOneWayRpcOnShortTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); - } - - @Test - public void testServerMqttOneWayRpcOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); - } - - @Test - public void testServerMqttTwoWayRpcWithEnabledJsonCompatibility() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, false); - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); - } - - @Test - public void testServerMqttTwoWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); - } - - @Test - public void testServerMqttTwoWayRpcOnShortTopic() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); - } - - @Test - public void testServerMqttTwoWayRpcOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); - } - - @Test - public void testServerMqttTwoWayRpcOnShortJsonTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); - } - - @Test - public void testGatewayServerMqttOneWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processProtoOneWayRpcTestGateway("Gateway Device OneWay RPC Proto"); - } - - @Test - public void testGatewayServerMqttTwoWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { - super.processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, true, true); - processProtoTwoWayRpcTestGateway("Gateway Device TwoWay RPC Proto"); - } - -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcIntegrationTest.java index 2d6a653264..0abd0f1d6c 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,37 +26,35 @@ import com.squareup.wire.schema.internal.parser.ProtoFileElement; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.junit.Assert; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceTransportType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; import org.thingsboard.server.gen.transport.TransportApiProtos; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.BASE_DEVICE_API_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.BASE_DEVICE_API_TOPIC_V2; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_CONNECT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_RPC_TOPIC; -/** - * @author Valerii Sosliuk - */ @Slf4j public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractMqttIntegrationTest { @@ -76,89 +74,96 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM private static final String DEVICE_RESPONSE = "{\"value1\":\"A\",\"value2\":\"B\"}"; - protected Long asyncContextTimeoutToUseRpcPlugin; - - protected void processBeforeTest(String deviceName, String gatewayName, TransportPayloadType payloadType, String telemetryTopic, String attributesTopic) throws Exception { - super.processBeforeTest(deviceName, gatewayName, payloadType, telemetryTopic, attributesTopic); - asyncContextTimeoutToUseRpcPlugin = 10000L; - } + protected static final Long asyncContextTimeoutToUseRpcPlugin = 10000L; protected void processOneWayRpcTest(String rpcSubTopic) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); - - CountDownLatch latch = new CountDownLatch(1); - TestOneWayMqttCallback callback = new TestOneWayMqttCallback(client, latch); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(rpcSubTopic.replace("+", "0")); client.setCallback(callback); - - client.subscribe(rpcSubTopic, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); + client.subscribeAndWait(rpcSubTopic, MqttQoS.AT_MOST_ONCE); String setGpioRequest = "{\"method\":\"setGpio\",\"params\":{\"pin\": \"23\",\"value\": 1}}"; - String deviceId = savedDevice.getId().getId().toString(); - String result = doPostAsync("/api/rpc/oneway/" + deviceId, setGpioRequest, String.class, status().isOk()); - Assert.assertTrue(StringUtils.isEmpty(result)); - latch.await(3, TimeUnit.SECONDS); + String result = doPostAsync("/api/rpc/oneway/" + savedDevice.getId(), setGpioRequest, String.class, status().isOk()); + assertTrue(StringUtils.isEmpty(result)); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + DeviceTransportType deviceTransportType = deviceProfile.getTransportType(); + if (deviceTransportType.equals(DeviceTransportType.MQTT)) { + DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); + assertTrue(transportConfiguration instanceof MqttDeviceProfileTransportConfiguration); + MqttDeviceProfileTransportConfiguration configuration = (MqttDeviceProfileTransportConfiguration) transportConfiguration; + TransportPayloadType transportPayloadType = configuration.getTransportPayloadTypeConfiguration().getTransportPayloadType(); + if (transportPayloadType.equals(TransportPayloadType.PROTOBUF)) { + // TODO: add correct validation of proto requests to device + assertTrue(callback.getPayloadBytes().length > 0); + } else { + assertEquals(JacksonUtil.toJsonNode(setGpioRequest), JacksonUtil.fromBytes(callback.getPayloadBytes())); + } + } else { + assertEquals(JacksonUtil.toJsonNode(setGpioRequest), JacksonUtil.fromBytes(callback.getPayloadBytes())); + } assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); + client.disconnect(); } protected void processJsonOneWayRpcTestGateway(String deviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); String payload = "{\"device\":\"" + deviceName + "\"}"; byte[] payloadBytes = payload.getBytes(); validateOneWayRpcGatewayResponse(deviceName, client, payloadBytes); + client.disconnect(); } protected void processJsonTwoWayRpcTest(String rpcSubTopic) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); - client.subscribe(rpcSubTopic, 1); - - CountDownLatch latch = new CountDownLatch(1); - TestJsonMqttCallback callback = new TestJsonMqttCallback(client, latch); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + client.subscribeAndWait(rpcSubTopic, MqttQoS.AT_LEAST_ONCE); + MqttTestRpcJsonCallback callback = new MqttTestRpcJsonCallback(client, rpcSubTopic.replace("+", "0")); client.setCallback(callback); - - Thread.sleep(1000); - String setGpioRequest = "{\"method\":\"setGpio\",\"params\":{\"pin\": \"26\",\"value\": 1}}"; - String deviceId = savedDevice.getId().getId().toString(); - - String result = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); - String expected = "{\"value1\":\"A\",\"value2\":\"B\"}"; - latch.await(3, TimeUnit.SECONDS); - Assert.assertEquals(expected, result); + String actualRpcResponse = doPostAsync("/api/rpc/twoway/" + savedDevice.getId(), setGpioRequest, String.class, status().isOk()); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + assertEquals(JacksonUtil.toJsonNode(setGpioRequest), JacksonUtil.fromBytes(callback.getPayloadBytes())); + assertEquals("{\"value1\":\"A\",\"value2\":\"B\"}", actualRpcResponse); + client.disconnect(); } protected void processProtoTwoWayRpcTest(String rpcSubTopic) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); - client.subscribe(rpcSubTopic, 1); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + client.subscribeAndWait(rpcSubTopic, MqttQoS.AT_LEAST_ONCE); - CountDownLatch latch = new CountDownLatch(1); - TestProtoMqttCallback callback = new TestProtoMqttCallback(client, latch); + MqttTestRpcProtoCallback callback = new MqttTestRpcProtoCallback(client, rpcSubTopic.replace("+", "0")); client.setCallback(callback); - Thread.sleep(1000); - String setGpioRequest = "{\"method\":\"setGpio\",\"params\":{\"pin\": \"26\",\"value\": 1}}"; String deviceId = savedDevice.getId().getId().toString(); - String result = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); - String expected = "{\"payload\":\"{\\\"value1\\\":\\\"A\\\",\\\"value2\\\":\\\"B\\\"}\"}"; - latch.await(3, TimeUnit.SECONDS); - Assert.assertEquals(expected, result); + String actualRpcResponse = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + // TODO: add correct validation of proto requests to device + assertTrue(callback.getPayloadBytes().length > 0); + assertEquals("{\"payload\":\"{\\\"value1\\\":\\\"A\\\",\\\"value2\\\":\\\"B\\\"}\"}", actualRpcResponse); + client.disconnect(); } protected void processProtoTwoWayRpcTestGateway(String deviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); TransportApiProtos.ConnectMsg connectMsgProto = getConnectProto(deviceName); byte[] payloadBytes = connectMsgProto.toByteArray(); validateProtoTwoWayRpcGatewayResponse(deviceName, client, payloadBytes); + client.disconnect(); } protected void processProtoOneWayRpcTestGateway(String deviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); TransportApiProtos.ConnectMsg connectMsgProto = getConnectProto(deviceName); byte[] payloadBytes = connectMsgProto.toByteArray(); validateOneWayRpcGatewayResponse(deviceName, client, payloadBytes); + client.disconnect(); } private TransportApiProtos.ConnectMsg getConnectProto(String deviceName) { @@ -183,29 +188,30 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM doPostAsync("/api/rpc/twoway/" + deviceId, JacksonUtil.toString(request), String.class, status().isOk()); } - MqttAsyncClient client = getMqttAsyncClient(accessToken); - client.setManualAcks(true); - CountDownLatch latch = new CountDownLatch(10); - TestSequenceMqttCallback callback = new TestSequenceMqttCallback(client, latch, result); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + client.enableManualAcks(); + MqttTestSequenceCallback callback = new MqttTestSequenceCallback(client, 10, result); client.setCallback(callback); - client.subscribe(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC, 1); + client.subscribeAndWait(DEVICE_RPC_REQUESTS_SUB_TOPIC, MqttQoS.AT_LEAST_ONCE); - latch.await(10, TimeUnit.SECONDS); - Assert.assertEquals(expected, result); + callback.getSubscribeLatch().await(10, TimeUnit.SECONDS); + assertEquals(expected, result); } protected void processJsonTwoWayRpcTestGateway(String deviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); String payload = "{\"device\":\"" + deviceName + "\"}"; byte[] payloadBytes = payload.getBytes(); validateJsonTwoWayRpcGatewayResponse(deviceName, client, payloadBytes); + client.disconnect(); } - protected void validateOneWayRpcGatewayResponse(String deviceName, MqttAsyncClient client, byte[] payloadBytes) throws Exception { - publishMqttMsg(client, payloadBytes, MqttTopics.GATEWAY_CONNECT_TOPIC); - + protected void validateOneWayRpcGatewayResponse(String deviceName, MqttTestClient client, byte[] connectPayloadBytes) throws Exception { + client.publish(GATEWAY_CONNECT_TOPIC, connectPayloadBytes); Device savedDevice = doExecuteWithRetriesAndInterval( () -> getDeviceByName(deviceName), 20, @@ -213,24 +219,45 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM ); assertNotNull(savedDevice); - CountDownLatch latch = new CountDownLatch(1); - TestOneWayMqttCallback callback = new TestOneWayMqttCallback(client, latch); + MqttTestCallback callback = new MqttTestCallback(GATEWAY_RPC_TOPIC); client.setCallback(callback); - - client.subscribe(MqttTopics.GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); - + client.subscribeAndWait(GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE); String setGpioRequest = "{\"method\": \"toggle_gpio\", \"params\": {\"pin\":1}}"; String deviceId = savedDevice.getId().getId().toString(); String result = doPostAsync("/api/rpc/oneway/" + deviceId, setGpioRequest, String.class, status().isOk()); - Assert.assertTrue(StringUtils.isEmpty(result)); - latch.await(3, TimeUnit.SECONDS); + assertTrue(StringUtils.isEmpty(result)); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + DeviceTransportType deviceTransportType = deviceProfile.getTransportType(); + if (deviceTransportType.equals(DeviceTransportType.MQTT)) { + DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); + assertTrue(transportConfiguration instanceof MqttDeviceProfileTransportConfiguration); + MqttDeviceProfileTransportConfiguration configuration = (MqttDeviceProfileTransportConfiguration) transportConfiguration; + TransportPayloadType transportPayloadType = configuration.getTransportPayloadTypeConfiguration().getTransportPayloadType(); + if (transportPayloadType.equals(TransportPayloadType.PROTOBUF)) { + // TODO: add correct validation of proto requests to device + assertTrue(callback.getPayloadBytes().length > 0); + } else { + JsonNode expectedJsonRequestData = getExpectedGatewayJsonRequestData(deviceName, setGpioRequest); + assertEquals(expectedJsonRequestData, JacksonUtil.fromBytes(callback.getPayloadBytes())); + } + } else { + JsonNode expectedJsonRequestData = getExpectedGatewayJsonRequestData(deviceName, setGpioRequest); + assertEquals(expectedJsonRequestData, JacksonUtil.fromBytes(callback.getPayloadBytes())); + } assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); } - protected void validateJsonTwoWayRpcGatewayResponse(String deviceName, MqttAsyncClient client, byte[] payloadBytes) throws Exception { - publishMqttMsg(client, payloadBytes, MqttTopics.GATEWAY_CONNECT_TOPIC); + private JsonNode getExpectedGatewayJsonRequestData(String deviceName, String requestStr) { + ObjectNode deviceData = (ObjectNode) JacksonUtil.toJsonNode(requestStr); + deviceData.put("id", 0); + ObjectNode expectedRequest = JacksonUtil.newObjectNode(); + expectedRequest.put("device", deviceName); + expectedRequest.set("data", deviceData); + return expectedRequest; + } + + protected void validateJsonTwoWayRpcGatewayResponse(String deviceName, MqttTestClient client, byte[] connectPayloadBytes) throws Exception { + client.publish(GATEWAY_CONNECT_TOPIC, connectPayloadBytes); Device savedDevice = doExecuteWithRetriesAndInterval( () -> getDeviceByName(deviceName), @@ -239,25 +266,21 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM ); assertNotNull(savedDevice); - CountDownLatch latch = new CountDownLatch(1); - TestJsonMqttCallback callback = new TestJsonMqttCallback(client, latch); + MqttTestRpcJsonCallback callback = new MqttTestRpcJsonCallback(client, GATEWAY_RPC_TOPIC); client.setCallback(callback); - - client.subscribe(MqttTopics.GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); + client.subscribeAndWait(GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE); String setGpioRequest = "{\"method\": \"toggle_gpio\", \"params\": {\"pin\":1}}"; String deviceId = savedDevice.getId().getId().toString(); - String result = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); - latch.await(3, TimeUnit.SECONDS); - String expected = "{\"success\":true}"; - assertEquals(expected, result); + String actualRpcResponse = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + log.warn("request payload: {}", JacksonUtil.fromBytes(callback.getPayloadBytes())); + assertEquals("{\"success\":true}", actualRpcResponse); assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); } - protected void validateProtoTwoWayRpcGatewayResponse(String deviceName, MqttAsyncClient client, byte[] payloadBytes) throws Exception { - publishMqttMsg(client, payloadBytes, MqttTopics.GATEWAY_CONNECT_TOPIC); + protected void validateProtoTwoWayRpcGatewayResponse(String deviceName, MqttTestClient client, byte[] connectPayloadBytes) throws Exception { + client.publish(GATEWAY_CONNECT_TOPIC, connectPayloadBytes); Device savedDevice = doExecuteWithRetriesAndInterval( () -> getDeviceByName(deviceName), @@ -266,20 +289,15 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM ); assertNotNull(savedDevice); - CountDownLatch latch = new CountDownLatch(1); - TestProtoMqttCallback callback = new TestProtoMqttCallback(client, latch); + MqttTestRpcProtoCallback callback = new MqttTestRpcProtoCallback(client, GATEWAY_RPC_TOPIC); client.setCallback(callback); - - client.subscribe(MqttTopics.GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE.value()); - - Thread.sleep(1000); + client.subscribeAndWait(GATEWAY_RPC_TOPIC, MqttQoS.AT_MOST_ONCE); String setGpioRequest = "{\"method\": \"toggle_gpio\", \"params\": {\"pin\":1}}"; String deviceId = savedDevice.getId().getId().toString(); - String result = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); - latch.await(3, TimeUnit.SECONDS); - String expected = "{\"success\":true}"; - assertEquals(expected, result); + String actualRpcResponse = doPostAsync("/api/rpc/twoway/" + deviceId, setGpioRequest, String.class, status().isOk()); + callback.getSubscribeLatch().await(3, TimeUnit.SECONDS); + assertEquals("{\"success\":true}", actualRpcResponse); assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); } @@ -287,132 +305,82 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM return doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class); } - protected MqttMessage processJsonMessageArrived(String requestTopic, MqttMessage mqttMessage) throws MqttException, InvalidProtocolBufferException { - MqttMessage message = new MqttMessage(); - if (requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC) || requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC_V2)) { - message.setPayload(DEVICE_RESPONSE.getBytes(StandardCharset.UTF_8)); + protected byte[] processJsonMessageArrived(String requestTopic, MqttMessage mqttMessage) { + if (requestTopic.startsWith(BASE_DEVICE_API_TOPIC) || requestTopic.startsWith(BASE_DEVICE_API_TOPIC_V2)) { + return DEVICE_RESPONSE.getBytes(StandardCharset.UTF_8); } else { JsonNode requestMsgNode = JacksonUtil.toJsonNode(new String(mqttMessage.getPayload(), StandardCharset.UTF_8)); String deviceName = requestMsgNode.get("device").asText(); int requestId = requestMsgNode.get("data").get("id").asInt(); - message.setPayload(("{\"device\": \"" + deviceName + "\", \"id\": " + requestId + ", \"data\": {\"success\": true}}").getBytes(StandardCharset.UTF_8)); - } - return message; - } - - protected class TestOneWayMqttCallback implements MqttCallback { - - private final MqttAsyncClient client; - private final CountDownLatch latch; - private Integer qoS; - - TestOneWayMqttCallback(MqttAsyncClient client, CountDownLatch latch) { - this.client = client; - this.latch = latch; - } - - int getQoS() { - return qoS; - } - - @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - log.info("Message Arrived: " + Arrays.toString(mqttMessage.getPayload())); - qoS = mqttMessage.getQos(); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - + String response = "{\"device\": \"" + deviceName + "\", \"id\": " + requestId + ", \"data\": {\"success\": true}}"; + return response.getBytes(StandardCharset.UTF_8); } } - protected class TestJsonMqttCallback implements MqttCallback { + protected class MqttTestRpcJsonCallback extends MqttTestCallback { - private final MqttAsyncClient client; - private final CountDownLatch latch; - private Integer qoS; + private final MqttTestClient client; - TestJsonMqttCallback(MqttAsyncClient client, CountDownLatch latch) { + public MqttTestRpcJsonCallback(MqttTestClient client, String awaitSubTopic) { + super(awaitSubTopic); this.client = client; - this.latch = latch; - } - - int getQoS() { - return qoS; } @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - log.info("Message Arrived: " + Arrays.toString(mqttMessage.getPayload())); - String responseTopic; - if (requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC_V2)) { - responseTopic = requestTopic.replace("req", "res"); - } else { - responseTopic = requestTopic.replace("request", "response"); + protected void messageArrivedOnAwaitSubTopic(String requestTopic, MqttMessage mqttMessage) { + log.warn("messageArrived on topic: {}, awaitSubTopic: {}", requestTopic, awaitSubTopic); + if (awaitSubTopic.equals(requestTopic)) { + qoS = mqttMessage.getQos(); + payloadBytes = mqttMessage.getPayload(); + String responseTopic; + if (requestTopic.startsWith(BASE_DEVICE_API_TOPIC_V2)) { + responseTopic = requestTopic.replace("req", "res"); + } else { + responseTopic = requestTopic.replace("request", "response"); + } + try { + client.publish(responseTopic, processJsonMessageArrived(requestTopic, mqttMessage)); + } catch (MqttException e) { + log.warn("Failed to publish response on topic: {} due to: ", responseTopic, e); + } + subscribeLatch.countDown(); } - qoS = mqttMessage.getQos(); - client.publish(responseTopic, processJsonMessageArrived(requestTopic, mqttMessage)); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - } } - protected class TestProtoMqttCallback implements MqttCallback { + protected class MqttTestRpcProtoCallback extends MqttTestCallback { - private final MqttAsyncClient client; - private final CountDownLatch latch; - private Integer qoS; + private final MqttTestClient client; - TestProtoMqttCallback(MqttAsyncClient client, CountDownLatch latch) { + public MqttTestRpcProtoCallback(MqttTestClient client, String awaitSubTopic) { + super(awaitSubTopic); this.client = client; - this.latch = latch; - } - - int getQoS() { - return qoS; - } - - @Override - public void connectionLost(Throwable throwable) { } @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - log.info("Message Arrived: " + Arrays.toString(mqttMessage.getPayload())); - String responseTopic; - if (requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC_V2)) { - responseTopic = requestTopic.replace("req", "res"); - } else { - responseTopic = requestTopic.replace("request", "response"); + protected void messageArrivedOnAwaitSubTopic(String requestTopic, MqttMessage mqttMessage) { + log.warn("messageArrived on topic: {}, awaitSubTopic: {}", requestTopic, awaitSubTopic); + if (awaitSubTopic.equals(requestTopic)) { + qoS = mqttMessage.getQos(); + payloadBytes = mqttMessage.getPayload(); + String responseTopic; + if (requestTopic.startsWith(BASE_DEVICE_API_TOPIC_V2)) { + responseTopic = requestTopic.replace("req", "res"); + } else { + responseTopic = requestTopic.replace("request", "response"); + } + try { + client.publish(responseTopic, processProtoMessageArrived(requestTopic, mqttMessage)); + } catch (Exception e) { + log.warn("Failed to publish response on topic: {} due to: ", responseTopic, e); + } + subscribeLatch.countDown(); } - qoS = mqttMessage.getQos(); - client.publish(responseTopic, processProtoMessageArrived(requestTopic, mqttMessage)); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - } } - protected MqttMessage processProtoMessageArrived(String requestTopic, MqttMessage mqttMessage) throws MqttException, InvalidProtocolBufferException { - MqttMessage message = new MqttMessage(); - if (requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC) || requestTopic.startsWith(MqttTopics.BASE_DEVICE_API_TOPIC_V2)) { + protected byte[] processProtoMessageArrived(String requestTopic, MqttMessage mqttMessage) throws MqttException, InvalidProtocolBufferException { + if (requestTopic.startsWith(BASE_DEVICE_API_TOPIC) || requestTopic.startsWith(BASE_DEVICE_API_TOPIC_V2)) { ProtoTransportPayloadConfiguration protoTransportPayloadConfiguration = getProtoTransportPayloadConfiguration(); ProtoFileElement rpcRequestProtoSchemaFile = protoTransportPayloadConfiguration.getTransportProtoSchema(RPC_REQUEST_PROTO_SCHEMA); DynamicSchema rpcRequestProtoSchema = protoTransportPayloadConfiguration.getDynamicSchema(rpcRequestProtoSchemaFile, ProtoTransportPayloadConfiguration.RPC_REQUEST_PROTO_SCHEMA); @@ -436,9 +404,9 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM DynamicMessage rpcResponseMsg = rpcResponseBuilder .setField(rpcResponseMsgDescriptor.findFieldByName("payload"), DEVICE_RESPONSE) .build(); - message.setPayload(rpcResponseMsg.toByteArray()); + return rpcResponseMsg.toByteArray(); } catch (InvalidProtocolBufferException e) { - log.warn("Command Response Ack Error, Invalid response received: ", e); + throw new RuntimeException("Command Response Ack Error, Invalid response received: ", e); } } else { TransportApiProtos.GatewayDeviceRpcRequestMsg msg = TransportApiProtos.GatewayDeviceRpcRequestMsg.parseFrom(mqttMessage.getPayload()); @@ -449,9 +417,8 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM .setId(requestId) .setData("{\"success\": true}") .build(); - message.setPayload(gatewayRpcResponseMsg.toByteArray()); + return gatewayRpcResponseMsg.toByteArray(); } - return message; } private ProtoTransportPayloadConfiguration getProtoTransportPayloadConfiguration() { @@ -463,37 +430,30 @@ public abstract class AbstractMqttServerSideRpcIntegrationTest extends AbstractM return (ProtoTransportPayloadConfiguration) transportPayloadTypeConfiguration; } - protected class TestSequenceMqttCallback implements MqttCallback { + protected class MqttTestSequenceCallback extends MqttTestCallback { - private final MqttAsyncClient client; - private final CountDownLatch latch; + private final MqttTestClient client; private final List expected; - TestSequenceMqttCallback(MqttAsyncClient client, CountDownLatch latch, List expected) { + MqttTestSequenceCallback(MqttTestClient client, int subscribeCount, List expected) { + super(subscribeCount); this.client = client; - this.latch = latch; this.expected = expected; } @Override - public void connectionLost(Throwable throwable) { - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) throws Exception { - log.info("Message Arrived: " + Arrays.toString(mqttMessage.getPayload())); + public void messageArrived(String requestTopic, MqttMessage mqttMessage) { + log.warn("messageArrived on topic: {}, awaitSubTopic: {}", requestTopic, awaitSubTopic); expected.add(new String(mqttMessage.getPayload())); String responseTopic = requestTopic.replace("request", "response"); - var qoS = mqttMessage.getQos(); - - client.messageArrivedComplete(mqttMessage.getId(), qoS); - client.publish(responseTopic, processJsonMessageArrived(requestTopic, mqttMessage)); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - + qoS = mqttMessage.getQos(); + try { + client.messageArrivedComplete(mqttMessage); + client.publish(responseTopic, processJsonMessageArrived(requestTopic, mqttMessage)); + } catch (MqttException e) { + log.warn("Failed to publish response on topic: {} due to: ", responseTopic, e); + } + subscribeLatch.countDown(); } } } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcBackwardCompatibilityIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcBackwardCompatibilityIntegrationTest.java new file mode 100644 index 0000000000..5fb123666f --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcBackwardCompatibilityIntegrationTest.java @@ -0,0 +1,162 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.thingsboard.server.transport.mqtt.rpc; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.thingsboard.server.common.data.TransportPayloadType; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; + +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC; + +@Slf4j +@DaoSqlTest +public class MqttServerSideRpcBackwardCompatibilityIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { + + @Test + public void testServerMqttOneWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + processBeforeTest(configProperties); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); + } + + @Test + public void testServerMqttOneWayRpcOnShortTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + } + + @Test + public void testServerMqttOneWayRpcOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); + } + + @Test + public void testServerMqttTwoWayRpcWithEnabledJsonCompatibility() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + super.processBeforeTest(configProperties); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); + } + + @Test + public void testServerMqttTwoWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); + } + + @Test + public void testServerMqttTwoWayRpcOnShortTopic() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .build(); + super.processBeforeTest(configProperties); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + } + + @Test + public void testServerMqttTwoWayRpcOnShortProtoTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); + } + + @Test + public void testServerMqttTwoWayRpcOnShortJsonTopicWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); + } + + @Test + public void testGatewayServerMqttOneWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .gatewayName("RPC test gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processProtoOneWayRpcTestGateway("Gateway Device OneWay RPC Proto"); + } + + @Test + public void testGatewayServerMqttTwoWayRpcWithEnabledJsonCompatibilityAndJsonDownlinks() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .gatewayName("RPC test gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .enableCompatibilityWithJsonPayloadFormat(true) + .useJsonPayloadFormatForDefaultDownlinkTopics(true) + .build(); + super.processBeforeTest(configProperties); + processProtoTwoWayRpcTestGateway("Gateway Device TwoWay RPC Proto"); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcDefaultIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcDefaultIntegrationTest.java similarity index 74% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcDefaultIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcDefaultIntegrationTest.java index fbb66e61c8..95e3b7fde3 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcDefaultIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcDefaultIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,29 +17,29 @@ package org.thingsboard.server.transport.mqtt.rpc; import com.datastax.oss.driver.api.core.uuid.Uuids; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.service.security.AccessValidator; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC; -/** - * @author Valerii Sosliuk - */ @Slf4j -public abstract class AbstractMqttServerSideRpcDefaultIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { +@DaoSqlTest +public class MqttServerSideRpcDefaultIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", "RPC test gateway", null, null, null); - } - - @After - public void afterTest() throws Exception { - super.processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .gatewayName("RPC test gateway") + .build(); + processBeforeTest(configProperties); } @Test @@ -82,32 +82,32 @@ public abstract class AbstractMqttServerSideRpcDefaultIntegrationTest extends Ab @Test public void testServerMqttOneWayRpc() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortJsonTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); } @Test public void testServerMqttTwoWayRpc() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortTopic() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortJsonTopic() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcJsonIntegrationTest.java similarity index 56% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcJsonIntegrationTest.java index 14098c6e2a..b3c3a994d1 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,54 +16,59 @@ package org.thingsboard.server.transport.mqtt.rpc; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; + +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC; @Slf4j -public abstract class AbstractMqttServerSideRpcJsonIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { +@DaoSqlTest +public class MqttServerSideRpcJsonIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.JSON, null, null); - } - - @After - public void afterTest() throws Exception { - super.processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .gatewayName("RPC test gateway") + .transportPayloadType(TransportPayloadType.JSON) + .build(); + processBeforeTest(configProperties); } @Test public void testServerMqttOneWayRpc() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortJsonTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); } @Test public void testServerMqttTwoWayRpc() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortTopic() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortJsonTopic() throws Exception { - processJsonTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); + processJsonTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC); } @Test @@ -77,10 +82,12 @@ public abstract class AbstractMqttServerSideRpcJsonIntegrationTest extends Abstr } protected void processJsonOneWayRpcTestGateway(String deviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); String payload = "{\"device\": \"" + deviceName + "\", \"type\": \"" + TransportPayloadType.JSON.name() + "\"}"; byte[] payloadBytes = payload.getBytes(); validateOneWayRpcGatewayResponse(deviceName, client, payloadBytes); + client.disconnect(); } } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcProtoIntegrationTest.java similarity index 54% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcProtoIntegrationTest.java index 30227dfe3b..e888f49ff4 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/AbstractMqttServerSideRpcProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/MqttServerSideRpcProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,54 +16,59 @@ package org.thingsboard.server.transport.mqtt.rpc; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; + +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC; @Slf4j -public abstract class AbstractMqttServerSideRpcProtoIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { +@DaoSqlTest +public class MqttServerSideRpcProtoIntegrationTest extends AbstractMqttServerSideRpcIntegrationTest { @Before public void beforeTest() throws Exception { - processBeforeTest("RPC test device", "RPC test gateway", TransportPayloadType.PROTOBUF, null, null, null, null, null, RPC_REQUEST_PROTO_SCHEMA, null, null, DeviceProfileProvisionType.DISABLED, false, false); - } - - @After - public void afterTest() throws Exception { - super.processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("RPC test device") + .gatewayName("RPC test gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .rpcRequestProtoSchema(RPC_REQUEST_PROTO_SCHEMA) + .build(); + processBeforeTest(configProperties); } @Test public void testServerMqttOneWayRpc() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttOneWayRpcOnShortProtoTopic() throws Exception { - processOneWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); + processOneWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); } @Test public void testServerMqttTwoWayRpc() throws Exception { - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortTopic() throws Exception { - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC); } @Test public void testServerMqttTwoWayRpcOnShortProtoTopic() throws Exception { - processProtoTwoWayRpcTest(MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); + processProtoTwoWayRpcTest(DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcIntegrationTest.java deleted file mode 100644 index b0438ca96b..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcIntegrationTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.rpc.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.rpc.AbstractMqttServerSideRpcDefaultIntegrationTest; - -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ -@DaoSqlTest -public class MqttServerSideRpcIntegrationTest extends AbstractMqttServerSideRpcDefaultIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcJsonIntegrationTest.java deleted file mode 100644 index 22eeea1624..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/rpc/sql/MqttServerSideRpcJsonIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.rpc.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.rpc.AbstractMqttServerSideRpcJsonIntegrationTest; - -@DaoSqlTest -public class MqttServerSideRpcJsonIntegrationTest extends AbstractMqttServerSideRpcJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesIntegrationTest.java similarity index 76% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesIntegrationTest.java index e6cf60fb2e..1d986d0453 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,14 +18,14 @@ package org.thingsboard.server.transport.mqtt.telemetry.attributes; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.HashSet; @@ -37,39 +37,43 @@ import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_ATTRIBUTES_TOPIC; @Slf4j -public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqttIntegrationTest { +@DaoSqlTest +public class MqttAttributesIntegrationTest extends AbstractMqttIntegrationTest { protected static final String PAYLOAD_VALUES_STR = "{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4," + " \"key5\": {\"someNumber\": 42, \"someArray\": [1,2,3], \"someNestedObject\": {\"key\": \"value\"}}}"; @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", null, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .gatewayName("Test Post Attributes gateway") + .build(); + processBeforeTest(configProperties); } @Test public void testPushAttributes() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); + processJsonPayloadAttributesTest(DEVICE_ATTRIBUTES_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); } @Test public void testPushAttributesOnShortTopic() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); + processJsonPayloadAttributesTest(DEVICE_ATTRIBUTES_SHORT_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); } @Test public void testPushAttributesOnShortJsonTopic() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); + processJsonPayloadAttributesTest(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes()); } @Test @@ -86,9 +90,11 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt } protected void processAttributesTest(String topic, List expectedKeys, byte[] payload, boolean presenceFieldsTest) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); - publishMqttMsg(client, payload, topic); + client.publishAndWait(topic, payload); + client.disconnect(); DeviceId deviceId = savedDevice.getId(); @@ -124,9 +130,11 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt } protected void processGatewayAttributesTest(List expectedKeys, byte[] payload, String firstDeviceName, String secondDeviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); - publishMqttMsg(client, payload, MqttTopics.GATEWAY_ATTRIBUTES_TOPIC); + client.publishAndWait(GATEWAY_ATTRIBUTES_TOPIC, payload); + client.disconnect(); Device firstDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + firstDeviceName, Device.class), 20, @@ -140,12 +148,12 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt assertNotNull(secondDevice); - Thread.sleep(2000); - - List firstDeviceActualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + firstDevice.getId() + "/keys/attributes/CLIENT_SCOPE", new TypeReference<>() {}); + List firstDeviceActualKeys = getActualKeysList(firstDevice.getId(), expectedKeys); + assertNotNull(firstDeviceActualKeys); Set firstDeviceActualKeySet = new HashSet<>(firstDeviceActualKeys); - List secondDeviceActualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + secondDevice.getId() + "/keys/attributes/CLIENT_SCOPE", new TypeReference<>() {}); + List secondDeviceActualKeys = getActualKeysList(secondDevice.getId(), expectedKeys); + assertNotNull(secondDeviceActualKeys); Set secondDeviceActualKeySet = new HashSet<>(secondDeviceActualKeys); Set expectedKeySet = new HashSet<>(expectedKeys); @@ -164,6 +172,21 @@ public abstract class AbstractMqttAttributesIntegrationTest extends AbstractMqtt } + private List getActualKeysList(DeviceId deviceId, List expectedKeys) throws Exception { + long start = System.currentTimeMillis(); + long end = System.currentTimeMillis() + 3000; + List firstDeviceActualKeys = null; + while (start <= end) { + firstDeviceActualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + deviceId + "/keys/attributes/CLIENT_SCOPE", new TypeReference<>() {}); + if (firstDeviceActualKeys.size() == expectedKeys.size()) { + break; + } + Thread.sleep(100); + start += 100; + } + return firstDeviceActualKeys; + } + @SuppressWarnings("unchecked") protected void assertAttributesValues(List> deviceValues, Set keySet) throws JsonProcessingException { for (Map map : deviceValues) { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesJsonIntegrationTest.java similarity index 70% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesJsonIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesJsonIntegrationTest.java index 9530bb2449..f77885c0fd 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,30 @@ package org.thingsboard.server.transport.mqtt.telemetry.attributes; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.dao.service.DaoSqlTest; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.List; @Slf4j -public abstract class AbstractMqttAttributesJsonIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesJsonIntegrationTest extends MqttAttributesIntegrationTest { private static final String POST_DATA_ATTRIBUTES_TOPIC = "data/attributes"; @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.JSON, null, POST_DATA_ATTRIBUTES_TOPIC); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .gatewayName("Test Post Attributes gateway") + .transportPayloadType(TransportPayloadType.JSON) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); } @Test diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesProtoIntegrationTest.java similarity index 73% rename from application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesProtoIntegrationTest.java rename to application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesProtoIntegrationTest.java index 48467be27f..4904ed7a5d 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/AbstractMqttAttributesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/MqttAttributesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,20 +25,25 @@ import org.junit.Test; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; +import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.gen.transport.TransportApiProtos; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC; @Slf4j -public abstract class AbstractMqttAttributesProtoIntegrationTest extends AbstractMqttAttributesIntegrationTest { +@DaoSqlTest +public class MqttAttributesProtoIntegrationTest extends MqttAttributesIntegrationTest { private static final String POST_DATA_ATTRIBUTES_TOPIC = "proto/attributes"; @@ -50,20 +55,36 @@ public abstract class AbstractMqttAttributesProtoIntegrationTest extends Abstrac @Test public void testPushAttributes() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postAttributesMsg = getDefaultDynamicMessage(); processAttributesTest(POST_DATA_ATTRIBUTES_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postAttributesMsg.toByteArray(), false); } @Test public void testPushAttributesWithEnabledJsonBackwardCompatibility() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC, true, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + processBeforeTest(configProperties); processJsonPayloadAttributesTest(POST_DATA_ATTRIBUTES_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes()); } @Test public void testPushAttributesWithExplicitPresenceProtoKeys() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicSchema attributesSchema = getDynamicSchema(); DynamicMessage.Builder nestedJsonObjectBuilder = attributesSchema.newMessageBuilder("PostAttributes.JsonObject.NestedJsonObject"); @@ -96,27 +117,47 @@ public abstract class AbstractMqttAttributesProtoIntegrationTest extends Abstrac @Test public void testPushAttributesOnShortTopic() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postAttributesMsg = getDefaultDynamicMessage(); - processAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postAttributesMsg.toByteArray(), false); + processAttributesTest(DEVICE_ATTRIBUTES_SHORT_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postAttributesMsg.toByteArray(), false); } @Test public void testPushAttributesOnShortJsonTopic() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC); - processJsonPayloadAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes()); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); + processJsonPayloadAttributesTest(DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes()); } @Test public void testPushAttributesOnShortProtoTopic() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, POST_DATA_ATTRIBUTES_TOPIC); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .attributesTopicFilter(POST_DATA_ATTRIBUTES_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postAttributesMsg = getDefaultDynamicMessage(); - processAttributesTest(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postAttributesMsg.toByteArray(), false); + processAttributesTest(DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postAttributesMsg.toByteArray(), false); } @Test public void testPushAttributesGateway() throws Exception { - processBeforeTest("Test Post Attributes device", "Test Post Attributes gateway", TransportPayloadType.PROTOBUF, null, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Attributes device") + .gatewayName("Test Post Attributes gateway") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .build(); + processBeforeTest(configProperties); TransportApiProtos.GatewayAttributesMsg.Builder gatewayAttributesMsgProtoBuilder = TransportApiProtos.GatewayAttributesMsg.newBuilder(); List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); String deviceName1 = "Device A"; diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesIntegrationTest.java deleted file mode 100644 index 06f222f8a1..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.telemetry.attributes.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.telemetry.attributes.AbstractMqttAttributesIntegrationTest; - -@DaoSqlTest -public class MqttAttributesIntegrationTest extends AbstractMqttAttributesIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesJsonIntegrationTest.java deleted file mode 100644 index eefde6336c..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesJsonIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.telemetry.attributes.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.telemetry.attributes.AbstractMqttAttributesJsonIntegrationTest; - -@DaoSqlTest -public class MqttAttributesJsonIntegrationTest extends AbstractMqttAttributesJsonIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesProtoIntegrationTest.java deleted file mode 100644 index a976f54e35..0000000000 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/attributes/sql/MqttAttributesProtoIntegrationTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright © 2016-2021 The Thingsboard Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.thingsboard.server.transport.mqtt.telemetry.attributes.sql; - -import org.thingsboard.server.dao.service.DaoSqlTest; -import org.thingsboard.server.transport.mqtt.telemetry.attributes.AbstractMqttAttributesProtoIntegrationTest; - -@DaoSqlTest -public class MqttAttributesProtoIntegrationTest extends AbstractMqttAttributesProtoIntegrationTest { -} diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesIntegrationTest.java index d7b4cc553e..5bb0d28a21 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,31 +18,31 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries; import com.fasterxml.jackson.core.type.TypeReference; import io.netty.handler.codec.mqtt.MqttQoS; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.eclipse.paho.client.mqttv3.MqttCallback; -import org.eclipse.paho.client.mqttv3.MqttConnectOptions; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.transport.mqtt.AbstractMqttIntegrationTest; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_ATTRIBUTES_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_CONNECT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_TELEMETRY_TOPIC; @Slf4j public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqttIntegrationTest { @@ -50,39 +50,41 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt protected static final String PAYLOAD_VALUES_STR = "{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4," + " \"key5\": {\"someNumber\": 42, \"someArray\": [1,2,3], \"someNestedObject\": {\"key\": \"value\"}}}"; + protected static final String MALFORMED_JSON_PAYLOAD = "{\"key1\":, \"key2\":true, \"key3\": 3.0, \"key4\": 4," + + " \"key5\": {\"someNumber\": 42, \"someArray\": [1,2,3], \"someNestedObject\": {\"key\": \"value\"}}}"; + @Before public void beforeTest() throws Exception { - processBeforeTest("Test Post Telemetry device", "Test Post Telemetry gateway", null, null, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device") + .gatewayName("Test Post Telemetry gateway") + .build(); + processBeforeTest(configProperties); } @Test public void testPushTelemetry() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadTelemetryTest(MqttTopics.DEVICE_TELEMETRY_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); + processJsonPayloadTelemetryTest(DEVICE_TELEMETRY_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); } @Test public void testPushTelemetryWithTs() throws Exception { String payloadStr = "{\"ts\": 10000, \"values\": " + PAYLOAD_VALUES_STR + "}"; List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadTelemetryTest(MqttTopics.DEVICE_TELEMETRY_TOPIC, expectedKeys, payloadStr.getBytes(), true); + processJsonPayloadTelemetryTest(DEVICE_TELEMETRY_TOPIC, expectedKeys, payloadStr.getBytes(), true); } @Test public void testPushTelemetryOnShortTopic() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadTelemetryTest(MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); + processJsonPayloadTelemetryTest(DEVICE_TELEMETRY_SHORT_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); } @Test public void testPushTelemetryOnShortJsonTopic() throws Exception { List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); - processJsonPayloadTelemetryTest(MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); + processJsonPayloadTelemetryTest(DEVICE_TELEMETRY_SHORT_JSON_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); } @Test @@ -91,14 +93,15 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt String deviceName1 = "Device A"; String deviceName2 = "Device B"; String payload = getGatewayTelemetryJsonPayload(deviceName1, deviceName2, "10000", "20000"); - processGatewayTelemetryTest(MqttTopics.GATEWAY_TELEMETRY_TOPIC, expectedKeys, payload.getBytes(), deviceName1, deviceName2); + processGatewayTelemetryTest(GATEWAY_TELEMETRY_TOPIC, expectedKeys, payload.getBytes(), deviceName1, deviceName2); } @Test public void testGatewayConnect() throws Exception { String payload = "{\"device\":\"Device A\"}"; - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - publishMqttMsg(client, payload.getBytes(), MqttTopics.GATEWAY_CONNECT_TOPIC); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + client.publish(GATEWAY_CONNECT_TOPIC, payload.getBytes()); String deviceName = "Device A"; @@ -107,6 +110,7 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt 100); assertNotNull(device); + client.disconnect(); } protected void processJsonPayloadTelemetryTest(String topic, List expectedKeys, byte[] payload, boolean withTs) throws Exception { @@ -114,23 +118,14 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt } protected void processTelemetryTest(String topic, List expectedKeys, byte[] payload, boolean withTs, boolean presenceFieldsTest) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(accessToken); - publishMqttMsg(client, payload, topic); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + client.publishAndWait(topic, payload); + client.disconnect(); - String deviceId = savedDevice.getId().getId().toString(); - - long start = System.currentTimeMillis(); - long end = System.currentTimeMillis() + 5000; + DeviceId deviceId = savedDevice.getId(); - List actualKeys = null; - while (start <= end) { - actualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + deviceId + "/keys/timeseries", new TypeReference<>() {}); - if (actualKeys.size() == expectedKeys.size()) { - break; - } - Thread.sleep(100); - start += 100; - } + List actualKeys = getActualKeysList(deviceId, expectedKeys); assertNotNull(actualKeys); Set actualKeySet = new HashSet<>(actualKeys); @@ -144,8 +139,8 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt } else { getTelemetryValuesUrl = "/api/plugins/telemetry/DEVICE/" + deviceId + "/values/timeseries?keys=" + String.join(",", actualKeySet); } - start = System.currentTimeMillis(); - end = System.currentTimeMillis() + 5000; + long start = System.currentTimeMillis(); + long end = System.currentTimeMillis() + 5000; Map>> values = null; while (start <= end) { values = doGetAsyncTyped(getTelemetryValuesUrl, new TypeReference<>() {}); @@ -184,9 +179,10 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt } protected void processGatewayTelemetryTest(String topic, List expectedKeys, byte[] payload, String firstDeviceName, String secondDeviceName) throws Exception { - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - - publishMqttMsg(client, payload, topic); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + client.publishAndWait(topic, payload); + client.disconnect(); Device firstDevice = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + firstDeviceName, Device.class), 20, @@ -200,12 +196,10 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt assertNotNull(secondDevice); - Thread.sleep(2000); - - List firstDeviceActualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + firstDevice.getId() + "/keys/timeseries", new TypeReference<>() {}); + List firstDeviceActualKeys = getActualKeysList(firstDevice.getId(), expectedKeys); Set firstDeviceActualKeySet = new HashSet<>(firstDeviceActualKeys); - List secondDeviceActualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + secondDevice.getId() + "/keys/timeseries", new TypeReference<>() {}); + List secondDeviceActualKeys = getActualKeysList(secondDevice.getId(), expectedKeys); Set secondDeviceActualKeySet = new HashSet<>(secondDeviceActualKeys); Set expectedKeySet = new HashSet<>(expectedKeys); @@ -223,6 +217,22 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt assertGatewayDeviceData(secondDeviceValues, expectedKeys); } + private List getActualKeysList(DeviceId deviceId, List expectedKeys) throws Exception { + long start = System.currentTimeMillis(); + long end = System.currentTimeMillis() + 3000; + + List actualKeys = null; + while (start <= end) { + actualKeys = doGetAsyncTyped("/api/plugins/telemetry/DEVICE/" + deviceId + "/keys/timeseries", new TypeReference<>() {}); + if (actualKeys.size() == expectedKeys.size()) { + break; + } + Thread.sleep(100); + start += 100; + } + return actualKeys; + } + protected String getGatewayTelemetryJsonPayload(String deviceA, String deviceB, String firstTsValue, String secondTsValue) { String payload = "[{\"ts\": " + firstTsValue + ", \"values\": " + PAYLOAD_VALUES_STR + "}, " + "{\"ts\": " + secondTsValue + ", \"values\": " + PAYLOAD_VALUES_STR + "}]"; @@ -309,64 +319,20 @@ public abstract class AbstractMqttTimeseriesIntegrationTest extends AbstractMqtt // @Test - Unstable public void testMqttQoSLevel() throws Exception { - String clientId = MqttAsyncClient.generateClientId(); - MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, clientId, new MemoryPersistence()); - - MqttConnectOptions options = new MqttConnectOptions(); - options.setUserName(accessToken); - CountDownLatch latch = new CountDownLatch(1); - TestMqttCallback callback = new TestMqttCallback(client, latch); + MqttTestClient client = new MqttTestClient(); + MqttTestCallback callback = new MqttTestCallback(); client.setCallback(callback); - client.connect(options).waitForCompletion(5000); - client.subscribe("v1/devices/me/attributes", MqttQoS.AT_MOST_ONCE.value()); + client.connectAndWait(accessToken); + client.subscribe(DEVICE_ATTRIBUTES_TOPIC, MqttQoS.AT_MOST_ONCE); String payload = "{\"key\":\"uniqueValue\"}"; // TODO 3.1: we need to acknowledge subscription only after it is processed by device actor and not when the message is pushed to queue. // MqttClient -> SUB REQUEST -> Transport -> Kafka -> Device Actor (subscribed) // MqttClient <- SUB_ACK <- Transport Thread.sleep(5000); doPostAsync("/api/plugins/telemetry/" + savedDevice.getId() + "/SHARED_SCOPE", payload, String.class, status().isOk()); - latch.await(10, TimeUnit.SECONDS); - assertEquals(payload, callback.getPayload()); + callback.getSubscribeLatch().await(10, TimeUnit.SECONDS); + assertEquals(payload.getBytes(), callback.getPayloadBytes()); assertEquals(MqttQoS.AT_MOST_ONCE.value(), callback.getQoS()); } - private static class TestMqttCallback implements MqttCallback { - - private final MqttAsyncClient client; - private final CountDownLatch latch; - private volatile Integer qoS; - private volatile String payload; - - String getPayload() { - return payload; - } - - TestMqttCallback(MqttAsyncClient client, CountDownLatch latch) { - this.client = client; - this.latch = latch; - } - - int getQoS() { - return qoS; - } - - @Override - public void connectionLost(Throwable throwable) { - log.error("Client connection lost", throwable); - } - - @Override - public void messageArrived(String requestTopic, MqttMessage mqttMessage) { - payload = new String(mqttMessage.getPayload()); - qoS = mqttMessage.getQos(); - latch.countDown(); - } - - @Override - public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { - - } - } - - } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesJsonIntegrationTest.java index 6887941e4d..4a7037f6e8 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,19 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.TransportPayloadType; -import org.thingsboard.server.common.data.device.profile.MqttTopics; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; @Slf4j public abstract class AbstractMqttTimeseriesJsonIntegrationTest extends AbstractMqttTimeseriesIntegrationTest { @@ -35,23 +36,31 @@ public abstract class AbstractMqttTimeseriesJsonIntegrationTest extends Abstract private static final String POST_DATA_TELEMETRY_TOPIC = "data/telemetry"; @Before + @Override public void beforeTest() throws Exception { - processBeforeTest("Test Post Telemetry device json payload", "Test Post Telemetry gateway json payload", TransportPayloadType.JSON, POST_DATA_TELEMETRY_TOPIC, null); - } - - @After - public void afterTest() throws Exception { - processAfterTest(); + //do nothing, processBeforeTest will be invoked in particular test methods with different parameters } @Test public void testPushTelemetry() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); processJsonPayloadTelemetryTest(POST_DATA_TELEMETRY_TOPIC, expectedKeys, PAYLOAD_VALUES_STR.getBytes(), false); } @Test public void testPushTelemetryWithTs() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); String payloadStr = "{\"ts\": 10000, \"values\": " + PAYLOAD_VALUES_STR + "}"; List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); processJsonPayloadTelemetryTest(POST_DATA_TELEMETRY_TOPIC, expectedKeys, payloadStr.getBytes(), true); @@ -59,21 +68,122 @@ public abstract class AbstractMqttTimeseriesJsonIntegrationTest extends Abstract @Test public void testPushTelemetryOnShortTopic() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); super.testPushTelemetryOnShortTopic(); } @Test - public void testPushTelemetryWithTsOnShortJsonTopic() throws Exception { + public void testPushTelemetryOnShortJsonTopic() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); super.testPushTelemetryOnShortJsonTopic(); } @Test public void testPushTelemetryGateway() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .gatewayName("Test Post Telemetry gateway json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); super.testPushTelemetryGateway(); } @Test public void testGatewayConnect() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .gatewayName("Test Post Telemetry gateway json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); super.testGatewayConnect(); } + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .sendAckOnValidationException(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertTrue(callback.isPubAckReceived()); + client.disconnect(); + } + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorDisabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertFalse(callback.isPubAckReceived()); + } + + @Test + public void testPushTelemetryGatewayWithMalformedPayloadAndSendAckOnErrorEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .gatewayName("Test Post Telemetry gateway json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .sendAckOnValidationException(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertTrue(callback.isPubAckReceived()); + client.disconnect(); + } + + @Test + public void testPushTelemetryGatewayWithMalformedPayloadAndSendAckOnErrorDisabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device json payload") + .gatewayName("Test Post Telemetry gateway json payload") + .transportPayloadType(TransportPayloadType.JSON) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertFalse(callback.isPubAckReceived()); + } + } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesProtoIntegrationTest.java index 6bef6e5fc8..95de5f0069 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/AbstractMqttTimeseriesProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,30 +20,38 @@ import com.google.protobuf.Descriptors; import com.google.protobuf.DynamicMessage; import com.squareup.wire.schema.internal.parser.ProtoFileElement; import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.junit.Before; import org.junit.Test; import org.thingsboard.server.common.data.Device; -import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.TransportPayloadType; import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; -import org.thingsboard.server.common.data.device.profile.MqttTopics; import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; import org.thingsboard.server.gen.transport.TransportApiProtos; import org.thingsboard.server.gen.transport.TransportProtos; +import org.thingsboard.server.transport.mqtt.MqttTestCallback; +import org.thingsboard.server.transport.mqtt.MqttTestClient; +import org.thingsboard.server.transport.mqtt.MqttTestConfigProperties; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_SHORT_PROTO_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_CONNECT_TOPIC; +import static org.thingsboard.server.common.data.device.profile.MqttTopics.GATEWAY_TELEMETRY_TOPIC; @Slf4j public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends AbstractMqttTimeseriesIntegrationTest { private static final String POST_DATA_TELEMETRY_TOPIC = "proto/telemetry"; + private static final String MALFORMED_PROTO_PAYLOAD = "invalid proto payload str"; @Before @Override @@ -53,14 +61,25 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac @Test public void testPushTelemetry() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postTelemetryMsg = getDefaultDynamicMessage(); processTelemetryTest(POST_DATA_TELEMETRY_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postTelemetryMsg.toByteArray(), false, false); } @Test public void testPushTelemetryWithEnabledJsonBackwardCompatibility() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null, true, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + processBeforeTest(configProperties); processJsonPayloadTelemetryTest(POST_DATA_TELEMETRY_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes(), false); } @@ -91,7 +110,13 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac " }\n" + " }\n" + "}"; - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null, schemaStr, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .telemetryProtoSchema(schemaStr) + .build(); + processBeforeTest(configProperties); DynamicSchema telemetrySchema = getDynamicSchema(schemaStr); DynamicMessage.Builder nestedJsonObjectBuilder = telemetrySchema.newMessageBuilder("PostTelemetry.JsonObject.NestedJsonObject"); @@ -136,7 +161,12 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac @Test public void testPushTelemetryWithExplicitPresenceProtoKeys() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicSchema telemetrySchema = getDynamicSchema(DEVICE_TELEMETRY_PROTO_SCHEMA); DynamicMessage.Builder nestedJsonObjectBuilder = telemetrySchema.newMessageBuilder("PostTelemetry.JsonObject.NestedJsonObject"); @@ -193,7 +223,13 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac " }\n" + " }\n" + "}"; - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null, schemaStr, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .telemetryProtoSchema(schemaStr) + .build(); + processBeforeTest(configProperties); DynamicSchema telemetrySchema = getDynamicSchema(schemaStr); DynamicMessage.Builder nestedJsonObjectBuilder = telemetrySchema.newMessageBuilder("PostTelemetry.JsonObject.NestedJsonObject"); @@ -233,27 +269,48 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac @Test public void testPushTelemetryOnShortTopic() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postTelemetryMsg = getDefaultDynamicMessage(); - processTelemetryTest(MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postTelemetryMsg.toByteArray(), false, false); + processTelemetryTest(DEVICE_TELEMETRY_SHORT_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postTelemetryMsg.toByteArray(), false, false); } @Test public void testPushTelemetryOnShortJsonTopic() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null); - processJsonPayloadTelemetryTest(MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes(), false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); + processJsonPayloadTelemetryTest(DEVICE_TELEMETRY_SHORT_JSON_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), PAYLOAD_VALUES_STR.getBytes(), false); } @Test public void testPushTelemetryOnShortProtoTopic() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); DynamicMessage postTelemetryMsg = getDefaultDynamicMessage(); - processTelemetryTest(MqttTopics.DEVICE_TELEMETRY_SHORT_PROTO_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postTelemetryMsg.toByteArray(), false, false); + processTelemetryTest(DEVICE_TELEMETRY_SHORT_PROTO_TOPIC, Arrays.asList("key1", "key2", "key3", "key4", "key5"), postTelemetryMsg.toByteArray(), false, false); } @Test public void testPushTelemetryGateway() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, null, null, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .gatewayName("Test Post Telemetry gateway proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); TransportApiProtos.GatewayTelemetryMsg.Builder gatewayTelemetryMsgProtoBuilder = TransportApiProtos.GatewayTelemetryMsg.newBuilder(); List expectedKeys = Arrays.asList("key1", "key2", "key3", "key4", "key5"); String deviceName1 = "Device A"; @@ -262,22 +319,143 @@ public abstract class AbstractMqttTimeseriesProtoIntegrationTest extends Abstrac TransportApiProtos.TelemetryMsg deviceBTelemetryMsgProto = getDeviceTelemetryMsgProto(deviceName2, expectedKeys, 10000, 20000); gatewayTelemetryMsgProtoBuilder.addAllMsg(Arrays.asList(deviceATelemetryMsgProto, deviceBTelemetryMsgProto)); TransportApiProtos.GatewayTelemetryMsg gatewayTelemetryMsg = gatewayTelemetryMsgProtoBuilder.build(); - processGatewayTelemetryTest(MqttTopics.GATEWAY_TELEMETRY_TOPIC, expectedKeys, gatewayTelemetryMsg.toByteArray(), deviceName1, deviceName2); + processGatewayTelemetryTest(GATEWAY_TELEMETRY_TOPIC, expectedKeys, gatewayTelemetryMsg.toByteArray(), deviceName1, deviceName2); } @Test public void testGatewayConnect() throws Exception { - processBeforeTest("Test Post Telemetry device proto payload", "Test Post Telemetry gateway proto payload", TransportPayloadType.PROTOBUF, POST_DATA_TELEMETRY_TOPIC, null, null, null, null, null, null, null, DeviceProfileProvisionType.DISABLED, false, false); + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .gatewayName("Test Post Telemetry gateway proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); String deviceName = "Device A"; TransportApiProtos.ConnectMsg connectMsgProto = getConnectProto(deviceName); - MqttAsyncClient client = getMqttAsyncClient(gatewayAccessToken); - publishMqttMsg(client, connectMsgProto.toByteArray(), MqttTopics.GATEWAY_CONNECT_TOPIC); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + client.publish(GATEWAY_CONNECT_TOPIC, connectMsgProto.toByteArray()); Device device = doExecuteWithRetriesAndInterval(() -> doGet("/api/tenant/devices?deviceName=" + deviceName, Device.class), 20, 100); assertNotNull(device); + client.disconnect(); + } + + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .sendAckOnValidationException(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_PROTO_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertTrue(callback.isPubAckReceived()); + client.disconnect(); + } + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorDisabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_PROTO_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertFalse(callback.isPubAckReceived()); + } + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorEnabledAndBackwardCompatibilityEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .enableCompatibilityWithJsonPayloadFormat(true) + .sendAckOnValidationException(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertTrue(callback.isPubAckReceived()); + client.disconnect(); + } + + @Test + public void testPushTelemetryWithMalformedPayloadAndSendAckOnErrorDisabledAndBackwardCompatibilityEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .enableCompatibilityWithJsonPayloadFormat(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(accessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_JSON_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertFalse(callback.isPubAckReceived()); + } + + @Test + public void testPushTelemetryGatewayWithMalformedPayloadAndSendAckOnErrorEnabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .gatewayName("Test Post Telemetry gateway proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .sendAckOnValidationException(true) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_PROTO_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertTrue(callback.isPubAckReceived()); + client.disconnect(); + } + + @Test + public void testPushTelemetryGatewayWithMalformedPayloadAndSendAckOnErrorDisabled() throws Exception { + MqttTestConfigProperties configProperties = MqttTestConfigProperties.builder() + .deviceName("Test Post Telemetry device proto payload") + .gatewayName("Test Post Telemetry gateway proto payload") + .transportPayloadType(TransportPayloadType.PROTOBUF) + .telemetryTopicFilter(POST_DATA_TELEMETRY_TOPIC) + .build(); + processBeforeTest(configProperties); + MqttTestClient client = new MqttTestClient(); + client.connectAndWait(gatewayAccessToken); + MqttTestCallback callback = new MqttTestCallback(); + client.setCallback(callback); + client.publish(POST_DATA_TELEMETRY_TOPIC, MALFORMED_PROTO_PAYLOAD.getBytes()); + callback.getDeliveryLatch().await(3, TimeUnit.SECONDS); + assertFalse(callback.isPubAckReceived()); } private DynamicSchema getDynamicSchema(String deviceTelemetryProtoSchema) { diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlIntegrationTest.java index 67946ffc6b..7006638eb1 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,6 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries.nosql; import org.thingsboard.server.dao.service.DaoNoSqlTest; import org.thingsboard.server.transport.mqtt.telemetry.timeseries.AbstractMqttTimeseriesIntegrationTest; -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ @DaoNoSqlTest public class MqttTimeseriesNoSqlIntegrationTest extends AbstractMqttTimeseriesIntegrationTest { } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlJsonIntegrationTest.java index 6b9987091e..8e6e2cf679 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlProtoIntegrationTest.java index dfdae8d3f8..e91d5982d7 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/nosql/MqttTimeseriesNoSqlProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlIntegrationTest.java index e89b45fc32..de9a596d43 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,6 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries.sql; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.telemetry.timeseries.AbstractMqttTimeseriesIntegrationTest; -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ @DaoSqlTest public class MqttTimeseriesSqlIntegrationTest extends AbstractMqttTimeseriesIntegrationTest { } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlJsonIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlJsonIntegrationTest.java index 4f4fd84168..323dd751f1 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlJsonIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlJsonIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,6 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries.sql; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.telemetry.timeseries.AbstractMqttTimeseriesJsonIntegrationTest; -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ @DaoSqlTest public class MqttTimeseriesSqlJsonIntegrationTest extends AbstractMqttTimeseriesJsonIntegrationTest { } diff --git a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlProtoIntegrationTest.java b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlProtoIntegrationTest.java index cf227e6af4..ebfc1d49cf 100644 --- a/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlProtoIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/transport/mqtt/telemetry/timeseries/sql/MqttTimeseriesSqlProtoIntegrationTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,6 @@ package org.thingsboard.server.transport.mqtt.telemetry.timeseries.sql; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.transport.mqtt.telemetry.timeseries.AbstractMqttTimeseriesProtoIntegrationTest; -/** - * Created by Valerii Sosliuk on 8/22/2017. - */ @DaoSqlTest public class MqttTimeseriesSqlProtoIntegrationTest extends AbstractMqttTimeseriesProtoIntegrationTest { } diff --git a/application/src/test/java/org/thingsboard/server/util/EventDeduplicationExecutorTest.java b/application/src/test/java/org/thingsboard/server/util/EventDeduplicationExecutorTest.java index bb5541089e..f938217e6c 100644 --- a/application/src/test/java/org/thingsboard/server/util/EventDeduplicationExecutorTest.java +++ b/application/src/test/java/org/thingsboard/server/util/EventDeduplicationExecutorTest.java @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/application/src/test/resources/application-test.properties b/application/src/test/resources/application-test.properties index 651b00ed67..518c9b42d3 100644 --- a/application/src/test/resources/application-test.properties +++ b/application/src/test/resources/application-test.properties @@ -1,22 +1,57 @@ transport.lwm2m.server.security.credentials.enabled=true transport.lwm2m.server.security.credentials.type=KEYSTORE -transport.lwm2m.server.security.credentials.keystore.store_file=lwm2m/credentials/serverKeyStore.jks -transport.lwm2m.server.security.credentials.keystore.store_password=server -transport.lwm2m.server.security.credentials.keystore.key_alias=server -transport.lwm2m.server.security.credentials.keystore.key_password=server -transport.lwm2m.bootstrap.enabled=false +transport.lwm2m.server.security.credentials.keystore.store_file=lwm2m/credentials/lwm2mserver.jks transport.lwm2m.bootstrap.security.credentials.enabled=true transport.lwm2m.bootstrap.security.credentials.type=KEYSTORE -transport.lwm2m.bootstrap.security.credentials.keystore.store_file=lwm2m/credentials/serverKeyStore.jks -transport.lwm2m.bootstrap.security.credentials.keystore.store_password=server -transport.lwm2m.bootstrap.security.credentials.keystore.key_alias=server -transport.lwm2m.bootstrap.security.credentials.keystore.key_password=server +transport.lwm2m.bootstrap.security.credentials.keystore.store_file=lwm2m/credentials/lwm2mserver.jks transport.lwm2m.security.trust-credentials.enabled=true transport.lwm2m.security.trust-credentials.type=KEYSTORE -transport.lwm2m.security.trust-credentials.keystore.store_file=lwm2m/credentials/serverKeyStore.jks -transport.lwm2m.security.trust-credentials.keystore.store_password=server +transport.lwm2m.security.trust-credentials.keystore.store_file=lwm2m/credentials/lwm2mtruststorechain.jks -edges.enabled=true +# Edge disabled to speed up the context init. Will be enabled by @TestPropertySource in respective tests +edges.enabled=false edges.storage.no_read_records_sleep=500 edges.storage.sleep_between_batches=500 actors.rpc.sequential=true + +# Transports disabled to speed up the context init. Particular transport will be enabled with @TestPropertySource in respective tests +transport.http.enabled=false +transport.mqtt.enabled=false +transport.coap.enabled=false +transport.lwm2m.enabled=false +transport.snmp.enabled=false + +# Low latency settings to perform tests as fast as possible +sql.attributes.batch_max_delay=5 +sql.attributes.batch_threads=2 +sql.ts.batch_max_delay=5 +sql.ts.batch_threads=2 +sql.ts_latest.batch_max_delay=5 +sql.ts_latest.batch_threads=2 +sql.events.batch_max_delay=5 +sql.events.batch_threads=2 +actors.system.tenant_dispatcher_pool_size=4 +actors.system.device_dispatcher_pool_size=8 +actors.system.rule_dispatcher_pool_size=12 +transport.sessions.report_timeout=10000 +queue.transport_api.request_poll_interval=5 +queue.transport_api.response_poll_interval=5 +queue.transport.poll_interval=5 +queue.core.poll-interval=5 +queue.core.partitions=2 +queue.rule-engine.poll-interval=5 +queue.rule-engine.queues[0].poll-interval=5 +queue.rule-engine.queues[0].partitions=2 +queue.rule-engine.queues[0].processing-strategy.retries=1 +queue.rule-engine.queues[0].processing-strategy.pause-between-retries=0 +queue.rule-engine.queues[0].processing-strategy.max-pause-between-retries=0 +queue.rule-engine.queues[1].poll-interval=5 +queue.rule-engine.queues[1].partitions=2 +queue.rule-engine.queues[1].processing-strategy.retries=1 +queue.rule-engine.queues[1].processing-strategy.pause-between-retries=0 +queue.rule-engine.queues[1].processing-strategy.max-pause-between-retries=0 +queue.rule-engine.queues[2].poll-interval=5 +queue.rule-engine.queues[2].partitions=2 +queue.rule-engine.queues[2].processing-strategy.retries=1 +queue.rule-engine.queues[2].processing-strategy.pause-between-retries=0 +queue.rule-engine.queues[2].processing-strategy.max-pause-between-retries=0 diff --git a/application/src/test/resources/logback.xml b/application/src/test/resources/logback-test.xml similarity index 100% rename from application/src/test/resources/logback.xml rename to application/src/test/resources/logback-test.xml diff --git a/application/src/test/resources/lwm2m/credentials/clientKeyStore.jks b/application/src/test/resources/lwm2m/credentials/clientKeyStore.jks deleted file mode 100644 index a6c9ae7fae..0000000000 Binary files a/application/src/test/resources/lwm2m/credentials/clientKeyStore.jks and /dev/null differ diff --git a/application/src/test/resources/lwm2m/credentials/lwm2mclient.jks b/application/src/test/resources/lwm2m/credentials/lwm2mclient.jks new file mode 100644 index 0000000000..ca8c8ed1d7 Binary files /dev/null and b/application/src/test/resources/lwm2m/credentials/lwm2mclient.jks differ diff --git a/application/src/test/resources/lwm2m/credentials/lwm2mserver.jks b/application/src/test/resources/lwm2m/credentials/lwm2mserver.jks new file mode 100644 index 0000000000..d16967343f Binary files /dev/null and b/application/src/test/resources/lwm2m/credentials/lwm2mserver.jks differ diff --git a/application/src/test/resources/lwm2m/credentials/lwm2mtruststorechain.jks b/application/src/test/resources/lwm2m/credentials/lwm2mtruststorechain.jks new file mode 100644 index 0000000000..b97f3629cd Binary files /dev/null and b/application/src/test/resources/lwm2m/credentials/lwm2mtruststorechain.jks differ diff --git a/application/src/test/resources/lwm2m/credentials/serverKeyStore.jks b/application/src/test/resources/lwm2m/credentials/serverKeyStore.jks deleted file mode 100644 index fc541a3b18..0000000000 Binary files a/application/src/test/resources/lwm2m/credentials/serverKeyStore.jks and /dev/null differ diff --git a/application/src/test/resources/lwm2m/credentials/shell/lwm2m_cfssl_chain_for_test_All.sh b/application/src/test/resources/lwm2m/credentials/shell/lwm2m_cfssl_chain_for_test_All.sh deleted file mode 100755 index b3b114cb28..0000000000 --- a/application/src/test/resources/lwm2m/credentials/shell/lwm2m_cfssl_chain_for_test_All.sh +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env bash - -readonly INTERMEDIATE_START=0 -readonly INTERMEDIATE_FINISH=2 -readonly CLIENT_START=0 -readonly CLIENT_FINISH=5 - -IS_IHFO=false -IS_SERVER_CREATED_KEY=true -IS_TRUST_CLIENT_CREATED_KEY=true - -cd -- "$( - dirname "${0}" -)" || exit 1 - -Help() -{ - # Display Help - echo "Description of the script functions." - echo - echo "Syntax: scriptTemplate [-g|h|v|V]" - echo "options:" - echo "h Print this Help." - echo "v Verbose mode." - echo "V Print software version and exit." - echo -} - -if [ "$1" == "-h" ] ; then - echo -e "Usage 2: ./`basename $0` \"Information is not displayed\" : \"Keys for the server are generated\" : \"Keys for the clients and trusts are generated\"" - echo -e "Usage 1: ./`basename $0` true \"Information is displayed\" : \"Keys for the server are generated\" : \"Keys for the clients and trusts are generated\"" - echo -e "Usage 3: ./`basename $0` true false \"Information is displayed\" : \"Keys for the server are not generated\" : \"Keys for the clients and trusts are generated\"" - echo -e "Usage 4: ./`basename $0` true false false \"Information is displayed\" : \"Keys for the server are not generated\" : \"Keys for the clients and trusts are not generated\"" - echo -e "Usage 4: ./`basename $0` true true false \"Information is displayed\" : \"Keys for the server are generated\" : \"Keys for the clients and trusts are not generated\"" - echo "This Help File: ./`basename $0` -h" - exit 0 -fi - -if [ -n "$1" ]; then - IS_IHFO=$1 -fi - -if [ -n "$2" ]; then - IS_SERVER_CREATED_KEY=$2 -fi - -if [ -n "$3" ]; then - IS_TRUST_CLIENT_CREATED_KEY=$3 -fi - -if [ "$IS_IHFO" = false ] ; then - if [ "$IS_SERVER_CREATED_KEY" = true ] ; then - ./lwm2m_cfssl_chain_server_for_test.sh > /dev/null 2>&1 & - fi - if [ "$IS_TRUST_CLIENT_CREATED_KEY" = true ] ; then - ./lwM2M_cfssl_chain_trusts_and_clients_for_test.sh ${INTERMEDIATE_START} ${INTERMEDIATE_FINISH} ${CLIENT_START} ${CLIENT_FINISH} > /dev/null 2>&1 & - fi -else - if [ "$IS_SERVER_CREATED_KEY" = true ] ; then - ./lwm2m_cfssl_chain_server_for_test.sh - fi - if [ "$IS_TRUST_CLIENT_CREATED_KEY" = true ] ; then - ./lwM2M_cfssl_chain_trusts_and_clients_for_test.sh ${INTERMEDIATE_START} ${INTERMEDIATE_FINISH} ${CLIENT_START} ${CLIENT_FINISH} - fi -fi \ No newline at end of file diff --git a/application/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/application/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000..ca6ee9cea8 --- /dev/null +++ b/application/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/common/actor/pom.xml b/common/actor/pom.xml index 16bd96eedb..a06fa00b55 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -1,6 +1,6 @@ + + + + + + %d{ISO8601} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + diff --git a/msa/js-executor/api/httpServer.js b/msa/js-executor/api/httpServer.js index 4948c45f61..62bf5807b1 100644 --- a/msa/js-executor/api/httpServer.js +++ b/msa/js-executor/api/httpServer.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/api/jsExecutor.js b/msa/js-executor/api/jsExecutor.js index 612c6ac5a9..02190406d2 100644 --- a/msa/js-executor/api/jsExecutor.js +++ b/msa/js-executor/api/jsExecutor.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/api/jsInvokeMessageProcessor.js b/msa/js-executor/api/jsInvokeMessageProcessor.js index 5257a03168..8f2ae8db49 100644 --- a/msa/js-executor/api/jsInvokeMessageProcessor.js +++ b/msa/js-executor/api/jsInvokeMessageProcessor.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/api/utils.js b/msa/js-executor/api/utils.js index 3474129692..4f02ad52ae 100644 --- a/msa/js-executor/api/utils.js +++ b/msa/js-executor/api/utils.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/config/custom-environment-variables.yml b/msa/js-executor/config/custom-environment-variables.yml index fdf261e25c..d408b14136 100644 --- a/msa/js-executor/config/custom-environment-variables.yml +++ b/msa/js-executor/config/custom-environment-variables.yml @@ -1,5 +1,5 @@ # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/msa/js-executor/config/default.yml b/msa/js-executor/config/default.yml index 7a6e7c2469..a08a5a28aa 100644 --- a/msa/js-executor/config/default.yml +++ b/msa/js-executor/config/default.yml @@ -1,5 +1,5 @@ # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/msa/js-executor/config/logger.js b/msa/js-executor/config/logger.js index 3934f6b61b..d01440a74b 100644 --- a/msa/js-executor/config/logger.js +++ b/msa/js-executor/config/logger.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/config/tb-js-executor.conf b/msa/js-executor/config/tb-js-executor.conf index 156dba0f85..fbdcc163f5 100644 --- a/msa/js-executor/config/tb-js-executor.conf +++ b/msa/js-executor/config/tb-js-executor.conf @@ -1,5 +1,5 @@ # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/msa/js-executor/docker/Dockerfile b/msa/js-executor/docker/Dockerfile index 992353dd3e..0934b4b1a1 100644 --- a/msa/js-executor/docker/Dockerfile +++ b/msa/js-executor/docker/Dockerfile @@ -1,5 +1,5 @@ # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/msa/js-executor/docker/start-js-executor.sh b/msa/js-executor/docker/start-js-executor.sh index ba0c3eaeed..804b93da84 100755 --- a/msa/js-executor/docker/start-js-executor.sh +++ b/msa/js-executor/docker/start-js-executor.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Copyright © 2016-2021 The Thingsboard Authors +# Copyright © 2016-2022 The Thingsboard Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/msa/js-executor/install.js b/msa/js-executor/install.js index d180a5247a..a20142a4a0 100644 --- a/msa/js-executor/install.js +++ b/msa/js-executor/install.js @@ -1,5 +1,5 @@ /* - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index 69fc59eed2..d1df447072 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "3.3.3", + "version": "3.4.0", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.js", "bin": "server.js", @@ -12,20 +12,19 @@ "start-prod": "NODE_ENV=production nodemon server.js" }, "dependencies": { - "@azure/service-bus": "^1.1.9", - "@google-cloud/pubsub": "^2.5.0", - "amqplib": "^0.6.0", - "aws-sdk": "^2.741.0", - "azure-sb": "^0.11.1", - "config": "^3.3.1", - "express": "^4.17.1", - "js-yaml": "^3.14.0", - "kafkajs": "^1.15.0", - "long": "^4.0.0", + "@azure/service-bus": "^7.5.1", + "@google-cloud/pubsub": "^3.0.1", + "amqplib": "^0.10.0", + "aws-sdk": "^2.1152.0", + "config": "^3.3.7", + "express": "^4.18.1", + "js-yaml": "^4.1.0", + "kafkajs": "^2.0.2", + "long": "^5.2.0", "uuid-parse": "^1.1.0", "uuid-random": "^1.3.2", - "winston": "^3.3.3", - "winston-daily-rotate-file": "^4.5.0" + "winston": "^3.7.2", + "winston-daily-rotate-file": "^4.7.1" }, "nyc": { "exclude": [ @@ -36,13 +35,19 @@ ] }, "devDependencies": { - "fs-extra": "^10.0.0", - "nodemon": "^2.0.12", - "pkg": "^5.3.1" + "fs-extra": "^10.1.0", + "nodemon": "^2.0.16", + "pkg": "^5.7.0" }, "pkg": { "assets": [ "node_modules/config/**/*.*" ] + }, + "resolutions": { + "ansi-regex": "^5.0.1", + "color-string": "^1.5.5", + "minimist": "^1.2.6", + "node-fetch": "^2.6.7" } } diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 72adb41d76..a910e4759f 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -1,6 +1,6 @@ 2.8.0 4.1.1 2.57 @@ -110,7 +112,7 @@ 1.4.3 1.9.4 3.2.2 - 1.5.2 + 1.8.3 1.0.3TB 3.4.0 8.17.0 @@ -123,15 +125,16 @@ 4.1.0 4.3.1.0 2.7.2 - 2.6.1 1.5.2 - 5.6.3 + 5.7.2 2.6.0 1.3.0 1.2.7 1.16.0 1.12 + 3.0.0 + 1.0.0 @@ -403,39 +406,9 @@ false - - ../common/transport/lwm2m/src/main/resources - - **/*.xml - **/*.jks - - false - - - - - - copy-lwm2m-resources - ${pkg.process-resources.phase} - - copy-resources - - - ../transport/lwm2m/src/main/data - - - ../common/transport/lwm2m/src/main/resources - - **/*.xml - **/*.jks - - false - - - copy-docker-config ${pkg.process-resources.phase} @@ -515,6 +488,7 @@ repackage + build-info @@ -668,7 +642,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.0.0-M5 + ${surefire.version} --illegal-access=permit @@ -829,10 +803,6 @@ **/*.proto.js docker/haproxy/** docker/tb-node/** - src/main/resources/models/*.xml - src/main/resources/credentials/*.jks - src/main/resources/credentials/shell/*.jks - src/main/resources/credentials/shell/*.jks.old ui/** src/.browserslistrc **/yarn.lock @@ -840,6 +810,7 @@ **/*.patch **/apache/cassandra/io/** .run/** + **/NetworkReceive.java JAVADOC_STYLE @@ -1687,11 +1658,6 @@ bcpkix-jdk15on ${bouncycastle.version} - - org.hsqldb - hsqldb - ${hsqldb.version} - org.testcontainers postgresql @@ -1905,6 +1871,16 @@ ${zeroturnaround.version} test + + org.opensmpp + opensmpp-core + ${opensmpp.version} + + + org.jboss.aerogear + aerogear-otp-java + ${aerogear-otp.version} + diff --git a/pull_request_template.md b/pull_request_template.md new file mode 100644 index 0000000000..6e7c31967e --- /dev/null +++ b/pull_request_template.md @@ -0,0 +1,30 @@ +## Pull Request description + +Put your PR description here instead of this sentence. + +## General checklist + +- [ ] You have reviewed the guidelines [document](https://docs.google.com/document/d/1wqcOafLx5hth8SAg4dqV_LV3un3m5WYR8RdTJ4MbbUM/edit?usp=sharing). +- [ ] PR name contains fix version. For example, "[3.3.4] Hotfix of some UI component" or "[3.4] New Super Feature". +- [ ] Description references specific [issue](https://github.com/thingsboard/thingsboard/issues). +- [ ] Description contains human-readable scope of changes. +- [ ] Description contains brief notes about what needs to be added to the documentation. +- [ ] No merge conflicts, commented blocks of code, code formatting issues. +- [ ] Changes are backward compatible or upgrade script is provided. +- [ ] Similar PR is opened for PE version to simplify merge. Required for internal contributors only. + +## Front-End feature checklist + +- [ ] Screenshots with affected component(s) are added. The best option is to provide 2 screens: before and after changes; +- [ ] If you change the widget or other API, ensure it is backward-compatible or upgrade script is present. +- [ ] Ensure new API is documented [here](https://github.com/thingsboard/thingsboard-ui-help) + +## Back-End feature checklist + +- [ ] Added corresponding unit and/or integration test(s). Provide written explanation in the PR description if you have failed to add tests. +- [ ] If new dependency was added: the dependency tree is checked for conflicts. +- [ ] If new service was added: the service is marked with corresponding @TbCoreComponent, @TbRuleEngineComponent, @TbTransportComponent, etc. +- [ ] If new REST API was added: the RestClient.java was updated, issue for [Python REST client](https://github.com/thingsboard/thingsboard-python-rest-client) is created. + + + diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 36ec99fab6..40c07c965f 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -1,6 +1,6 @@ - + [parentDashboard]="parentDashboard" + [parentAliasController]="parentAliasController"> +
+ {{ 'dashboard.non-existent-dashboard-state-error' | translate:{stateId} }} +
diff --git a/ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.scss b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.scss similarity index 82% rename from ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.scss rename to ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.scss index dfe76e39e3..01322e7215 100644 --- a/ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,4 +14,8 @@ * limitations under the License. */ :host { + position: relative; + display: block; + width: 100%; + height: 100%; } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.ts b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.ts index fb22d9f3c2..50863b0595 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.ts +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-state.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -14,14 +14,14 @@ /// limitations under the License. /// -import { ChangeDetectorRef, Component, Input, OnDestroy, OnInit } from '@angular/core'; +import { ChangeDetectorRef, Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { Dashboard } from '@shared/models/dashboard.models'; -import { StateObject } from '@core/api/widget-api.models'; +import { Dashboard, DashboardLayoutId } from '@shared/models/dashboard.models'; +import { IAliasController, StateObject } from '@core/api/widget-api.models'; import { updateEntityParams, WidgetContext } from '@home/models/widget-component.models'; -import { deepClone, objToBase64 } from '@core/utils'; +import { deepClone, isDefinedAndNotNull, isNotEmptyStr, objToBase64 } from '@core/utils'; import { IDashboardComponent } from '@home/models/dashboard-component.models'; import { EntityId } from '@shared/models/id/entity-id'; import { Subscription } from 'rxjs'; @@ -29,7 +29,7 @@ import { Subscription } from 'rxjs'; @Component({ selector: 'tb-dashboard-state', templateUrl: './dashboard-state.component.html', - styleUrls: [] + styleUrls: ['./dashboard-state.component.scss'] }) export class DashboardStateComponent extends PageComponent implements OnInit, OnDestroy { @@ -42,6 +42,15 @@ export class DashboardStateComponent extends PageComponent implements OnInit, On @Input() syncParentStateParams = false; + @Input() + defaultAutofillLayout = true; + + @Input() + defaultMargin; + + @Input() + defaultBackgroundColor; + @Input() entityParamName: string; @@ -54,6 +63,10 @@ export class DashboardStateComponent extends PageComponent implements OnInit, On parentDashboard: IDashboardComponent; + parentAliasController: IAliasController; + + stateExists = true; + private stateSubscription: Subscription; constructor(protected store: Store, @@ -63,14 +76,32 @@ export class DashboardStateComponent extends PageComponent implements OnInit, On ngOnInit(): void { this.dashboard = deepClone(this.ctx.stateController.dashboardCtrl.dashboardCtx.getDashboard()); - this.updateCurrentState(); - this.parentDashboard = this.ctx.parentDashboard ? - this.ctx.parentDashboard : this.ctx.dashboard; - if (this.syncParentStateParams) { - this.stateSubscription = this.ctx.stateController.dashboardCtrl.dashboardCtx.stateChanged.subscribe(() => { - this.updateCurrentState(); - this.cd.markForCheck(); - }); + const state = this.dashboard.configuration.states[this.stateId]; + if (state) { + for (const layoutId of Object.keys(state.layouts)) { + if (this.defaultAutofillLayout) { + state.layouts[layoutId as DashboardLayoutId].gridSettings.autoFillHeight = true; + state.layouts[layoutId as DashboardLayoutId].gridSettings.mobileAutoFillHeight = true; + } + if (isDefinedAndNotNull(this.defaultMargin)) { + state.layouts[layoutId as DashboardLayoutId].gridSettings.margin = this.defaultMargin; + } + if (isNotEmptyStr(this.defaultBackgroundColor)) { + state.layouts[layoutId as DashboardLayoutId].gridSettings.backgroundColor = this.defaultBackgroundColor; + } + } + this.updateCurrentState(); + this.parentDashboard = this.ctx.parentDashboard ? + this.ctx.parentDashboard : this.ctx.dashboard; + if (this.syncParentStateParams) { + this.parentAliasController = this.parentDashboard.aliasController; + this.stateSubscription = this.ctx.stateController.dashboardCtrl.dashboardCtx.stateChanged.subscribe(() => { + this.updateCurrentState(); + this.cd.markForCheck(); + }); + } + } else { + this.stateExists = false; } } diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html index de15c409ec..d7fb4c3f88 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/dashboard-toolbar.component.html @@ -1,6 +1,6 @@ + + +
+
+
{{ headerTitle }}
+
{{ headerSubtitle }}
+
+
+ +
+ + +
+
+
+ + + + + + + + +
+ diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.scss b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.scss new file mode 100644 index 0000000000..27b3d4f2f8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.scss @@ -0,0 +1,119 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@import "../../../../../scss/constants"; + +:host { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + overflow: hidden; + + .settings-card { + margin: 8px; + padding: 0; + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + + .details-toolbar { + height: 84px; + min-height: 84px; + border-radius: 4px 4px 0 0; + background: #fff; + border-bottom: 1px solid rgba(0, 0, 0, 0.12); + + .mat-toolbar-tools { + padding: 0 8px; + } + + .tb-details-title-header { + min-width: 0; + width: auto; + } + + .tb-details-title { + font-size: 1rem; + font-weight: 500; + + @media #{$mat-gt-sm} { + font-size: 1.2rem; + } + } + + .tb-details-subtitle { + font-size: 0.9rem; + opacity: .8; + } + + .tb-ellipsis { + width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } + + @media #{$mat-md} { + width: 80%; + } + + @media #{$mat-gt-md} { + width: 60%; + } + + .tb-header-button { + .tb-btn-header { + position: relative !important; + display: inline-block !important; + animation: tbMoveFromTopFade .3s ease both; + + &.tb-hide { + animation: tbMoveToTopFade .3s ease both; + } + } + } + } +} + +:host ::ng-deep { + .tb-help { + .mat-icon-button.mat-primary { + color: rgba(0, 0, 0, 0.52); + } + } + + .mat-card-content { + position: relative; + overflow: hidden; + + > .mat-tab-group { + > .mat-tab-body-wrapper { + position: absolute; + top: 49px; + left: 0; + right: 0; + bottom: 0; + } + > .mat-tab-header { + .mat-tab-label { + min-width: 40px; + } + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts new file mode 100644 index 0000000000..d0b141256e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts @@ -0,0 +1,173 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { + ChangeDetectionStrategy, + ChangeDetectorRef, + Component, + ComponentFactoryResolver, + HostBinding, + Injector, + OnDestroy, + OnInit +} from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { EntityTableConfig } from '@home/models/entity/entities-table-config.models'; +import { BaseData, HasId } from '@shared/models/base-data'; +import { ActivatedRoute, Router } from '@angular/router'; +import { FormGroup } from '@angular/forms'; +import { AssetId } from '@shared/models/id/asset-id'; +import { TranslateService } from '@ngx-translate/core'; +import { deepClone } from '@core/utils'; +import { BroadcastService } from '@core/services/broadcast.service'; +import { EntityDetailsPanelComponent } from '@home/components/entity/entity-details-panel.component'; +import { DialogService } from '@core/services/dialog.service'; +import { IEntityDetailsPageComponent } from '@home/models/entity/entity-details-page-component.models'; + +@Component({ + selector: 'tb-entity-details-page', + templateUrl: './entity-details-page.component.html', + styleUrls: ['./entity-details-page.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class EntityDetailsPageComponent extends EntityDetailsPanelComponent implements IEntityDetailsPageComponent, OnInit, OnDestroy { + + headerTitle: string; + headerSubtitle: string; + + isReadOnly = false; + + set entitiesTableConfig(entitiesTableConfig: EntityTableConfig>) { + if (this.entitiesTableConfigValue !== entitiesTableConfig) { + this.entitiesTableConfigValue = entitiesTableConfig; + if (this.entitiesTableConfigValue) { + this.entitiesTableConfigValue.setEntityDetailsPage(this); + this.isEdit = false; + this.entity = null; + } + } + } + + get entitiesTableConfig(): EntityTableConfig> { + return this.entitiesTableConfigValue; + } + + @HostBinding('class') 'tb-absolute-fill'; + + constructor(private route: ActivatedRoute, + private router: Router, + protected injector: Injector, + protected cd: ChangeDetectorRef, + protected componentFactoryResolver: ComponentFactoryResolver, + private broadcast: BroadcastService, + private translate: TranslateService, + private dialogService: DialogService, + protected store: Store) { + super(store, injector, cd, componentFactoryResolver); + this.entitiesTableConfig = this.route.snapshot.data.entitiesTableConfig; + } + + ngOnInit() { + this.headerSubtitle = ''; + this.headerSubtitle = this.translate.instant(this.entitiesTableConfig.entityTranslations.details); + super.init(); + this.entityComponent.isDetailsPage = true; + this.subscriptions.push(this.entityAction.subscribe((action) => { + if (action.action === 'delete') { + this.deleteEntity(action.event, action.entity); + } + })); + this.subscriptions.push(this.route.paramMap.subscribe( paramMap => { + if (this.entitiesTableConfig) { + const entityType = this.entitiesTableConfig.entityType; + const id = paramMap.get('entityId'); + this.currentEntityId = { id, entityType }; + this.reload(); + this.selectedTab = 0; + } + })); + } + + ngOnDestroy() { + super.ngOnDestroy(); + } + + reload(): void { + this.reloadEntity().subscribe(() => { + this.onUpdateEntity(); + }); + } + + onToggleDetailsEditMode() { + if (this.isEdit) { + this.entityComponent.entity = this.entity; + if (this.entityTabsComponent) { + this.entityTabsComponent.entity = this.entity; + } + this.isEdit = !this.isEdit; + } else { + this.isEdit = !this.isEdit; + this.editingEntity = deepClone(this.entity); + this.entityComponent.entity = this.editingEntity; + if (this.entityTabsComponent) { + this.entityTabsComponent.entity = this.editingEntity; + } + if (this.entitiesTableConfig.hideDetailsTabsOnEdit) { + this.selectedTab = 0; + } + } + } + + onApplyDetails() { + this.saveEntity(false).subscribe((entity) => { + if (entity) { + this.onUpdateEntity(); + } + }); + } + + confirmForm(): FormGroup { + return this.detailsForm; + } + + private onUpdateEntity() { + this.broadcast.broadcast('updateBreadcrumb'); + this.isReadOnly = this.entitiesTableConfig.detailsReadonly(this.entity); + this.headerTitle = this.entitiesTableConfig.entityTitle(this.entity); + } + + private deleteEntity($event: Event, entity: BaseData) { + if ($event) { + $event.stopPropagation(); + } + this.dialogService.confirm( + this.entitiesTableConfig.deleteEntityTitle(entity), + this.entitiesTableConfig.deleteEntityContent(entity), + this.translate.instant('action.no'), + this.translate.instant('action.yes'), + true + ).subscribe((result) => { + if (result) { + this.entitiesTableConfig.deleteEntity(entity.id).subscribe( + () => { + this.router.navigate(['../'], {relativeTo: this.route}); + } + ); + } + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.html b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.html index c5f1ec3671..cba0b85ce9 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.html @@ -1,6 +1,6 @@ + + +
+ +
+ {{'filter.dynamic-value' | translate}} +
+
+ +
+
+ +
+
+
+ + + + + {{'filter.no-dynamic-value' | translate}} + + + {{dynamicValueSourceTypeTranslations.get(sourceType) | translate}} + + + +
+
+ + + + +
+
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-dynamic-value.component.ts b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-dynamic-value.component.ts new file mode 100644 index 0000000000..95084db163 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-dynamic-value.component.ts @@ -0,0 +1,99 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormGroup, + NG_VALUE_ACCESSOR, +} from '@angular/forms'; +import { + DynamicValueSourceType, + dynamicValueSourceTypeTranslationMap, + getDynamicSourcesForAllowUser +} from '@shared/models/query/query.models'; + +@Component({ + selector: 'tb-alarm-dynamic-value', + templateUrl: './alarm-dynamic-value.component.html', + providers: [{ + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => AlarmDynamicValue), + multi: true + }] +}) + +export class AlarmDynamicValue implements ControlValueAccessor, OnInit{ + public dynamicValue: FormGroup; + public dynamicValueSourceTypes: DynamicValueSourceType[] = getDynamicSourcesForAllowUser(false); + public dynamicValueSourceTypeTranslations = dynamicValueSourceTypeTranslationMap; + private propagateChange = (v: any) => { }; + + @Input() + helpId: string; + + @Input() + disabled: boolean; + + constructor(private fb: FormBuilder) { + } + + ngOnInit(): void { + this.dynamicValue = this.fb.group({ + sourceType: [null, []], + sourceAttribute: [null] + }) + + this.dynamicValue.get('sourceType').valueChanges.subscribe( + (sourceType) => { + if (!sourceType) { + this.dynamicValue.get('sourceAttribute').patchValue(null, {emitEvent: false}); + } + } + ); + + this.dynamicValue.valueChanges.subscribe(() => { + this.updateModel(); + }) + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + writeValue(dynamicValue: {sourceType: string, sourceAttribute: string}): void { + if(dynamicValue) { + this.dynamicValue.patchValue(dynamicValue, {emitEvent: false}); + } + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.dynamicValue.disable({emitEvent: false}); + } else { + this.dynamicValue.enable({emitEvent: false}); + } + } + + private updateModel() { + this.propagateChange(this.dynamicValue.value); + } +} diff --git a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-rule-condition-dialog.component.html b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-rule-condition-dialog.component.html index bc07daddbb..bc0b6f48bd 100644 --- a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-rule-condition-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-rule-condition-dialog.component.html @@ -1,6 +1,6 @@ -
-
+
+ {{('device-profile.condition' | translate) + ': '}} +
+
device-profile.schedule-days
@@ -73,8 +74,8 @@
+
device-profile.schedule-days
-
diff --git a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.scss b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.scss index 43a7243e1e..d2292126ec 100644 --- a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.scss +++ b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.ts b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.ts index d5c9f02876..f8d2e96bd1 100644 --- a/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/alarm/alarm-schedule.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -64,7 +64,6 @@ export class AlarmScheduleComponent implements ControlValueAccessor, Validator, alarmScheduleTypes = Object.keys(AlarmScheduleType); alarmScheduleType = AlarmScheduleType; alarmScheduleTypeTranslate = AlarmScheduleTypeTranslationMap; - dayOfWeekTranslationsArray = dayOfWeekTranslations; allDays = Array(7).fill(0).map((x, i) => i); @@ -91,8 +90,10 @@ export class AlarmScheduleComponent implements ControlValueAccessor, Validator, daysOfWeek: this.fb.array(new Array(7).fill(false), this.validateDayOfWeeks), startsOn: [0, Validators.required], endsOn: [0, Validators.required], - items: this.fb.array(Array.from({length: 7}, (value, i) => this.defaultItemsScheduler(i)), this.validateItems) + items: this.fb.array(Array.from({length: 7}, (value, i) => this.defaultItemsScheduler(i)), this.validateItems), + dynamicValue: [null] }); + this.alarmScheduleForm.get('type').valueChanges.subscribe((type) => { const defaultTimezone = getDefaultTimezone(); this.alarmScheduleForm.reset({type, items: this.defaultItems, timezone: defaultTimezone}, {emitEvent: false}); @@ -158,7 +159,8 @@ export class AlarmScheduleComponent implements ControlValueAccessor, Validator, timezone: this.modelValue.timezone, daysOfWeek, startsOn: utcTimestampToTimeOfDay(this.modelValue.startsOn), - endsOn: utcTimestampToTimeOfDay(this.modelValue.endsOn) + endsOn: utcTimestampToTimeOfDay(this.modelValue.endsOn), + dynamicValue: this.modelValue.dynamicValue }, {emitEvent: false}); break; case AlarmScheduleType.CUSTOM: @@ -177,7 +179,8 @@ export class AlarmScheduleComponent implements ControlValueAccessor, Validator, this.alarmScheduleForm.patchValue({ type: this.modelValue.type, timezone: this.modelValue.timezone, - items: alarmDays + items: alarmDays, + dynamicValue: this.modelValue.dynamicValue }, {emitEvent: false}); } break; diff --git a/ui-ngx/src/app/modules/home/components/profile/alarm/create-alarm-rules.component.html b/ui-ngx/src/app/modules/home/components/profile/alarm/create-alarm-rules.component.html index d7da1580e4..01c8d8bbf8 100644 --- a/ui-ngx/src/app/modules/home/components/profile/alarm/create-alarm-rules.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/alarm/create-alarm-rules.component.html @@ -1,6 +1,6 @@
+ +
+ + + + + +
+
+ tenant-profile.no-queue +
+
+ +
+
diff --git a/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.scss b/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.scss new file mode 100644 index 0000000000..189badf9fd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.scss @@ -0,0 +1,27 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +:host { + .tb-tenant-profile-queues { + .mat-expansion-panel-body { + padding-bottom: 0 !important; + } + } + + .tb-prompt{ + margin: 30px 0; + } +} diff --git a/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.ts b/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.ts new file mode 100644 index 0000000000..aa5325e974 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/profile/queue/tenant-profile-queues.component.ts @@ -0,0 +1,203 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnDestroy } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormArray, + FormBuilder, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + ValidationErrors, + Validator, + Validators +} from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@app/core/core.state'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { Subscription } from 'rxjs'; +import { QueueInfo } from '@shared/models/queue.models'; +import { UtilsService } from '@core/services/utils.service'; +import { guid } from '@core/utils'; + +@Component({ + selector: 'tb-tenant-profile-queues', + templateUrl: './tenant-profile-queues.component.html', + styleUrls: ['./tenant-profile-queues.component.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TenantProfileQueuesComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TenantProfileQueuesComponent), + multi: true, + } + ] +}) +export class TenantProfileQueuesComponent implements ControlValueAccessor, Validator, OnDestroy { + + tenantProfileQueuesFormGroup: FormGroup; + newQueue = false; + idMap = []; + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + @Input() + disabled: boolean; + + private valueChangeSubscription$: Subscription = null; + + private propagateChange = (v: any) => { }; + + constructor(private store: Store, + private utils: UtilsService, + private fb: FormBuilder) { + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + ngOnDestroy() { + if (this.valueChangeSubscription$) { + this.valueChangeSubscription$.unsubscribe(); + } + } + + registerOnTouched(fn: any): void { + } + + ngOnInit() { + this.tenantProfileQueuesFormGroup = this.fb.group({ + queues: this.fb.array([]) + }); + } + + get queuesFormArray(): FormArray { + return this.tenantProfileQueuesFormGroup.get('queues') as FormArray; + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.tenantProfileQueuesFormGroup.disable({emitEvent: false}); + } else { + this.tenantProfileQueuesFormGroup.enable({emitEvent: false}); + } + } + + writeValue(queues: Array | null): void { + if (this.valueChangeSubscription$) { + this.valueChangeSubscription$.unsubscribe(); + } + const queuesControls: Array = []; + if (queues) { + queues.forEach((queue, index) => { + if (!queue.id) { + if (!this.idMap[index]) { + this.idMap.push(guid()); + } + queue.id = this.idMap[index]; + } + queuesControls.push(this.fb.control(queue, [Validators.required])); + }); + } + this.tenantProfileQueuesFormGroup.setControl('queues', this.fb.array(queuesControls)); + if (this.disabled) { + this.tenantProfileQueuesFormGroup.disable({emitEvent: false}); + } else { + this.tenantProfileQueuesFormGroup.enable({emitEvent: false}); + } + this.valueChangeSubscription$ = this.tenantProfileQueuesFormGroup.valueChanges.subscribe(() => + this.updateModel() + ); + } + + public trackByQueue(index: number, queueControl: AbstractControl) { + if (queueControl) { + return queueControl.value.id; + } + return null; + } + + public removeQueue(index: number) { + (this.tenantProfileQueuesFormGroup.get('queues') as FormArray).removeAt(index); + this.idMap.splice(index, 1); + } + + public addQueue() { + const queue = { + id: guid(), + consumerPerPartition: false, + name: '', + packProcessingTimeout: 2000, + partitions: 10, + pollInterval: 25, + processingStrategy: { + failurePercentage: 0, + maxPauseBetweenRetries: 3, + pauseBetweenRetries: 3, + retries: 3, + type: '' + }, + submitStrategy: { + batchSize: 0, + type: '' + }, + topic: '', + additionalInfo: { + description: '' + } + }; + this.idMap.push(queue.id); + this.newQueue = true; + const queuesArray = this.tenantProfileQueuesFormGroup.get('queues') as FormArray; + queuesArray.push(this.fb.control(queue, [])); + this.tenantProfileQueuesFormGroup.updateValueAndValidity(); + if (!this.tenantProfileQueuesFormGroup.valid) { + this.updateModel(); + } + } + + getTitle(value): string { + return this.utils.customTranslation(value, value); + } + + public validate(c: AbstractControl): ValidationErrors | null { + return this.tenantProfileQueuesFormGroup.valid ? null : { + queues: { + valid: false, + }, + }; + } + + private updateModel() { + const queues: Array = this.tenantProfileQueuesFormGroup.get('queues').value; + this.propagateChange(queues); + } +} diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-autocomplete.component.html b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-autocomplete.component.html index 01789bb787..670332d0e4 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-autocomplete.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-autocomplete.component.html @@ -1,6 +1,6 @@
- - - -
tenant-profile.profile-configuration
-
-
- - - - -
+ +
diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-data.component.ts b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-data.component.ts index 4f2c5ba657..a6b02305d5 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-data.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-data.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -14,12 +14,13 @@ /// limitations under the License. /// -import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { Store } from '@ngrx/store'; import { AppState } from '@app/core/core.state'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { TenantProfileData } from '@shared/models/tenant.model'; +import { Subscription } from 'rxjs'; @Component({ selector: 'tb-tenant-profile-data', @@ -31,7 +32,7 @@ import { TenantProfileData } from '@shared/models/tenant.model'; multi: true }] }) -export class TenantProfileDataComponent implements ControlValueAccessor, OnInit { +export class TenantProfileDataComponent implements ControlValueAccessor, OnInit, OnDestroy { tenantProfileDataFormGroup: FormGroup; @@ -47,6 +48,7 @@ export class TenantProfileDataComponent implements ControlValueAccessor, OnInit @Input() disabled: boolean; + private valueChange$: Subscription = null; private propagateChange = (v: any) => { }; constructor(private store: Store, @@ -64,11 +66,17 @@ export class TenantProfileDataComponent implements ControlValueAccessor, OnInit this.tenantProfileDataFormGroup = this.fb.group({ configuration: [null, Validators.required] }); - this.tenantProfileDataFormGroup.valueChanges.subscribe(() => { + this.valueChange$ = this.tenantProfileDataFormGroup.valueChanges.subscribe(() => { this.updateModel(); }); } + ngOnDestroy() { + if (this.valueChange$) { + this.valueChange$.unsubscribe(); + } + } + setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (this.disabled) { @@ -79,7 +87,7 @@ export class TenantProfileDataComponent implements ControlValueAccessor, OnInit } writeValue(value: TenantProfileData | null): void { - this.tenantProfileDataFormGroup.patchValue({configuration: value?.configuration}, {emitEvent: false}); + this.tenantProfileDataFormGroup.patchValue({configuration: value}, {emitEvent: false}); } private updateModel() { @@ -87,7 +95,7 @@ export class TenantProfileDataComponent implements ControlValueAccessor, OnInit if (this.tenantProfileDataFormGroup.valid) { tenantProfileData = this.tenantProfileDataFormGroup.getRawValue(); } - this.propagateChange(tenantProfileData); + this.propagateChange(tenantProfileData?.configuration); } } diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-dialog.component.html b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-dialog.component.html index ef37564fd5..babe00ab1c 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant-profile-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/tenant-profile-dialog.component.html @@ -1,6 +1,6 @@
+
- - +
+ + + + + {{'tenant-profile.queues-with-count' | translate: + {count: entityForm.get('profileData').get('queueConfiguration').value ? + entityForm.get('profileData').get('queueConfiguration').value.length : 0} }} + + + + + + + + + +
tenant-profile.profile-configuration
+
+
+ + + + +
+
+
tenant-profile.description diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.scss b/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.scss index 309efb582c..f9940b3dae 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.scss +++ b/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,4 +25,21 @@ white-space: normal; } } + .fields-group { + padding: 0 16px 8px; + margin-bottom: 10px; + border: 1px groove rgba(0, 0, 0, .25); + border-radius: 4px; + legend { + color: rgba(0, 0, 0, .7); + width: fit-content; + } + } + + .mat-expansion-panel-header { + height: 48px; + } + .expansion-panel-block { + padding-bottom: 16px; + } } diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.ts b/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.ts index 24636b565c..413055fede 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.ts +++ b/ui-ngx/src/app/modules/home/components/profile/tenant-profile.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -18,16 +18,12 @@ import { ChangeDetectorRef, Component, Inject, Input, Optional } from '@angular/ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; -import { - createTenantProfileConfiguration, - TenantProfile, - TenantProfileData, - TenantProfileType -} from '@shared/models/tenant.model'; +import { createTenantProfileConfiguration, TenantProfile, TenantProfileType } from '@shared/models/tenant.model'; import { ActionNotificationShow } from '@app/core/notification/notification.actions'; import { TranslateService } from '@ngx-translate/core'; import { EntityTableConfig } from '@home/models/entity/entities-table-config.models'; import { EntityComponent } from '../entity/entity.component'; +import { guid } from '@core/utils'; @Component({ selector: 'tb-tenant-profile', @@ -57,27 +53,67 @@ export class TenantProfileComponent extends EntityComponent { } buildForm(entity: TenantProfile): FormGroup { - return this.fb.group( + const mainQueue = [ + { + id: guid(), + consumerPerPartition: true, + name: 'Main', + packProcessingTimeout: 2000, + partitions: 10, + pollInterval: 25, + processingStrategy: { + failurePercentage: 0, + maxPauseBetweenRetries: 3, + pauseBetweenRetries: 3, + retries: 3, + type: 'SKIP_ALL_FAILURES' + }, + submitStrategy: { + batchSize: 1000, + type: 'BURST' + }, + topic: 'tb_rule_engine.main', + additionalInfo: { + description: '' + } + } + ]; + const formGroup = this.fb.group( { name: [entity ? entity.name : '', [Validators.required, Validators.maxLength(255)]], isolatedTbCore: [entity ? entity.isolatedTbCore : false, []], isolatedTbRuleEngine: [entity ? entity.isolatedTbRuleEngine : false, []], - profileData: [entity && !this.isAdd ? entity.profileData : { - configuration: createTenantProfileConfiguration(TenantProfileType.DEFAULT) - } as TenantProfileData, []], + profileData: this.fb.group({ + configuration: [entity && !this.isAdd ? entity?.profileData.configuration + : createTenantProfileConfiguration(TenantProfileType.DEFAULT), []], + queueConfiguration: [entity && !this.isAdd ? entity?.profileData.queueConfiguration : null, []] + }), description: [entity ? entity.description : '', []], } ); + formGroup.get('isolatedTbRuleEngine').valueChanges.subscribe((value) => { + if (value) { + formGroup.get('profileData').patchValue({ + queueConfiguration: mainQueue + }, {emitEvent: false}); + } else { + formGroup.get('profileData').patchValue({ + queueConfiguration: null + }, {emitEvent: false}); + } + }); + return formGroup; } updateForm(entity: TenantProfile) { - this.entityForm.patchValue({name: entity.name}); - this.entityForm.patchValue({isolatedTbCore: entity.isolatedTbCore}); - this.entityForm.patchValue({isolatedTbRuleEngine: entity.isolatedTbRuleEngine}); - this.entityForm.patchValue({profileData: !this.isAdd ? entity.profileData : { - configuration: createTenantProfileConfiguration(TenantProfileType.DEFAULT) - } as TenantProfileData}); - this.entityForm.patchValue({description: entity.description}); + this.entityForm.patchValue({name: entity.name}, {emitEvent: false}); + this.entityForm.patchValue({isolatedTbCore: entity.isolatedTbCore}, {emitEvent: false}); + this.entityForm.patchValue({isolatedTbRuleEngine: entity.isolatedTbRuleEngine}, {emitEvent: false}); + this.entityForm.get('profileData').patchValue({ + configuration: !this.isAdd ? entity.profileData?.configuration : createTenantProfileConfiguration(TenantProfileType.DEFAULT) + }, {emitEvent: false}); + this.entityForm.get('profileData').patchValue({queueConfiguration: entity.profileData?.queueConfiguration}, {emitEvent: false}); + this.entityForm.patchValue({description: entity.description}, {emitEvent: false}); } updateFormState() { diff --git a/ui-ngx/src/app/modules/home/components/profile/tenant/default-tenant-profile-configuration.component.html b/ui-ngx/src/app/modules/home/components/profile/tenant/default-tenant-profile-configuration.component.html index 66cb503bd3..fef4d4cef5 100644 --- a/ui-ngx/src/app/modules/home/components/profile/tenant/default-tenant-profile-configuration.component.html +++ b/ui-ngx/src/app/modules/home/components/profile/tenant/default-tenant-profile-configuration.component.html @@ -1,6 +1,6 @@ + +
+ + admin.queue-name + + + {{ 'queue.name-required' | translate }} + + + {{ 'queue.name-unique' | translate }} + + + + queue.poll-interval + + + {{ 'queue.poll-interval-required' | translate }} + + + {{ 'queue.poll-interval-min-value' | translate }} + + + + queue.partitions + + + {{ 'queue.partitions-required' | translate }} + + + {{ 'queue.partitions-min-value' | translate }} + + + +
{{ 'queue.consumer-per-partition' | translate }}
+
{{'queue.consumer-per-partition-hint' | translate}}
+
+ + queue.processing-timeout + + + {{ 'queue.pack-processing-timeout-required' | translate }} + + + {{ 'queue.pack-processing-timeout-min-value' | translate }} + + + + + + + queue.submit-strategy + + + +
+ + queue.submit-strategy + + + {{ queueSubmitStrategyTypesMap.get(queueSubmitStrategyTypes[strategy]).label | translate }} + + + + {{ 'queue.submit-strategy-type-required' | translate }} + + + + queue.batch-size + + + {{ 'queue.batch-size-required' | translate }} + + + {{ 'queue.batch-size-min-value' | translate }} + + +
+
+
+ + + + queue.processing-strategy + + + +
+ + queue.processing-strategy + + + {{ queueProcessingStrategyTypesMap.get(queueProcessingStrategyTypes[strategy]).label | translate }} + + + + {{ 'queue.processing-strategy-type-required' | translate }} + + + + queue.retries + + + {{ 'queue.retries-required' | translate }} + + + {{ 'queue.retries-min-value' | translate }} + + + + queue.failure-percentage + + + {{ 'queue.failure-percentage-required' | translate }} + + + {{ 'queue.failure-percentage-min-value' | translate }} + + + {{ 'queue.failure-percentage-max-value' | translate }} + + + + queue.pause-between-retries + + + {{ 'queue.pause-between-retries-required' | translate }} + + + {{ 'queue.pause-between-retries-min-value' | translate }} + + + + queue.max-pause-between-retries + + + {{ 'queue.max-pause-between-retries-required' | translate }} + + + {{ 'queue.max-pause-between-retries-min-value' | translate }} + + +
+
+
+
+ + queue.description + + queue.description-hint + +
diff --git a/ui-ngx/src/app/modules/home/components/queue/queue-form.component.scss b/ui-ngx/src/app/modules/home/components/queue/queue-form.component.scss new file mode 100644 index 0000000000..13128ad29a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/queue/queue-form.component.scss @@ -0,0 +1,28 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host ::ng-deep { + .queue-strategy { + padding-bottom: 16px; + + .mat-expansion-panel-header { + height: 50px; + } + + .mat-expansion-panel-body { + padding-bottom: 0 !important; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/queue/queue-form.component.ts b/ui-ngx/src/app/modules/home/components/queue/queue-form.component.ts new file mode 100644 index 0000000000..b84dfc9985 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/queue/queue-form.component.ts @@ -0,0 +1,215 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { UtilsService } from '@core/services/utils.service'; +import { + QueueInfo, + QueueProcessingStrategyTypes, + QueueProcessingStrategyTypesMap, + QueueSubmitStrategyTypes, + QueueSubmitStrategyTypesMap +} from '@shared/models/queue.models'; +import { isDefinedAndNotNull } from '@core/utils'; +import { Subscription } from 'rxjs'; + +@Component({ + selector: 'tb-queue-form', + templateUrl: './queue-form.component.html', + styleUrls: ['./queue-form.component.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => QueueFormComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => QueueFormComponent), + multi: true, + } + ] +}) +export class QueueFormComponent implements ControlValueAccessor, OnInit, OnDestroy, Validator { + + @Input() + disabled: boolean; + + @Input() + newQueue = false; + + @Input() + systemQueue = false; + + queueFormGroup: FormGroup; + hideBatchSize = false; + + queueSubmitStrategyTypes = QueueSubmitStrategyTypes; + queueProcessingStrategyTypes = QueueProcessingStrategyTypes; + submitStrategies: string[] = Object.values(this.queueSubmitStrategyTypes); + processingStrategies: string[] = Object.values(this.queueProcessingStrategyTypes); + queueSubmitStrategyTypesMap = QueueSubmitStrategyTypesMap; + queueProcessingStrategyTypesMap = QueueProcessingStrategyTypesMap; + + private modelValue: QueueInfo; + private propagateChange = null; + private propagateChangePending = false; + private valueChange$: Subscription = null; + + constructor(private utils: UtilsService, + private fb: FormBuilder) { + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + if (this.propagateChangePending) { + this.propagateChangePending = false; + setTimeout(() => { + this.propagateChange(this.modelValue); + }, 0); + } + } + + registerOnTouched(fn: any): void { + } + + ngOnInit() { + this.queueFormGroup = this.fb.group( + { + name: ['', [Validators.required]], + pollInterval: [25, [Validators.min(1), Validators.required]], + partitions: [10, [Validators.min(1), Validators.required]], + consumerPerPartition: [false, []], + packProcessingTimeout: [2000, [Validators.min(1), Validators.required]], + submitStrategy: this.fb.group({ + type: [null, [Validators.required]], + batchSize: [null], + }), + processingStrategy: this.fb.group({ + type: [null, [Validators.required]], + retries: [3, [Validators.min(0), Validators.required]], + failurePercentage: [ 0, [Validators.min(0), Validators.required, Validators.max(100)]], + pauseBetweenRetries: [3, [Validators.min(1), Validators.required]], + maxPauseBetweenRetries: [3, [Validators.min(1), Validators.required]], + }), + topic: [''], + additionalInfo: this.fb.group({ + description: [''] + }) + }); + this.valueChange$ = this.queueFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.queueFormGroup.get('name').valueChanges.subscribe((value) => { + this.queueFormGroup.patchValue({topic: `tb_rule_engine.${value}`}); + }); + this.queueFormGroup.get('submitStrategy').get('type').valueChanges.subscribe(() => { + this.submitStrategyTypeChanged(); + }); + if (this.newQueue) { + this.queueFormGroup.get('name').enable({emitEvent: false}); + } else { + this.queueFormGroup.get('name').disable({emitEvent: false}); + } + } + + ngOnDestroy() { + if (this.valueChange$) { + this.valueChange$.unsubscribe(); + this.valueChange$ = null; + } + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.queueFormGroup.disable({emitEvent: false}); + } else { + this.queueFormGroup.enable({emitEvent: false}); + this.queueFormGroup.get('name').disable({emitEvent: false}); + } + } + + writeValue(value: QueueInfo): void { + this.propagateChangePending = false; + this.modelValue = value; + if (isDefinedAndNotNull(this.modelValue)) { + this.queueFormGroup.patchValue(this.modelValue, {emitEvent: false}); + this.queueFormGroup.get('additionalInfo').get('description') + .patchValue(this.modelValue.additionalInfo?.description, {emitEvent: false}); + this.submitStrategyTypeChanged(); + } + if (!this.disabled && !this.queueFormGroup.valid) { + this.updateModel(); + } + } + + public validate(c: FormControl) { + if (c.parent && !this.systemQueue) { + const queueName = c.value.name; + const profileQueues = []; + c.parent.getRawValue().forEach((queue) => { + profileQueues.push(queue.name); + } + ); + if (profileQueues.filter(profileQueue => profileQueue === queueName).length > 1) { + this.queueFormGroup.get('name').setErrors({ + unique: true + }); + } + } + return (this.queueFormGroup.valid) ? null : { + queue: { + valid: false, + }, + }; + } + + private updateModel() { + const value = this.queueFormGroup.value; + this.modelValue = {...this.modelValue, ...value}; + if (this.propagateChange) { + this.propagateChange(this.modelValue); + } else { + this.propagateChangePending = true; + } + } + + submitStrategyTypeChanged() { + const form = this.queueFormGroup.get('submitStrategy') as FormGroup; + const type: QueueSubmitStrategyTypes = form.get('type').value; + const batchSizeField = form.get('batchSize'); + if (type === QueueSubmitStrategyTypes.BATCH) { + batchSizeField.patchValue(1000, {emitEvent: false}); + batchSizeField.setValidators([Validators.min(1), Validators.required]); + this.hideBatchSize = true; + } else { + batchSizeField.patchValue(null, {emitEvent: false}); + batchSizeField.clearValidators(); + this.hideBatchSize = false; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/relation/relation-dialog.component.html b/ui-ngx/src/app/modules/home/components/relation/relation-dialog.component.html index 800ee57ad3..9ae32f6fd8 100644 --- a/ui-ngx/src/app/modules/home/components/relation/relation-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/relation/relation-dialog.component.html @@ -1,6 +1,6 @@ +
+
+ + admin.smpp-provider.smpp-version + + + {{smppVersion.value}} + + + + + admin.smpp-provider.smpp-host + + + {{'admin.smpp-provider.smpp-host-required' | translate}} + + + + admin.smpp-provider.smpp-port + + + {{'admin.smpp-provider.smpp-port-required' | translate}} + + +
+
+ + admin.smpp-provider.system-id + + + {{'admin.smpp-provider.system-id-required' | translate}} + + + + admin.smpp-provider.password + + + + {{'admin.smpp-provider.password-required' | translate}} + + +
+ + + + + admin.smpp-provider.type-settings + + + + + admin.smpp-provider.system-type + + + + admin.smpp-provider.bind-type + + + {{bindTypesTranslation.get(bindType) | translate}} + + + + + admin.smpp-provider.service-type + + + + + + + + admin.smpp-provider.source-settings + + + + + admin.smpp-provider.source-address + + + + admin.smpp-provider.source-ton + + + {{typeOfNumberMap.get(sourceTon).name | translate}} + + + + + admin.smpp-provider.source-npi + + + {{numberingPlanIdentificationMap.get(sourceNpi).name | translate}} + + + + + + + + + admin.smpp-provider.destination-settings + + + + + admin.smpp-provider.destination-ton + + + {{typeOfNumberMap.get(destinationTon).name | translate}} + + + + + admin.smpp-provider.destination-npi + + + {{numberingPlanIdentificationMap.get(destinationNpi).name | translate}} + + + + + + + + + admin.smpp-provider.additional-settings + + + + + admin.smpp-provider.address-range + + + + admin.smpp-provider.coding-scheme + + + {{codingSchemesMap.get(codingScheme).name | translate}} + + + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/sms/smpp-sms-provider-configuration.component.ts b/ui-ngx/src/app/modules/home/components/sms/smpp-sms-provider-configuration.component.ts new file mode 100644 index 0000000000..605af2cb51 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/sms/smpp-sms-provider-configuration.component.ts @@ -0,0 +1,137 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { + AwsSnsSmsProviderConfiguration, + BindTypes, + bindTypesTranslationMap, + CodingSchemes, + codingSchemesMap, + NumberingPlanIdentification, + numberingPlanIdentificationMap, + SmppSmsProviderConfiguration, + smppVersions, + SmsProviderConfiguration, + SmsProviderType, + TypeOfNumber, + typeOfNumberMap +} from '@shared/models/settings.models'; +import { isDefinedAndNotNull } from '@core/utils'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; + +@Component({ + selector: 'tb-smpp-sms-provider-configuration', + templateUrl: './smpp-sms-provider-configuration.component.html', + styleUrls: [], + providers: [{ + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => SmppSmsProviderConfigurationComponent), + multi: true + }] +}) + +export class SmppSmsProviderConfigurationComponent implements ControlValueAccessor, OnInit{ + constructor(private fb: FormBuilder) { + } + private requiredValue: boolean; + + get required(): boolean { + return this.requiredValue; + } + + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + @Input() + disabled: boolean; + + smppSmsProviderConfigurationFormGroup: FormGroup; + + smppVersions = smppVersions; + + bindTypes = Object.keys(BindTypes); + bindTypesTranslation = bindTypesTranslationMap; + + typeOfNumber = Object.keys(TypeOfNumber); + typeOfNumberMap = typeOfNumberMap; + + numberingPlanIdentification = Object.keys(NumberingPlanIdentification); + numberingPlanIdentificationMap = numberingPlanIdentificationMap; + + codingSchemes = Object.keys(CodingSchemes); + codingSchemesMap = codingSchemesMap; + + private propagateChange = (v: any) => { }; + + ngOnInit(): void { + this.smppSmsProviderConfigurationFormGroup = this.fb.group({ + protocolVersion: [null, [Validators.required]], + host: [null, [Validators.required]], + port: [null, [Validators.required]], + systemId: [null, [Validators.required]], + password: [null, [Validators.required]], + systemType: [null], + bindType: [null, []], + serviceType: [null, []], + sourceAddress: [null, []], + sourceTon: [null, []], + sourceNpi: [null, []], + destinationTon: [null, []], + destinationNpi: [null, []], + addressRange: [null, []], + codingScheme: [null, []], + }); + + this.smppSmsProviderConfigurationFormGroup.valueChanges.subscribe(() => { + this.updateValue(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.smppSmsProviderConfigurationFormGroup.disable({emitEvent: false}); + } else { + this.smppSmsProviderConfigurationFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: AwsSnsSmsProviderConfiguration | null): void { + if (isDefinedAndNotNull(value)) { + this.smppSmsProviderConfigurationFormGroup.patchValue(value, {emitEvent: false}); + } + } + + private updateValue() { + let configuration: SmppSmsProviderConfiguration = null; + if (this.smppSmsProviderConfigurationFormGroup.valid) { + configuration = this.smppSmsProviderConfigurationFormGroup.value; + (configuration as SmsProviderConfiguration).type = SmsProviderType.SMPP; + } + this.propagateChange(configuration); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/sms/sms-provider-configuration.component.html b/ui-ngx/src/app/modules/home/components/sms/sms-provider-configuration.component.html index d9964285e3..f4d9d0d1c9 100644 --- a/ui-ngx/src/app/modules/home/components/sms/sms-provider-configuration.component.html +++ b/ui-ngx/src/app/modules/home/components/sms/sms-provider-configuration.component.html @@ -1,6 +1,6 @@ - close
- DataKey; + generateDataKey: (chip: any, type: DataKeyType, datakeySettingsSchema: JsonSettingsSchema) => DataKey; fetchEntityKeys: (entityAliasId: string, types: Array) => Observable>; } diff --git a/ui-ngx/src/app/modules/home/components/widget/data-keys.component.scss b/ui-ngx/src/app/modules/home/components/widget/data-keys.component.scss index 2078ee2c81..68ce6f5262 100644 --- a/ui-ngx/src/app/modules/home/components/widget/data-keys.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/data-keys.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,49 +13,48 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -:host { - .mat-chip.mat-standard-chip { - overflow: hidden; - .tb-attribute-chip { - max-width: 100%; - color: rgb(66, 66, 66); - font-weight: normal; - font-size: 16px; +.mat-chip.mat-standard-chip.tb-datakey-chip { + overflow: hidden; - .tb-chip-drag-handle { - cursor: move; + .tb-attribute-chip { + max-width: 100%; + color: rgb(66, 66, 66); + font-weight: normal; + font-size: 16px; - mat-icon { - pointer-events: none; - } - } + .tb-chip-drag-handle { + cursor: move; - .tb-chip-labels { - display: flex; - flex-direction: row; - align-items: flex-end; - min-width: 0; - .tb-chip-label { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - } + mat-icon { + pointer-events: none; + } + } - .tb-chip-separator { - white-space: pre; - } + .tb-chip-labels { + display: flex; + flex-direction: row; + align-items: flex-end; + min-width: 0; + .tb-chip-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } - .mat-chip-remove.mat-icon { - width: 24px; - height: 24px; - font-size: 24px; - margin-left: 0; - color: inherit; - opacity: inherit; + .tb-chip-separator { + white-space: pre; } } + + .mat-chip-remove.mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + margin-left: 0; + color: inherit; + opacity: inherit; + } } } diff --git a/ui-ngx/src/app/modules/home/components/widget/data-keys.component.ts b/ui-ngx/src/app/modules/home/components/widget/data-keys.component.ts index ff7f5e2f0c..d2361bbf9d 100644 --- a/ui-ngx/src/app/modules/home/components/widget/data-keys.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/data-keys.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import { MatAutocomplete } from '@angular/material/autocomplete'; import { MatChipInputEvent, MatChipList } from '@angular/material/chips'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; -import { DataKey, DatasourceType, widgetType } from '@shared/models/widget.models'; +import { DataKey, DatasourceType, Widget, JsonSettingsSchema, widgetType } from '@shared/models/widget.models'; import { IAliasController } from '@core/api/widget-api.models'; import { DataKeysCallbacks } from './data-keys.component.models'; import { alarmFields } from '@shared/models/alarm.models'; @@ -61,6 +61,7 @@ import { } from '@home/components/widget/data-key-config-dialog.component'; import { deepClone } from '@core/utils'; import { MatChipDropEvent } from '@app/shared/components/mat-chip-draggable.directive'; +import { Dashboard } from '@shared/models/dashboard.models'; @Component({ selector: 'tb-data-keys', @@ -111,7 +112,16 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie aliasController: IAliasController; @Input() - datakeySettingsSchema: any; + datakeySettingsSchema: JsonSettingsSchema; + + @Input() + dataKeySettingsDirective: string; + + @Input() + dashboard: Dashboard; + + @Input() + widget: Widget; @Input() callbacks: DataKeysCallbacks; @@ -145,6 +155,7 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie dataKeyType: DataKeyType; placeholder: string; + secondaryPlaceholder: string; requiredText: string; searchText = ''; @@ -230,20 +241,34 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie private updateParams() { if (this.datasourceType === DatasourceType.function) { this.dataKeyType = DataKeyType.function; - this.placeholder = this.translate.instant('datakey.function-types'); this.requiredText = this.translate.instant('datakey.function-types-required'); + if (this.widgetType === widgetType.latest) { + this.placeholder = this.translate.instant('datakey.latest-key-functions'); + this.secondaryPlaceholder = '+' + this.translate.instant('datakey.latest-key-function'); + } else if (this.widgetType === widgetType.alarm) { + this.placeholder = this.translate.instant('datakey.alarm-key-functions'); + this.secondaryPlaceholder = '+' + this.translate.instant('alarm-key-function'); + } else { + this.placeholder = this.translate.instant('datakey.timeseries-key-functions'); + this.secondaryPlaceholder = '+' + this.translate.instant('datakey.timeseries-key-function'); + } } else { if (this.widgetType === widgetType.latest) { this.dataKeyType = null; + this.placeholder = this.translate.instant('datakey.latest-keys'); + this.secondaryPlaceholder = '+' + this.translate.instant('datakey.latest-key'); this.requiredText = this.translate.instant('datakey.timeseries-or-attributes-required'); } else if (this.widgetType === widgetType.alarm) { this.dataKeyType = null; + this.placeholder = this.translate.instant('datakey.alarm-keys'); + this.secondaryPlaceholder = '+' + this.translate.instant('datakey.alarm-key'); this.requiredText = this.translate.instant('datakey.alarm-fields-timeseries-or-attributes-required'); } else { this.dataKeyType = DataKeyType.timeseries; + this.placeholder = this.translate.instant('datakey.timeseries-keys'); + this.secondaryPlaceholder = '+' + this.translate.instant('datakey.timeseries-key'); this.requiredText = this.translate.instant('datakey.timeseries-required'); } - this.placeholder = ''; } } @@ -251,7 +276,7 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie if (this.widgetType === widgetType.alarm) { this.keys = this.utils.getDefaultAlarmDataKeys(); } else if (this.isEntityCountDatasource) { - this.keys = [this.callbacks.generateDataKey('count', DataKeyType.count)]; + this.keys = [this.callbacks.generateDataKey('count', DataKeyType.count, this.datakeySettingsSchema)]; } else { this.keys = []; } @@ -325,7 +350,7 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie } private addFromChipValue(chip: DataKey) { - const key = this.callbacks.generateDataKey(chip.name, chip.type); + const key = this.callbacks.generateDataKey(chip.name, chip.type, this.datakeySettingsSchema); this.addKey(key); } @@ -395,6 +420,10 @@ export class DataKeysComponent implements ControlValueAccessor, OnInit, AfterVie data: { dataKey: deepClone(key), dataKeySettingsSchema: this.datakeySettingsSchema, + dataKeySettingsDirective: this.dataKeySettingsDirective, + dashboard: this.dashboard, + aliasController: this.aliasController, + widget: this.widget, entityAliasId: this.entityAliasId, showPostProcessing: this.widgetType !== widgetType.alarm, callbacks: this.callbacks diff --git a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog-container.component.ts b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog-container.component.ts index 949cd89417..be717873da 100644 --- a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog-container.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog-container.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.component.ts index 0f518ab9ab..ce5b3badb8 100644 --- a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.service.ts b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.service.ts index a2d61a9eaa..0e0d200d5e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.service.ts +++ b/ui-ngx/src/app/modules/home/components/widget/dialog/custom-dialog.service.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog-token.ts b/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog-token.ts index 7a281c309e..5d0ee4733f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog-token.ts +++ b/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog-token.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog.component.html index ca4f2a56b7..2ae29c5f5b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/dialog/embed-dashboard-dialog.component.html @@ -1,6 +1,6 @@ - +
diff --git a/ui-ngx/src/app/modules/home/components/widget/legend.component.scss b/ui-ngx/src/app/modules/home/components/widget/legend.component.scss index f4e5284203..9aefd0c88d 100644 --- a/ui-ngx/src/app/modules/home/components/widget/legend.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/legend.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ &.tb-legend-row { width: auto; margin-left: auto; + margin-right: auto; } .tb-legend-header, diff --git a/ui-ngx/src/app/modules/home/components/widget/legend.component.ts b/ui-ngx/src/app/modules/home/components/widget/legend.component.ts index 004fd5087b..0074280732 100644 --- a/ui-ngx/src/app/modules/home/components/widget/legend.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/legend.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -60,11 +60,13 @@ export class LegendComponent implements OnInit { } legendKeys(): LegendKey[] { - let keys = this.legendData.keys; - if (this.legendConfig.sortDataKeys) { - keys = this.legendData.keys.sort((key1, key2) => key1.dataKey.label.localeCompare(key2.dataKey.label)); - } - return keys.filter(legendKey => this.legendData.keys[legendKey.dataIndex].dataKey.inLegend); + try { + let keys = this.legendData.keys; + if (this.legendConfig.sortDataKeys) { + keys = this.legendData.keys.sort((key1, key2) => key1.dataKey.label.localeCompare(key2.dataKey.label)); + } + return keys.filter(legendKey => this.legendData.keys[legendKey.dataIndex].dataKey.inLegend); + } catch (e) {} } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/alarm-filter-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/alarm-filter-panel.component.html index a252d37586..9741440574 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/alarm-filter-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/alarm-filter-panel.component.html @@ -1,6 +1,6 @@ -
, + private onDragendListener?, + snappable = false) { + this.circleData = this.map.convertToCircleFormat(JSON.parse(data[this.settings.circleKeyName])); + const centerPosition = this.createCenterPosition(); + const circleFillColor = this.getFillColor(); + const circleStrokeColor = this.getStrokeColor(); + this.leafletCircle = L.circle(centerPosition, { + radius: this.circleData.radius, + fillColor: circleFillColor, + color: circleStrokeColor, + weight: settings.circleStrokeWeight, + fillOpacity: settings.circleFillColorOpacity, + opacity: settings.circleStrokeOpacity, + pmIgnore: !settings.editableCircle, + snapIgnore: !snappable + }).addTo(this.map.map); + + if (settings.showCircleLabel) { + this.updateLabel(); + } + + if (settings.showCircleTooltip) { + this.tooltip = createTooltip(this.leafletCircle, settings, data.$datasource, + settings.autoCloseCircleTooltip, settings.showCircleTooltipAction); + this.updateTooltip(); + } + + this.createEventListeners(); + } + + private createEventListeners() { + if (this.settings.editableCircle && this.onDragendListener) { + // Change center position (call in drag drop mode) + this.leafletCircle.on('pm:dragstart', () => this.editing = true); + this.leafletCircle.on('pm:dragend', () => this.editing = false); + // Change radius (call in edit mode) + this.leafletCircle.on('pm:markerdragstart', () => this.editing = true); + this.leafletCircle.on('pm:markerdragend', () => this.editing = false); + this.leafletCircle.on('pm:edit', (e) => this.onDragendListener(e, this.data)); + } + + if (this.settings.circleClick) { + this.leafletCircle.on('click', (event: LeafletMouseEvent) => { + for (const action in this.settings.circleClick) { + if (typeof (this.settings.circleClick[action]) === 'function') { + this.settings.circleClick[action](event.originalEvent, this.data.$datasource); + } + } + }); + } + } + + private updateLabel() { + this.leafletCircle.unbindTooltip(); + if (this.settings.showCircleLabel) { + if (!this.map.circleLabelText || this.settings.useCircleLabelFunction) { + const pattern = this.settings.useCircleLabelFunction ? + safeExecute(this.settings.parsedCircleLabelFunction, + [this.data, this.dataSources, this.data.dsIndex]) : this.settings.circleLabel; + this.map.circleLabelText = parseWithTranslation.prepareProcessPattern(pattern, true); + this.map.replaceInfoTooltipCircle = processDataPattern(this.map.circleLabelText, this.data); + } + const circleLabelText = fillDataPattern(this.map.circleLabelText, this.map.replaceInfoTooltipCircle, this.data); + const labelColor = this.map.ctx.widgetConfig.color; + this.leafletCircle.bindTooltip(`
${circleLabelText}
`, + { className: 'tb-polygon-label', permanent: true, sticky: true, direction: 'center'}) + .openTooltip(this.leafletCircle.getLatLng()); + } + } + + private updateTooltip() { + const pattern = this.settings.useCircleTooltipFunction ? + safeExecute(this.settings.parsedCircleTooltipFunction, [this.data, this.dataSources, this.data.dsIndex]) : + this.settings.circleTooltipPattern; + this.tooltip.setContent(parseWithTranslation.parseTemplate(pattern, this.data, true)); + } + + private updateCircleColor() { + const circleFillColor = this.getFillColor(); + const circleStrokeColor = this.getStrokeColor(); + const style: L.PathOptions = { + fillColor: circleFillColor, + color: circleStrokeColor + }; + this.leafletCircle.setStyle(style); + } + + updateCircle(data: FormattedData, dataSources: FormattedData[]) { + if (this.editing) { + return; + } + this.data = data; + this.dataSources = dataSources; + this.circleData = this.map.convertToCircleFormat(JSON.parse(data[this.settings.circleKeyName])); + const newCenterPosition = this.createCenterPosition(); + if (!this.leafletCircle.getLatLng().equals(newCenterPosition) && !this.editing) { + this.leafletCircle.setLatLng(newCenterPosition); + } + if (this.leafletCircle.getRadius() !== this.circleData.radius) { + this.leafletCircle.setRadius(this.circleData.radius); + } + if (this.settings.showCircleLabel) { + this.updateLabel(); + } + if (this.settings.showCircleTooltip) { + this.updateTooltip(); + } + if (this.settings.useCircleStrokeColorFunction || this.settings.useCircleFillColorFunction) { + this.updateCircleColor(); + } + } + + private createCenterPosition(): L.LatLng { + return new L.LatLng(this.circleData.latitude, this.circleData.longitude); + } + + private getFillColor(): string | null { + return functionValueCalculator(this.settings.useCircleFillColorFunction, this.settings.parsedCircleFillColorFunction, + [this.data, this.dataSources, this.data.dsIndex], this.settings.circleFillColor); + } + + private getStrokeColor(): string | null { + return functionValueCalculator(this.settings.useCircleStrokeColorFunction, this.settings.parsedCircleStrokeColorFunction, + [this.data, this.dataSources, this.data.dsIndex], this.settings.circleStrokeColor); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/common-maps-utils.ts b/ui-ngx/src/app/modules/home/components/widget/lib/maps/common-maps-utils.ts index 9f1810f82f..a1d4e8b5b6 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/common-maps-utils.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/common-maps-utils.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ /// limitations under the License. /// -import { FormattedData, MapProviders, ReplaceInfo } from '@home/components/widget/lib/maps/map-models'; +import { MapProviders } from '@home/components/widget/lib/maps/map-models'; import { createLabelFromDatasource, hashCode, @@ -27,28 +27,9 @@ import { } from '@core/utils'; import { Observable, Observer, of } from 'rxjs'; import { map } from 'rxjs/operators'; -import { Datasource, DatasourceData } from '@shared/models/widget.models'; -import _ from 'lodash'; -import { mapProviderSchema, providerSets } from '@home/components/widget/lib/maps/schemes'; -import { addCondition, mergeSchemes } from '@core/schema-utils'; +import { FormattedData } from '@shared/models/widget.models'; import L from 'leaflet'; -export function getProviderSchema(mapProvider: MapProviders, ignoreImageMap = false) { - const providerSchema = _.cloneDeep(mapProviderSchema); - if (mapProvider) { - providerSchema.schema.properties.provider.default = mapProvider; - } - if (ignoreImageMap) { - providerSchema.form[0].items = providerSchema.form[0]?.items.filter(item => item.value !== 'image-map'); - } - return mergeSchemes([providerSchema, - ...Object.keys(providerSets)?.map( - (key: string) => { - const setting = providerSets[key]; - return addCondition(setting?.schema, `model.provider === '${setting.name}'`); - })]); -} - export function getRatio(firsMoment: number, secondMoment: number, intermediateMoment: number): number { return (intermediateMoment - firsMoment) / (secondMoment - firsMoment); } @@ -76,9 +57,12 @@ export function findAngle(startPoint: FormattedData, endPoint: FormattedData, la } -export function getDefCenterPosition(position) { +export function getDefCenterPosition(position): [number, number] { if (typeof (position) === 'string') { - return position.split(','); + const parts = position.split(','); + if (parts.length === 2) { + return [Number(parts[0]), Number(parts[1])]; + } } if (typeof (position) === 'object') { return position; @@ -123,6 +107,7 @@ export function aspectCache(imageUrl: string): Observable { return aspect; })); } + return of(0); } export type TranslateFunc = (key: string, defaultTranslation?: string) => string; @@ -138,7 +123,7 @@ function createButtonElement(actionName: string, actionText: string) { return ``; } -function parseTemplate(template: string, data: { $datasource?: Datasource, [key: string]: any }, +function parseTemplate(template: string, data: FormattedData, translateFn?: TranslateFunc) { let res = ''; try { @@ -207,67 +192,6 @@ function parseTemplate(template: string, data: { $datasource?: Datasource, [key: return res; } -export function processPattern(template: string, data: { $datasource?: Datasource, [key: string]: any }): Array { - const replaceInfo = []; - try { - const reg = /\${([^}]*)}/g; - let match = reg.exec(template); - while (match !== null) { - const variableInfo: ReplaceInfo = { - dataKeyName: '', - valDec: 2, - variable: '' - }; - const variable = match[0]; - let label = match[1]; - let valDec = 2; - const splitValues = label.split(':'); - if (splitValues.length > 1) { - label = splitValues[0]; - valDec = parseFloat(splitValues[1]); - } - - variableInfo.variable = variable; - variableInfo.valDec = valDec; - - if (label.startsWith('#')) { - const keyIndexStr = label.substring(1); - const n = Math.floor(Number(keyIndexStr)); - if (String(n) === keyIndexStr && n >= 0) { - variableInfo.dataKeyName = data.$datasource.dataKeys[n].label; - } - } else { - variableInfo.dataKeyName = label; - } - replaceInfo.push(variableInfo); - - match = reg.exec(template); - } - } catch (ex) { - console.log(ex, template); - } - return replaceInfo; -} - -export function fillPattern(markerLabelText: string, replaceInfoLabelMarker: Array, data: FormattedData) { - let text = createLabelFromDatasource(data.$datasource, markerLabelText); - if (replaceInfoLabelMarker) { - for (const variableInfo of replaceInfoLabelMarker) { - let txtVal = ''; - if (variableInfo.dataKeyName && isDefinedAndNotNull(data[variableInfo.dataKeyName])) { - const varData = data[variableInfo.dataKeyName]; - if (isNumber(varData)) { - txtVal = padValue(varData, variableInfo.valDec); - } else { - txtVal = varData; - } - } - text = text.replace(variableInfo.variable, txtVal); - } - } - return text; -} - function prepareProcessPattern(template: string, translateFn?: TranslateFunc): string { if (translateFn) { template = translateFn(template); @@ -307,7 +231,7 @@ export const parseWithTranslation = { throw Error('Translate not assigned'); } }, - parseTemplate(template: string, data: object, forceTranslate = false): string { + parseTemplate(template: string, data: FormattedData, forceTranslate = false): string { return parseTemplate(forceTranslate ? this.translate(template) : template, data, this.translate.bind(this)); }, prepareProcessPattern(template: string, forceTranslate = false): string { @@ -318,106 +242,6 @@ export const parseWithTranslation = { } }; -export function parseData(input: DatasourceData[], dataIndex?: number): FormattedData[] { - return _(input).groupBy(el => el?.datasource.entityName + el?.datasource.entityType) - .values().value().map((entityArray, i) => { - const obj: FormattedData = { - entityName: entityArray[0]?.datasource?.entityName, - entityId: entityArray[0].datasource.entityId, - entityType: entityArray[0].datasource.entityType, - $datasource: entityArray[0].datasource, - dsIndex: i, - deviceType: null - }; - entityArray.filter(el => el.data.length).forEach(el => { - const index = isDefined(dataIndex) ? dataIndex : el.data.length - 1; - if (!obj.hasOwnProperty(el.dataKey.label) || el.data[index][1] !== '') { - obj[el.dataKey.label] = el.data[index][1]; - obj[el.dataKey.label + '|ts'] = el.data[index][0]; - if (el.dataKey.label.toLowerCase() === 'type') { - obj.deviceType = el.data[index][1]; - } - } - }); - return obj; - }); -} - -export function flatData(input: FormattedData[]): FormattedData { - let result: FormattedData = {} as FormattedData; - if (input.length) { - for (const toMerge of input) { - result = {...result, ...toMerge}; - } - result.entityName = input[0].entityName; - result.entityId = input[0].entityId; - result.entityType = input[0].entityType; - result.$datasource = input[0].$datasource; - result.dsIndex = input[0].dsIndex; - result.deviceType = input[0].deviceType; - } - return result; -} - -export function parseArray(input: DatasourceData[]): FormattedData[][] { - return _(input).groupBy(el => el.datasource.entityName) - .values().value().map((entityArray, dsIndex) => { - const timeDataMap: {[time: number]: FormattedData} = {}; - entityArray.filter(e => e.data.length).forEach(entity => { - entity.data.forEach(tsData => { - const time = tsData[0]; - const value = tsData[1]; - let data = timeDataMap[time]; - if (!data) { - data = { - entityName: entity.datasource.entityName, - entityId: entity.datasource.entityId, - entityType: entity.datasource.entityType, - $datasource: entity.datasource, - dsIndex, - time, - deviceType: null - }; - timeDataMap[time] = data; - } - data[entity.dataKey.label] = value; - data[entity.dataKey.label + '|ts'] = time; - if (entity.dataKey.label.toLowerCase() === 'type') { - data.deviceType = value; - } - }); - }); - return _.values(timeDataMap); - }); -} - -export function parseFunction(source: any, params: string[] = ['def']): (...args: any[]) => any { - let res = null; - if (source?.length) { - try { - res = new Function(...params, source); - } - catch (err) { - res = null; - } - } - return res; -} - -export function safeExecute(func: (...args: any[]) => any, params = []) { - let res = null; - if (func && typeof (func) === 'function') { - try { - res = func(...params); - } - catch (err) { - console.log('error in external function:', err); - res = null; - } - } - return res; -} - export function functionValueCalculator(useFunction: boolean, func: (...args: any[]) => any, params = [], defaultValue: any) { let res; if (useFunction && isDefined(func) && isFunction(func)) { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/maps/dialogs/select-entity-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/maps/dialogs/select-entity-dialog.component.html index 93fa72c84b..de34d1e01b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/maps/dialogs/select-entity-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/maps/dialogs/select-entity-dialog.component.html @@ -1,6 +1,6 @@ -
-
+
+
{{ value }} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.scss index 4d9ea4f814..1b097fe150 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.ts index 547f91b7bb..3105d68f66 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/knob.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/led-indicator.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/led-indicator.component.html index 64fe8a9ca9..31ebe769b0 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/led-indicator.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/led-indicator.component.html @@ -1,6 +1,6 @@ + + +

{{ 'widgets.persistent-table.add-title' | translate }}

+ + +
+ + +
+
+
+
+ + {{ rpcMessageTypeText }} + +
+
+ + widgets.persistent-table.method + + + {{'widgets.persistent-table.method-error' | translate}} + + + {{'widgets.persistent-table.white-space-error' | translate}} + + + + widgets.persistent-table.retries + + +
+
+ + +
+ + + + widgets.persistent-table.additional-info + + + + + + + +
+
+
+
+ + +
+ +
+
+ diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss new file mode 100644 index 0000000000..4958d4efa8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.scss @@ -0,0 +1,30 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host ::ng-deep { + .add-dialog { + + .params-json-editor, + .additional-json-editor { + .tb-json-object-panel { + margin: 0 0 16px; + } + + .mat-expansion-panel-body { + padding-bottom: 0 !important; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts new file mode 100644 index 0000000000..6e81d98ce7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-add-dialog.component.ts @@ -0,0 +1,75 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, OnInit } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { RequestData } from '@shared/models/rpc.models'; +import { TranslateService } from '@ngx-translate/core'; + +@Component({ + selector: 'tb-persistent-add-dialog', + templateUrl: './persistent-add-dialog.component.html', + styleUrls: ['./persistent-add-dialog.component.scss'] +}) + +export class PersistentAddDialogComponent extends DialogComponent implements OnInit { + + public persistentFormGroup: FormGroup; + public rpcMessageTypeText: string; + + private requestData: RequestData = null; + + constructor(protected store: Store, + protected router: Router, + public dialogRef: MatDialogRef, + private fb: FormBuilder, + private translate: TranslateService) { + super(store, router, dialogRef); + + this.persistentFormGroup = this.fb.group( + { + method: ['', [Validators.required, Validators.pattern(/^\S+$/)]], + oneWayElseTwoWay: [false], + retries: [null, [Validators.pattern(/^-?[0-9]+$/), Validators.min(0)]], + params: [null], + additionalInfo: [null] + } + ); + } + + save() { + this.requestData = this.persistentFormGroup.value; + this.close(); + } + + ngOnInit(): void { + this.rpcMessageTypeText = this.translate.instant('widgets.persistent-table.message-types.false'); + this.persistentFormGroup.get('oneWayElseTwoWay').valueChanges.subscribe( + () => { + this.rpcMessageTypeText = this.translate.instant(`widgets.persistent-table.message-types.${this.persistentFormGroup.get('oneWayElseTwoWay').value}`); + } + ); + } + + close(): void { + this.dialogRef.close(this.requestData); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html new file mode 100644 index 0000000000..b9e57b4bbd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.html @@ -0,0 +1,118 @@ + +
+ +

{{ persistentFormGroup.get('rpcId').value }}

+ + +
+ + +
+
+
+
+ + widgets.persistent-table.created-time + + + + widgets.persistent-table.expiration-time + + +
+
+ + widgets.persistent-table.message-type + + + + widgets.persistent-table.status + + + + widgets.persistent-table.method + + + + widgets.persistent-table.retries + + +
+ + + + + + {{ 'widgets.persistent-table.response' | translate }} + + + + + + + + {{ 'widgets.persistent-table.params' | translate }} + + + + + + + + + + {{ 'widgets.persistent-table.additional-info' | translate }} + + + + + + + + +
+
+
+ + +
+ +
+
+ diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceJsonSqlTest.java b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss similarity index 60% rename from application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceJsonSqlTest.java rename to ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss index 598041f0ee..9025d6199e 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/provision/sql/CoapProvisionDeviceJsonSqlTest.java +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.coap.provision.sql; +:host ::ng-deep { + .rpc-dialog { + .mat-expansion-panel-body { + padding-bottom: 0 !important; + } -import org.thingsboard.server.transport.coap.provision.AbstractCoapProvisionJsonDeviceTest; -import org.thingsboard.server.dao.service.DaoSqlTest; + .tb-json-object-panel { + margin: 0 0 16px 0; + } + } -@DaoSqlTest -public class CoapProvisionDeviceJsonSqlTest extends AbstractCoapProvisionJsonDeviceTest { + .tb-audit-log-response-data { + width: 100%; + min-width: 400px; + height: 100%; + min-height: 100px; + border: 1px solid #c0c0c0; + } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts new file mode 100644 index 0000000000..a072ea312b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-details-dialog.component.ts @@ -0,0 +1,126 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { DatePipe } from '@angular/common'; +import { TranslateService } from '@ngx-translate/core'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { DeviceService } from '@core/http/device.service'; +import { PersistentRpc, RpcStatus, rpcStatusColors, rpcStatusTranslation } from '@shared/models/rpc.models'; +import { NULL_UUID } from '@shared/models/id/has-uuid'; +import { DialogService } from '@core/services/dialog.service'; + +export interface PersistentDetailsDialogData { + persistentRequest: PersistentRpc; + allowDelete: boolean; +} + +@Component({ + selector: 'tb-persistent-details-dialog', + templateUrl: './persistent-details-dialog.component.html', + styleUrls: ['./persistent-details-dialog.component.scss'] +}) + +export class PersistentDetailsDialogComponent extends DialogComponent implements OnInit { + + @ViewChild('responseDataEditor', {static: true}) + responseDataEditorElmRef: ElementRef; + + public persistentFormGroup: FormGroup; + public rpcStatusColorsMap = rpcStatusColors; + public rpcStatus = RpcStatus; + public allowDelete: boolean; + + private persistentUpdated = false; + private responseData: string; + + constructor(protected store: Store, + protected router: Router, + private datePipe: DatePipe, + private translate: TranslateService, + @Inject(MAT_DIALOG_DATA) public data: PersistentDetailsDialogData, + public dialogRef: MatDialogRef, + private dialogService: DialogService, + private deviceService: DeviceService, + private fb: FormBuilder) { + super(store, router, dialogRef); + + this.allowDelete = data.allowDelete; + + this.persistentFormGroup = this.fb.group( + { + rpcId: [''], + createdTime: [''], + expirationTime: [''], + messageType: [''], + status: [''], + method: [''], + params: [''], + retries: [''], + response: [''], + additionalInfo: [''] + } + ); + this.loadPersistentFields(data.persistentRequest); + this.responseData = JSON.stringify(data.persistentRequest.response, null, 2); + } + + loadPersistentFields(request: PersistentRpc) { + this.persistentFormGroup.patchValue({ + rpcId: this.translate.instant('widgets.persistent-table.details-title') + request.id.id, + createdTime: this.datePipe.transform(request.createdTime, 'yyyy-MM-dd HH:mm:ss'), + expirationTime: this.datePipe.transform(request.expirationTime, 'yyyy-MM-dd HH:mm:ss'), + messageType: this.translate.instant('widgets.persistent-table.message-types.' + request.request.oneway), + status: this.translate.instant(rpcStatusTranslation.get(request.status)), + method: request.request.body.method, + retries: request.request.retries || null, + response: request.response || null, + params: JSON.parse(request.request.body.params) || null, + additionalInfo: request.additionalInfo || null + }, {emitEvent: false}); + } + + ngOnInit(): void { + } + + close(): void { + this.dialogRef.close(this.persistentUpdated); + } + + deleteRpcRequest() { + const persistentRpc = this.data.persistentRequest; + if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) { + this.dialogService.confirm( + this.translate.instant('widgets.persistent-table.delete-request-title'), + this.translate.instant('widgets.persistent-table.delete-request-text'), + this.translate.instant('action.no'), + this.translate.instant('action.yes') + ).subscribe((res) => { + if (res) { + this.deviceService.deletePersistedRpc(persistentRpc.id.id).subscribe(() => { + this.persistentUpdated = true; + this.close(); + }); + } + }); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html new file mode 100644 index 0000000000..b3bb295ed2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.html @@ -0,0 +1,44 @@ + +
+ + widgets.persistent-table.rpc-status-list + + + {{ 'widgets.persistent-table.rpc-search-status-all' | translate }} + + + {{ rpcSearchStatusTranslationMap.get(searchStatus) | translate }} + + + +
+ + +
+ diff --git a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestSqlIntegrationTest.java b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss similarity index 57% rename from application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestSqlIntegrationTest.java rename to ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss index bb01f20b11..45ba061843 100644 --- a/application/src/test/java/org/thingsboard/server/transport/coap/attributes/request/sql/CoapAttributesRequestSqlIntegrationTest.java +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.thingsboard.server.transport.coap.attributes.request.sql; +:host { + width: 100%; + height: 100%; + min-width: 300px; + overflow: hidden; + background: #fff; + border-radius: 4px; + box-shadow: + 0 7px 8px -4px rgba(0, 0, 0, .2), + 0 13px 19px 2px rgba(0, 0, 0, .14), + 0 5px 24px 4px rgba(0, 0, 0, .12); -import org.thingsboard.server.transport.coap.attributes.request.AbstractCoapAttributesRequestIntegrationTest; -import org.thingsboard.server.dao.service.DaoSqlTest; + .mat-content { + overflow: hidden; + background-color: #fff; + } -@DaoSqlTest -public class CoapAttributesRequestSqlIntegrationTest extends AbstractCoapAttributesRequestIntegrationTest { + .mat-padding { + padding: 16px; + } } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts new file mode 100644 index 0000000000..e3d46dfca3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-filter-panel.component.ts @@ -0,0 +1,67 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, Inject, InjectionToken } from '@angular/core'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { OverlayRef } from '@angular/cdk/overlay'; +import { RpcStatus, rpcStatusTranslation } from '@shared/models/rpc.models'; +import { TranslateService } from '@ngx-translate/core'; + +export const PERSISTENT_FILTER_PANEL_DATA = new InjectionToken('AlarmFilterPanelData'); + +export interface PersistentFilterPanelData { + rpcStatus: RpcStatus; +} + +@Component({ + selector: 'tb-persistent-filter-panel', + templateUrl: './persistent-filter-panel.component.html', + styleUrls: ['./persistent-filter-panel.component.scss'] +}) +export class PersistentFilterPanelComponent { + + public persistentFilterFormGroup: FormGroup; + public result: PersistentFilterPanelData; + public rpcSearchStatusTranslationMap = rpcStatusTranslation; + public rpcSearchPlaceholder: string; + + public persistentSearchStatuses = Object.keys(RpcStatus); + + constructor(@Inject(PERSISTENT_FILTER_PANEL_DATA) + public data: PersistentFilterPanelData, + public overlayRef: OverlayRef, + private fb: FormBuilder, + private translate: TranslateService) { + this.persistentFilterFormGroup = this.fb.group( + { + rpcStatus: this.data.rpcStatus + } + ); + this.rpcSearchPlaceholder = this.translate.instant('widgets.persistent-table.any-status'); + } + + update() { + this.result = { + rpcStatus: this.persistentFilterFormGroup.get('rpcStatus').value + }; + this.overlayRef.dispose(); + } + + cancel() { + this.overlayRef.dispose(); + } +} + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html new file mode 100644 index 0000000000..7614d7e0e6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.html @@ -0,0 +1,126 @@ + +
+
+
+
+ + + {{ 'widgets.persistent-table.rpc-id' | translate }} + + + {{ column.id.id }} + + + + + {{ 'widgets.persistent-table.created-time' | translate }} + + + {{ column.createdTime | date:'yyyy-MM-dd HH:mm:ss' }} + + + + + {{ 'widgets.persistent-table.expiration-time' | translate }} + + + {{ column.expirationTime | date:'yyyy-MM-dd HH:mm:ss' }} + + + + + {{ 'widgets.persistent-table.status' | translate }} + + + {{ rpcStatusTranslation.get(column.status) | translate }} + + + + + {{ 'widgets.persistent-table.message-type' | translate }} + + + {{ 'widgets.persistent-table.message-types.' + column.request.oneway | translate }} + + + + + {{ 'widgets.persistent-table.method' | translate }} + + + {{ column.request.body.method }} + + + + + + +
+ + + +
+
+ + + + + + +
+
+
+ + +
+ {{ noDataDisplayMessageText }} + {{ 'common.loading' | translate }} +
+ + +
+ diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss new file mode 100644 index 0000000000..842d53d143 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.scss @@ -0,0 +1,53 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + width: 100%; + height: 100%; + display: block; + .tb-table-widget { + .table-container { + position: relative; + } + + .mat-table { + .mat-row { + &.invisible { + visibility: hidden; + } + } + } + + span.no-data-found { + position: absolute; + top: 60px; + bottom: 0; + left: 0; + right: 0; + } + + .column-id { + min-width: 250px; + max-width: 250px; + width: 250px; + } + + .column-time { + min-width: 120px; + max-width: 120px; + width: 120px; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts new file mode 100644 index 0000000000..5beef7ea8c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/persistent-table.component.ts @@ -0,0 +1,582 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { + ChangeDetectorRef, + Component, + ElementRef, + Injector, + Input, + OnInit, + StaticProvider, + ViewChild, + ViewContainerRef +} from '@angular/core'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { WidgetContext } from '@home/models/widget-component.models'; +import { WidgetConfig } from '@shared/models/widget.models'; +import { IWidgetSubscription } from '@core/api/widget-api.models'; +import { BehaviorSubject, merge, Observable, of, ReplaySubject, Subject, throwError } from 'rxjs'; +import { catchError, map, tap } from 'rxjs/operators'; +import { + constructTableCssString, + noDataMessage, + TableCellButtonActionDescriptor, + TableWidgetSettings +} from '@home/components/widget/lib/table-widget.models'; +import cssjs from '@core/css/css'; +import { UtilsService } from '@core/services/utils.service'; +import { TranslateService } from '@ngx-translate/core'; +import { hashCode, isDefined, isNumber } from '@core/utils'; +import { CollectionViewer, DataSource } from '@angular/cdk/collections'; +import { emptyPageData, PageData } from '@shared/models/page/page-data'; +import { + PersistentRpc, + PersistentRpcData, + RequestData, + RpcStatus, + rpcStatusColors, + rpcStatusTranslation +} from '@shared/models/rpc.models'; +import { PageLink } from '@shared/models/page/page-link'; +import { Direction, SortOrder, sortOrderFromString } from '@shared/models/page/sort-order'; +import { MatPaginator } from '@angular/material/paginator'; +import { MatSort } from '@angular/material/sort'; +import { NULL_UUID } from '@shared/models/id/has-uuid'; +import { DialogService } from '@core/services/dialog.service'; +import { DeviceService } from '@core/http/device.service'; +import { MatDialog } from '@angular/material/dialog'; +import { + PersistentDetailsDialogComponent, + PersistentDetailsDialogData +} from '@home/components/widget/lib/rpc/persistent-details-dialog.component'; +import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; +import { ComponentPortal } from '@angular/cdk/portal'; +import { + PERSISTENT_FILTER_PANEL_DATA, + PersistentFilterPanelComponent, + PersistentFilterPanelData +} from '@home/components/widget/lib/rpc/persistent-filter-panel.component'; +import { PersistentAddDialogComponent } from '@home/components/widget/lib/rpc/persistent-add-dialog.component'; +import { ResizeObserver } from '@juggle/resize-observer'; +import { hidePageSizePixelValue } from '@shared/models/constants'; +import { HttpErrorResponse } from '@angular/common/http'; + +interface PersistentTableWidgetSettings extends TableWidgetSettings { + defaultSortOrder: string; + defaultPageSize: number; + displayPagination: boolean; + enableStickyAction: boolean; + enableStickyHeader: boolean; + enableFilter: boolean; + displayColumns: string[]; + displayDetails: boolean; + allowDelete: boolean; + allowSendRequest: boolean; +} + +interface PersistentTableWidgetActionDescriptor extends TableCellButtonActionDescriptor { + details?: boolean; + delete?: boolean; +} + +@Component({ + selector: 'tb-persistent-table-widget', + templateUrl: './persistent-table.component.html', + styleUrls: ['./persistent-table.component.scss' , '../table-widget.scss'] +}) + +export class PersistentTableComponent extends PageComponent implements OnInit { + + @Input() + ctx: WidgetContext; + + @ViewChild(MatPaginator) paginator: MatPaginator; + @ViewChild(MatSort) sort: MatSort; + + private settings: PersistentTableWidgetSettings; + private widgetConfig: WidgetConfig; + private subscription: IWidgetSubscription; + private enableFilterAction = true; + private allowSendRequest = true; + private defaultPageSize = 10; + private defaultSortOrder = '-createdTime'; + private rpcStatusFilter: RpcStatus; + private displayDetails = true; + private allowDelete = true; + private displayTableColumns: string[]; + private widgetResize$: ResizeObserver; + + public persistentDatasource: PersistentDatasource; + public noDataDisplayMessageText: string; + public rpcStatusColor = rpcStatusColors; + public rpcStatusTranslation = rpcStatusTranslation; + public displayPagination = true; + public enableStickyHeader = true; + public enableStickyAction = true; + public pageLink: PageLink; + public pageSizeOptions; + public actionCellButtonAction: PersistentTableWidgetActionDescriptor[] = []; + public displayedColumns: string[]; + public hidePageSize = false; + hasData = false; + + constructor(protected store: Store, + private elementRef: ElementRef, + private overlay: Overlay, + private viewContainerRef: ViewContainerRef, + private utils: UtilsService, + private translate: TranslateService, + private dialogService: DialogService, + private deviceService: DeviceService, + private dialog: MatDialog, + private cd: ChangeDetectorRef) { + super(store); + } + + ngOnInit() { + this.ctx.$scope.persistentTableWidget = this; + this.settings = this.ctx.settings; + this.widgetConfig = this.ctx.widgetConfig; + this.subscription = this.ctx.defaultSubscription; + this.initializeConfig(); + this.hasData = this.ctx.defaultSubscription.hasResolvedData; + this.ctx.updateWidgetParams(); + if (this.displayPagination) { + this.widgetResize$ = new ResizeObserver(() => { + const showHidePageSize = this.elementRef.nativeElement.offsetWidth < hidePageSizePixelValue; + if (showHidePageSize !== this.hidePageSize) { + this.hidePageSize = showHidePageSize; + this.cd.markForCheck(); + } + }); + this.widgetResize$.observe(this.elementRef.nativeElement); + } + } + + ngOnDestroy() { + if (this.widgetResize$) { + this.widgetResize$.disconnect(); + } + } + + ngAfterViewInit(): void { + if (this.displayPagination) { + this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); + } + ((this.displayPagination ? merge(this.sort.sortChange, this.paginator.page) : this.sort.sortChange) as Observable) + .pipe( + tap(() => this.updateData()) + ) + .subscribe(); + this.updateData(); + } + + private initializeConfig() { + + this.displayPagination = isDefined(this.settings.displayPagination) ? this.settings.displayPagination : true; + this.enableStickyHeader = isDefined(this.settings.enableStickyHeader) ? this.settings.enableStickyHeader : true; + this.displayTableColumns = isDefined(this.settings.displayColumns) ? this.settings.displayColumns : []; + this.enableStickyAction = isDefined(this.settings.enableStickyAction) ? this.settings.enableStickyAction : true; + this.enableFilterAction = isDefined(this.settings.enableFilter) ? this.settings.enableFilter : true; + this.displayDetails = isDefined(this.settings.displayDetails) ? this.settings.displayDetails : true; + this.allowDelete = isDefined(this.settings.allowDelete) ? this.settings.allowDelete : true; + this.allowSendRequest = isDefined(this.settings.allowSendRequest) ? this.settings.allowSendRequest : true; + + this.noDataDisplayMessageText = + noDataMessage(this.widgetConfig.noDataDisplayMessage, 'widgets.persistent-table.no-request-prompt', this.utils, this.translate); + + this.displayedColumns = [...this.displayTableColumns]; + + const pageSize = this.settings.defaultPageSize; + if (isDefined(pageSize) && isNumber(pageSize) && pageSize > 0) { + this.defaultPageSize = pageSize; + } + this.pageSizeOptions = [this.defaultPageSize, this.defaultPageSize * 2, this.defaultPageSize * 3]; + if (this.settings.defaultSortOrder && this.settings.defaultSortOrder.length) { + this.defaultSortOrder = this.settings.defaultSortOrder; + } + const sortOrder: SortOrder = sortOrderFromString(this.defaultSortOrder); + this.pageLink = new PageLink(this.defaultPageSize, 0, null, sortOrder); + this.pageLink.pageSize = this.displayPagination ? this.defaultPageSize : 1024; + + + this.ctx.widgetActions = [ + { + name: 'widgets.persistent-table.add', + show: this.allowSendRequest, + icon: 'add', + onAction: $event => this.addPersistentRpcRequest($event) + }, + { + name: 'widgets.persistent-table.refresh', + show: true, + icon: 'refresh', + onAction: () => this.reloadPersistentRequests() + }, + { + name: 'widgets.persistent-table.filter', + show: this.enableFilterAction, + icon: 'filter_list', + onAction: $event => this.editFilter($event) + } + ]; + + if (this.settings.displayDetails) { + this.actionCellButtonAction.push( + { + displayName: this.translate.instant('widgets.persistent-table.details'), + icon: 'more_horiz', + details: true + } as PersistentTableWidgetActionDescriptor + ); + } + if (this.settings.allowDelete) { + this.actionCellButtonAction.push( + { + displayName: this.translate.instant('widgets.persistent-table.delete'), + icon: 'delete', + delete: true + } as PersistentTableWidgetActionDescriptor + ); + } + if (this.actionCellButtonAction.length) { + this.displayedColumns.push('actions'); + } + + this.persistentDatasource = new PersistentDatasource(this.translate, this.subscription, this.ctx); + + const cssString = constructTableCssString(this.widgetConfig); + const cssParser = new cssjs(); + cssParser.testMode = false; + const namespace = 'persistent-table-' + hashCode(cssString); + cssParser.cssPreviewNamespace = namespace; + cssParser.createStyleElement(namespace, cssString); + $(this.elementRef.nativeElement).addClass(namespace); + } + + private updateData() { + if (this.displayPagination) { + this.pageLink.page = this.paginator.pageIndex; + this.pageLink.pageSize = this.paginator.pageSize; + } else { + this.pageLink.page = 0; + } + if (this.settings.defaultSortOrder && this.settings.defaultSortOrder.length) { + this.defaultSortOrder = this.utils.customTranslation(this.settings.defaultSortOrder, this.settings.defaultSortOrder); + } + this.pageLink.sortOrder.property = this.sort.active; + this.pageLink.sortOrder.direction = Direction[this.sort.direction.toUpperCase()]; + this.persistentDatasource.loadPersistent(this.pageLink, this.rpcStatusFilter); + this.ctx.detectChanges(); + } + + public onDataUpdated() { + this.ctx.detectChanges(); + } + + reloadPersistentRequests() { + if (this.displayPagination) { + this.paginator.pageIndex = 0; + } + this.updateData(); + } + + deleteRpcRequest($event: Event, persistentRpc: PersistentRpc) { + if ($event) { + $event.stopPropagation(); + } + if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) { + this.dialogService.confirm( + this.translate.instant('widgets.persistent-table.delete-request-title'), + this.translate.instant('widgets.persistent-table.delete-request-text'), + this.translate.instant('action.no'), + this.translate.instant('action.yes') + ).subscribe((res) => { + if (res) { + this.deviceService.deletePersistedRpc(persistentRpc.id.id).subscribe(() => { + this.reloadPersistentRequests(); + }); + } + }); + } + } + + openRequestDetails($event: Event, persistentRpc: PersistentRpc) { + if ($event) { + $event.stopPropagation(); + } + if (persistentRpc && persistentRpc.id && persistentRpc.id.id !== NULL_UUID) { + this.dialog.open + (PersistentDetailsDialogComponent, + { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + persistentRequest: persistentRpc, + allowDelete: this.allowDelete + } + }).afterClosed().subscribe( + (res) => { + if (res) { + this.reloadPersistentRequests(); + } + } + ); + } + } + + addPersistentRpcRequest($event: Event){ + if ($event) { + $event.stopPropagation(); + } + this.dialog.open + (PersistentAddDialogComponent, + { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'] + }).afterClosed().subscribe( + (requestData) => { + if (requestData) { + this.sendRequests(requestData); + } + } + ); + } + + private sendRequests(requestData: RequestData) { + let commandPromise; + if (requestData.oneWayElseTwoWay) { + commandPromise = this.ctx.controlApi.sendOneWayCommand( + requestData.method, + requestData.params, null, + true, null, + requestData.retries, + requestData.additionalInfo + ); + } else { + commandPromise = this.ctx.controlApi.sendTwoWayCommand( + requestData.method, + requestData.params, + null, + true, null, + requestData.retries, + requestData.additionalInfo + ); + } + commandPromise.subscribe( + () => { + this.reloadPersistentRequests(); + } + ); + } + + public onActionButtonClick($event: Event, persistentRpc: PersistentRpc, actionDescriptor: PersistentTableWidgetActionDescriptor) { + if (actionDescriptor.details) { + this.openRequestDetails($event, persistentRpc); + } + if (actionDescriptor.delete) { + this.deleteRpcRequest($event, persistentRpc); + } + } + + private editFilter($event: Event) { + if ($event) { + $event.stopPropagation(); + } + const target = $event.target || $event.srcElement || $event.currentTarget; + const config = new OverlayConfig(); + config.backdropClass = 'cdk-overlay-transparent-backdrop'; + config.hasBackdrop = true; + const connectedPosition: ConnectedPosition = { + originX: 'end', + originY: 'bottom', + overlayX: 'end', + overlayY: 'top' + }; + config.positionStrategy = this.overlay.position().flexibleConnectedTo(target as HTMLElement) + .withPositions([connectedPosition]); + + const overlayRef = this.overlay.create(config); + overlayRef.backdropClick().subscribe(() => { + overlayRef.dispose(); + }); + const providers: StaticProvider[] = [ + { + provide: PERSISTENT_FILTER_PANEL_DATA, + useValue: { + rpcStatus: this.rpcStatusFilter + } as PersistentFilterPanelData + }, + { + provide: OverlayRef, + useValue: overlayRef + } + ]; + const injector = Injector.create({parent: this.viewContainerRef.injector, providers}); + const componentRef = overlayRef.attach(new ComponentPortal(PersistentFilterPanelComponent, + this.viewContainerRef, injector)); + componentRef.onDestroy(() => { + if (componentRef.instance.result) { + const result = componentRef.instance.result; + this.rpcStatusFilter = result.rpcStatus; + this.reloadPersistentRequests(); + } + }); + this.ctx.detectChanges(); + } +} + +class PersistentDatasource implements DataSource { + + private persistentSubject = new BehaviorSubject([]); + private pageDataSubject = new BehaviorSubject>(emptyPageData()); + + private rpcErrorText: string; + private executingSubjects: Array>; + private executingRpcRequest = false; + + public dataLoading = true; + public pageData$ = this.pageDataSubject.asObservable(); + + constructor(private translate: TranslateService, + private subscription: IWidgetSubscription, + private ctx: WidgetContext) { + } + + connect(collectionViewer: CollectionViewer): Observable> { + return this.persistentSubject.asObservable(); + } + + disconnect(collectionViewer: CollectionViewer): void { + this.persistentSubject.complete(); + this.pageDataSubject.complete(); + } + + reset() { + const pageData = emptyPageData(); + this.persistentSubject.next(pageData.data); + this.pageDataSubject.next(pageData); + } + + loadPersistent(pageLink: PageLink, rpcStatusFilter: RpcStatus) { + this.dataLoading = true; + + const result = new ReplaySubject>(); + this.fetchEntities(pageLink, rpcStatusFilter).pipe( + catchError(() => of(emptyPageData())), + ).subscribe( + (pageData) => { + this.persistentSubject.next(pageData.data); + this.pageDataSubject.next(pageData); + result.next(pageData); + this.dataLoading = false; + } + ); + return result; + } + + fetchEntities(pageLink: PageLink, rpcStatusFilter: RpcStatus): Observable> { + if (!this.subscription.rpcEnabled) { + return throwError(new Error('Rpc disabled!')); + } else if (!this.subscription.targetDeviceId) { + return throwError(new Error('Target device is not set!')); + } + const rpcSubject: Subject = new Subject(); + + this.ctx.deviceService.getPersistedRpcRequests(this.subscription.targetDeviceId, pageLink, rpcStatusFilter).subscribe( + (responseBody) => { + rpcSubject.next(responseBody); + rpcSubject.complete(); + }, + (rejection: HttpErrorResponse) => { + this.rpcErrorText = null; + this.executingSubjects = []; + + const index = this.executingSubjects.indexOf(rpcSubject); + if (index >= 0) { + this.executingSubjects.splice(index, 1); + } + this.executingRpcRequest = this.executingSubjects.length > 0; + this.subscription.options.callbacks.rpcStateChanged(this.subscription); + if (!this.executingRpcRequest || rejection.status === 504) { + this.subscription.rpcRejection = rejection; + if (rejection.status === 504) { + this.subscription.rpcErrorText = 'Request Timeout.'; + } else { + this.subscription.rpcErrorText = 'Error : ' + rejection.status + ' - ' + rejection.statusText; + const error = this.extractRejectionErrorText(rejection); + if (error) { + this.subscription.rpcErrorText += '
'; + this.subscription.rpcErrorText += error.message || ''; + } + } + this.subscription.callbacks.onRpcFailed(this.subscription); + } + rpcSubject.error(rejection); + } + ); + return rpcSubject.asObservable(); + } + + extractRejectionErrorText(rejection: HttpErrorResponse) { + let error = null; + if (rejection.error) { + error = rejection.error; + try { + error = rejection.error ? JSON.parse(rejection.error) : null; + } catch (e) {} + } + if (error && !error.message) { + error = this.prepareMessageFromData(error); + } else if (error && error.message) { + error = error.message; + } + return error; + } + + prepareMessageFromData(data) { + if (typeof data === 'object' && data.constructor === ArrayBuffer) { + const msg = String.fromCharCode.apply(null, new Uint8Array(data)); + try { + const msgObj = JSON.parse(msg); + if (msgObj.message) { + return msgObj.message; + } else { + return msg; + } + } catch (e) { + return msg; + } + } else { + return data; + } + } + + isEmpty(): Observable { + return this.persistentSubject.pipe( + map((requests) => !requests.length) + ); + } + + total(): Observable { + return this.pageDataSubject.pipe( + map((pageData) => pageData.totalElements) + ); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html index a7b1306133..425f7ee37a 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/round-switch.component.html @@ -1,6 +1,6 @@ -
+
{{ error }} @@ -37,3 +37,14 @@
+ +
+
+ {{title}} + +
+ +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.scss index 293246c79e..a261ee6b71 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.scss +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.ts index 697c837a6e..96c36337a7 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/rpc/switch.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ /// limitations under the License. /// -import { Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; +import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { WidgetContext } from '@home/models/widget-component.models'; import { UtilsService } from '@core/services/utils.service'; @@ -26,11 +26,14 @@ import { DatasourceType, widgetType } from '@shared/models/widget.models'; import { EntityType } from '@shared/models/entity-type.models'; import { MatSlideToggle } from '@angular/material/slide-toggle'; import { ResizeObserver } from '@juggle/resize-observer'; +import { ThemePalette } from '@angular/material/core/common-behaviors/color'; const switchAspectRation = 2.7893; type RetrieveValueMethod = 'rpc' | 'attribute' | 'timeseries'; +type SwitchType = 'switch' | 'slide-toggle'; + interface SwitchSettings { initialValue: boolean; title: string; @@ -44,6 +47,8 @@ interface SwitchSettings { requestTimeout: number; requestPersistent: boolean; persistentPollingInterval: number; + labelPosition: 'before' | 'after'; + sliderColor: ThemePalette; } @Component({ @@ -51,28 +56,33 @@ interface SwitchSettings { templateUrl: './switch.component.html', styleUrls: ['./switch.component.scss'] }) -export class SwitchComponent extends PageComponent implements OnInit, OnDestroy { - - @ViewChild('switch', {static: true}) switchElementRef: ElementRef; - @ViewChild('switchContainer', {static: true}) switchContainerRef: ElementRef; - @ViewChild('matSlideToggle', {static: true}) matSlideToggleRef: MatSlideToggle; - @ViewChild('onoffContainer', {static: true}) onoffContainerRef: ElementRef; - @ViewChild('onLabel', {static: true}) onLabelRef: ElementRef; - @ViewChild('offLabel', {static: true}) offLabelRef: ElementRef; - @ViewChild('switchTitleContainer', {static: true}) switchTitleContainerRef: ElementRef; - @ViewChild('switchTitle', {static: true}) switchTitleRef: ElementRef; - @ViewChild('textMeasure', {static: true}) textMeasureRef: ElementRef; - @ViewChild('switchErrorContainer', {static: true}) switchErrorContainerRef: ElementRef; - @ViewChild('switchError', {static: true}) switchErrorRef: ElementRef; +export class SwitchComponent extends PageComponent implements OnInit, AfterViewInit, OnDestroy { + + @ViewChild('switch', {static: false}) switchElementRef: ElementRef; + @ViewChild('switchContainer', {static: false}) switchContainerRef: ElementRef; + @ViewChild('matSlideToggle', {static: false}) matSlideToggleRef: MatSlideToggle; + @ViewChild('onoffContainer', {static: false}) onoffContainerRef: ElementRef; + @ViewChild('onLabel', {static: false}) onLabelRef: ElementRef; + @ViewChild('offLabel', {static: false}) offLabelRef: ElementRef; + @ViewChild('switchTitleContainer', {static: false}) switchTitleContainerRef: ElementRef; + @ViewChild('switchTitle', {static: false}) switchTitleRef: ElementRef; + @ViewChild('textMeasure', {static: false}) textMeasureRef: ElementRef; + @ViewChild('switchErrorContainer', {static: false}) switchErrorContainerRef: ElementRef; + @ViewChild('switchError', {static: false}) switchErrorRef: ElementRef; @Input() ctx: WidgetContext; + @Input() + switchType: SwitchType = 'switch'; + showTitle = false; value = false; error = ''; title = ''; showOnOffLabels = false; + labelPosition: 'before' | 'after' = 'after'; + sliderColor: ThemePalette = 'accent'; private isSimulated: boolean; private requestTimeout: number; @@ -87,7 +97,7 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy private valueSubscription: IWidgetSubscription; - private executingUpdateValue: boolean; + public executingUpdateValue: boolean; private scheduledValue: boolean; private rpcValue: boolean; @@ -111,22 +121,27 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy } ngOnInit(): void { - this.switchElement = $(this.switchElementRef.nativeElement); - this.switchContainer = $(this.switchContainerRef.nativeElement); - this.matSlideToggle = $(this.matSlideToggleRef._elementRef.nativeElement); - this.onoffContainer = $(this.onoffContainerRef.nativeElement); - this.onLabel = $(this.onLabelRef.nativeElement); - this.offLabel = $(this.offLabelRef.nativeElement); - this.switchTitleContainer = $(this.switchTitleContainerRef.nativeElement); - this.switchTitle = $(this.switchTitleRef.nativeElement); - this.textMeasure = $(this.textMeasureRef.nativeElement); - this.switchErrorContainer = $(this.switchErrorContainerRef.nativeElement); - this.switchError = $(this.switchErrorRef.nativeElement); - - this.switchResize$ = new ResizeObserver(() => { - this.resize(); - }); - this.switchResize$.observe(this.switchContainerRef.nativeElement); + } + + ngAfterViewInit() { + if (this.switchType === 'switch') { + this.switchElement = $(this.switchElementRef.nativeElement); + this.switchContainer = $(this.switchContainerRef.nativeElement); + this.matSlideToggle = $(this.matSlideToggleRef._elementRef.nativeElement); + this.onoffContainer = $(this.onoffContainerRef.nativeElement); + this.onLabel = $(this.onLabelRef.nativeElement); + this.offLabel = $(this.offLabelRef.nativeElement); + this.switchTitleContainer = $(this.switchTitleContainerRef.nativeElement); + this.switchTitle = $(this.switchTitleRef.nativeElement); + this.textMeasure = $(this.textMeasureRef.nativeElement); + this.switchErrorContainer = $(this.switchErrorContainerRef.nativeElement); + this.switchError = $(this.switchErrorRef.nativeElement); + + this.switchResize$ = new ResizeObserver(() => { + this.resize(); + }); + this.switchResize$.observe(this.switchContainerRef.nativeElement); + } this.init(); } @@ -145,6 +160,8 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy this.title = isDefined(settings.title) ? settings.title : ''; this.showTitle = !!(this.title && this.title.length); this.showOnOffLabels = isDefined(settings.showOnOffLabels) ? settings.showOnOffLabels : true; + this.labelPosition = isDefined(settings.labelPosition) ? settings.labelPosition : 'after'; + this.sliderColor = isDefined(settings.sliderColor) ? settings.sliderColor : 'accent'; const initialValue = isDefined(settings.initialValue) ? settings.initialValue : false; this.setValue(initialValue); @@ -256,7 +273,9 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy private onError(error: string) { this.error = error; - this.setFontSize(this.switchError, this.error, this.switchErrorContainer.height(), this.switchErrorContainer.width()); + if (this.switchType === 'switch') { + this.setFontSize(this.switchError, this.error, this.switchErrorContainer.height(), this.switchErrorContainer.width()); + } this.ctx.detectChanges(); } @@ -278,6 +297,10 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy }, () => { const errorText = this.ctx.defaultSubscription.rpcErrorText; + if (this.switchType === 'slide-toggle') { + this.ctx.defaultSubscription.rpcErrorText = null; + this.ctx.hideToast(this.ctx.toastTargetId); + } this.onError(errorText); } ); @@ -304,6 +327,10 @@ export class SwitchComponent extends PageComponent implements OnInit, OnDestroy () => { this.executingUpdateValue = false; const errorText = this.ctx.defaultSubscription.rpcErrorText; + if (this.switchType === 'slide-toggle') { + this.ctx.defaultSubscription.rpcErrorText = null; + this.ctx.hideToast(this.ctx.toastTargetId); + } this.onError(errorText); } ); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings.models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings.models.ts index f7aac069a3..e5089d3070 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings.models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings.models.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.html new file mode 100644 index 0000000000..6931d256e8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.html @@ -0,0 +1,95 @@ + +
+ + widgets.table.column-width + + +
+ widgets.table.cell-style + + + + + {{ 'widgets.table.use-cell-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.table.cell-content + + + + + {{ 'widgets.table.use-cell-content-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+ + widgets.table.default-column-visibility + + + {{ 'widgets.table.column-visibility-visible' | translate }} + + + {{ 'widgets.table.column-visibility-hidden' | translate }} + + + + + widgets.table.column-selection-to-display + + + {{ 'widgets.table.column-selection-to-display-enabled' | translate }} + + + {{ 'widgets.table.column-selection-to-display-disabled' | translate }} + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.ts new file mode 100644 index 0000000000..9f9cbbf5e1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-key-settings.component.ts @@ -0,0 +1,86 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-alarms-table-key-settings', + templateUrl: './alarms-table-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class AlarmsTableKeySettingsComponent extends WidgetSettingsComponent { + + alarmsTableKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.alarmsTableKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + columnWidth: '0px', + useCellStyleFunction: false, + cellStyleFunction: '', + useCellContentFunction: false, + cellContentFunction: '', + defaultColumnVisibility: 'visible', + columnSelectionToDisplay: 'enabled' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.alarmsTableKeySettingsForm = this.fb.group({ + columnWidth: [settings.columnWidth, []], + useCellStyleFunction: [settings.useCellStyleFunction, []], + cellStyleFunction: [settings.cellStyleFunction, [Validators.required]], + useCellContentFunction: [settings.useCellContentFunction, []], + cellContentFunction: [settings.cellContentFunction, [Validators.required]], + defaultColumnVisibility: [settings.defaultColumnVisibility, []], + columnSelectionToDisplay: [settings.columnSelectionToDisplay, []], + }); + } + + protected validatorTriggers(): string[] { + return ['useCellStyleFunction', 'useCellContentFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const useCellStyleFunction: boolean = this.alarmsTableKeySettingsForm.get('useCellStyleFunction').value; + const useCellContentFunction: boolean = this.alarmsTableKeySettingsForm.get('useCellContentFunction').value; + if (useCellStyleFunction) { + this.alarmsTableKeySettingsForm.get('cellStyleFunction').enable(); + } else { + this.alarmsTableKeySettingsForm.get('cellStyleFunction').disable(); + } + if (useCellContentFunction) { + this.alarmsTableKeySettingsForm.get('cellContentFunction').enable(); + } else { + this.alarmsTableKeySettingsForm.get('cellContentFunction').disable(); + } + this.alarmsTableKeySettingsForm.get('cellStyleFunction').updateValueAndValidity({emitEvent}); + this.alarmsTableKeySettingsForm.get('cellContentFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.html new file mode 100644 index 0000000000..3b5516c26c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.html @@ -0,0 +1,110 @@ + +
+
+ widgets.table.common-table-settings + + widgets.table.alarms-table-title + + +
+
+ + {{ 'widgets.table.enable-alarms-selection' | translate }} + + + {{ 'widgets.table.enable-alarms-search' | translate }} + + + {{ 'widgets.table.enable-select-column-display' | translate }} + + + {{ 'widgets.table.enable-alarm-filter' | translate }} + +
+
+ + {{ 'widgets.table.enable-sticky-header' | translate }} + + + {{ 'widgets.table.enable-sticky-action' | translate }} + +
+
+ + widgets.table.hidden-cell-button-display-mode + + + {{ 'widgets.table.show-empty-space-hidden-action' | translate }} + + + {{ 'widgets.table.dont-reserve-space-hidden-action' | translate }} + + + +
+ + {{ 'widgets.table.display-alarm-details' | translate }} + + + {{ 'widgets.table.allow-alarms-ack' | translate }} + + + {{ 'widgets.table.allow-alarms-clear' | translate }} + +
+ + {{ 'widgets.table.display-pagination' | translate }} + + + widgets.table.default-page-size + + +
+ + widgets.table.default-sort-order + + +
+
+
+ widgets.table.row-style + + + + + {{ 'widgets.table.use-row-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.ts new file mode 100644 index 0000000000..c57ae7d6f5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component.ts @@ -0,0 +1,104 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-alarms-table-widget-settings', + templateUrl: './alarms-table-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class AlarmsTableWidgetSettingsComponent extends WidgetSettingsComponent { + + alarmsTableWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.alarmsTableWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + alarmsTitle: '', + enableSelection: true, + enableSearch: true, + enableSelectColumnDisplay: true, + enableFilter: true, + enableStickyHeader: true, + enableStickyAction: true, + reserveSpaceForHiddenAction: 'true', + displayDetails: true, + allowAcknowledgment: true, + allowClear: true, + displayPagination: true, + defaultPageSize: 10, + defaultSortOrder: '-createdTime', + useRowStyleFunction: false, + rowStyleFunction: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.alarmsTableWidgetSettingsForm = this.fb.group({ + alarmsTitle: [settings.alarmsTitle, []], + enableSelection: [settings.enableSelection, []], + enableSearch: [settings.enableSearch, []], + enableSelectColumnDisplay: [settings.enableSelectColumnDisplay, []], + enableFilter: [settings.enableFilter, []], + enableStickyHeader: [settings.enableStickyHeader, []], + enableStickyAction: [settings.enableStickyAction, []], + reserveSpaceForHiddenAction: [settings.reserveSpaceForHiddenAction, []], + displayDetails: [settings.displayDetails, []], + allowAcknowledgment: [settings.allowAcknowledgment, []], + allowClear: [settings.allowClear, []], + displayPagination: [settings.displayPagination, []], + defaultPageSize: [settings.defaultPageSize, [Validators.min(1)]], + defaultSortOrder: [settings.defaultSortOrder, []], + useRowStyleFunction: [settings.useRowStyleFunction, []], + rowStyleFunction: [settings.rowStyleFunction, [Validators.required]] + }); + } + + protected validatorTriggers(): string[] { + return ['useRowStyleFunction', 'displayPagination']; + } + + protected updateValidators(emitEvent: boolean) { + const useRowStyleFunction: boolean = this.alarmsTableWidgetSettingsForm.get('useRowStyleFunction').value; + const displayPagination: boolean = this.alarmsTableWidgetSettingsForm.get('displayPagination').value; + if (useRowStyleFunction) { + this.alarmsTableWidgetSettingsForm.get('rowStyleFunction').enable(); + } else { + this.alarmsTableWidgetSettingsForm.get('rowStyleFunction').disable(); + } + if (displayPagination) { + this.alarmsTableWidgetSettingsForm.get('defaultPageSize').enable(); + } else { + this.alarmsTableWidgetSettingsForm.get('defaultPageSize').disable(); + } + this.alarmsTableWidgetSettingsForm.get('rowStyleFunction').updateValueAndValidity({emitEvent}); + this.alarmsTableWidgetSettingsForm.get('defaultPageSize').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.html new file mode 100644 index 0000000000..0a9d442775 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.html @@ -0,0 +1,65 @@ + +
+
+ widgets.dashboard-state.dashboard-state-settings + + + + + + + + + + + + + widget-config.advanced-settings + + + + + {{ 'widgets.dashboard-state.autofill-state-layout' | translate }} + + + widgets.dashboard-state.default-margin + + + + + + {{ 'widgets.dashboard-state.sync-parent-state-params' | translate }} + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.ts new file mode 100644 index 0000000000..7c8d9de6e4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component.ts @@ -0,0 +1,99 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, ViewChild } from '@angular/core'; +import { WidgetActionType, WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Observable, of } from 'rxjs'; +import { map, mergeMap, startWith } from 'rxjs/operators'; + +@Component({ + selector: 'tb-dashboard-state-widget-settings', + templateUrl: './dashboard-state-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class DashboardStateWidgetSettingsComponent extends WidgetSettingsComponent { + + @ViewChild('dashboardStateInput') dashboardStateInput: ElementRef; + + dashboardStateWidgetSettingsForm: FormGroup; + + filteredDashboardStates: Observable>; + dashboardStateSearchText = ''; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.dashboardStateWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + stateId: '', + defaultAutofillLayout: true, + defaultMargin: 0, + defaultBackgroundColor: '#fff', + syncParentStateParams: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.dashboardStateWidgetSettingsForm = this.fb.group({ + stateId: [settings.stateId, []], + defaultAutofillLayout: [settings.defaultAutofillLayout, []], + defaultMargin: [settings.defaultMargin, [Validators.min(0)]], + defaultBackgroundColor: [settings.defaultBackgroundColor, []], + syncParentStateParams: [settings.syncParentStateParams, []] + }); + this.dashboardStateSearchText = ''; + this.filteredDashboardStates = this.dashboardStateWidgetSettingsForm.get('stateId').valueChanges + .pipe( + startWith(''), + map(value => value ? value : ''), + mergeMap(name => this.fetchDashboardStates(name) ) + ); + } + + public clearDashboardState(value: string = '') { + this.dashboardStateInput.nativeElement.value = value; + this.dashboardStateWidgetSettingsForm.get('stateId').patchValue(value, {emitEvent: true}); + setTimeout(() => { + this.dashboardStateInput.nativeElement.blur(); + this.dashboardStateInput.nativeElement.focus(); + }, 0); + } + + private fetchDashboardStates(searchText?: string): Observable> { + this.dashboardStateSearchText = searchText; + const stateIds = Object.keys(this.dashboard.configuration.states); + const result = searchText ? stateIds.filter(this.createFilterForDashboardState(searchText)) : stateIds; + if (result && result.length) { + return of(result); + } else { + return of([searchText]); + } + } + + private createFilterForDashboardState(query: string): (stateId: string) => boolean { + const lowercaseQuery = query.toLowerCase(); + return stateId => stateId.toLowerCase().indexOf(lowercaseQuery) === 0; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.html new file mode 100644 index 0000000000..e2f403eb46 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.html @@ -0,0 +1,22 @@ + +
+ + {{ 'widgets.edge.display-default-title' | translate }} + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.ts new file mode 100644 index 0000000000..2d26f5e76d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component.ts @@ -0,0 +1,52 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-edge-quick-overview-widget-settings', + templateUrl: './edge-quick-overview-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class EdgeQuickOverviewWidgetSettingsComponent extends WidgetSettingsComponent { + + edgeQuickOverviewWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.edgeQuickOverviewWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + enableDefaultTitle: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.edgeQuickOverviewWidgetSettingsForm = this.fb.group({ + enableDefaultTitle: [settings.enableDefaultTitle, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.html new file mode 100644 index 0000000000..2a2f16d581 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.html @@ -0,0 +1,74 @@ + +
+
+ widgets.entities-hierarchy.hierarchy-data-settings + + + + +
+
+ widgets.entities-hierarchy.node-state-settings + + + + +
+
+ widgets.entities-hierarchy.display-settings + + + + +
+
+ widgets.entities-hierarchy.sort-settings + + +
+
+ diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.ts new file mode 100644 index 0000000000..d9e850b14f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component.ts @@ -0,0 +1,64 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-entities-hierarchy-widget-settings', + templateUrl: './entities-hierarchy-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class EntitiesHierarchyWidgetSettingsComponent extends WidgetSettingsComponent { + + entitiesHierarchyWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.entitiesHierarchyWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + nodeRelationQueryFunction: '', + nodeHasChildrenFunction: '', + nodeOpenedFunction: '', + nodeDisabledFunction: '', + nodeIconFunction: '', + nodeTextFunction: '', + nodesSortFunction: '', + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.entitiesHierarchyWidgetSettingsForm = this.fb.group({ + nodeRelationQueryFunction: [settings.nodeRelationQueryFunction, []], + nodeHasChildrenFunction: [settings.nodeHasChildrenFunction, []], + nodeOpenedFunction: [settings.nodeOpenedFunction, []], + nodeDisabledFunction: [settings.nodeDisabledFunction, []], + nodeIconFunction: [settings.nodeIconFunction, []], + nodeTextFunction: [settings.nodeTextFunction, []], + nodesSortFunction: [settings.nodesSortFunction, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.html new file mode 100644 index 0000000000..8714a5b820 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.html @@ -0,0 +1,95 @@ + +
+ + widgets.table.column-width + + +
+ widgets.table.cell-style + + + + + {{ 'widgets.table.use-cell-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.table.cell-content + + + + + {{ 'widgets.table.use-cell-content-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+ + widgets.table.default-column-visibility + + + {{ 'widgets.table.column-visibility-visible' | translate }} + + + {{ 'widgets.table.column-visibility-hidden' | translate }} + + + + + widgets.table.column-selection-to-display + + + {{ 'widgets.table.column-selection-to-display-enabled' | translate }} + + + {{ 'widgets.table.column-selection-to-display-disabled' | translate }} + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.ts new file mode 100644 index 0000000000..738e99223c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-key-settings.component.ts @@ -0,0 +1,86 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-entities-table-key-settings', + templateUrl: './entities-table-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class EntitiesTableKeySettingsComponent extends WidgetSettingsComponent { + + entitiesTableKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.entitiesTableKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + columnWidth: '0px', + useCellStyleFunction: false, + cellStyleFunction: '', + useCellContentFunction: false, + cellContentFunction: '', + defaultColumnVisibility: 'visible', + columnSelectionToDisplay: 'enabled' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.entitiesTableKeySettingsForm = this.fb.group({ + columnWidth: [settings.columnWidth, []], + useCellStyleFunction: [settings.useCellStyleFunction, []], + cellStyleFunction: [settings.cellStyleFunction, [Validators.required]], + useCellContentFunction: [settings.useCellContentFunction, []], + cellContentFunction: [settings.cellContentFunction, [Validators.required]], + defaultColumnVisibility: [settings.defaultColumnVisibility, []], + columnSelectionToDisplay: [settings.columnSelectionToDisplay, []], + }); + } + + protected validatorTriggers(): string[] { + return ['useCellStyleFunction', 'useCellContentFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const useCellStyleFunction: boolean = this.entitiesTableKeySettingsForm.get('useCellStyleFunction').value; + const useCellContentFunction: boolean = this.entitiesTableKeySettingsForm.get('useCellContentFunction').value; + if (useCellStyleFunction) { + this.entitiesTableKeySettingsForm.get('cellStyleFunction').enable(); + } else { + this.entitiesTableKeySettingsForm.get('cellStyleFunction').disable(); + } + if (useCellContentFunction) { + this.entitiesTableKeySettingsForm.get('cellContentFunction').enable(); + } else { + this.entitiesTableKeySettingsForm.get('cellContentFunction').disable(); + } + this.entitiesTableKeySettingsForm.get('cellStyleFunction').updateValueAndValidity({emitEvent}); + this.entitiesTableKeySettingsForm.get('cellContentFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.html new file mode 100644 index 0000000000..e58f083bea --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.html @@ -0,0 +1,116 @@ + +
+
+ widgets.table.common-table-settings + + widgets.table.entities-table-title + + +
+
+ + {{ 'widgets.table.enable-search' | translate }} + + + {{ 'widgets.table.enable-select-column-display' | translate }} + +
+
+ + {{ 'widgets.table.enable-sticky-header' | translate }} + + + {{ 'widgets.table.enable-sticky-action' | translate }} + +
+
+ + widgets.table.hidden-cell-button-display-mode + + + {{ 'widgets.table.show-empty-space-hidden-action' | translate }} + + + {{ 'widgets.table.dont-reserve-space-hidden-action' | translate }} + + + +
+
+ + {{ 'widgets.table.display-entity-name' | translate }} + + + widgets.table.entity-name-column-title + + +
+
+ + {{ 'widgets.table.display-entity-label' | translate }} + + + widgets.table.entity-label-column-title + + +
+ + {{ 'widgets.table.display-entity-type' | translate }} + +
+ + {{ 'widgets.table.display-pagination' | translate }} + + + widgets.table.default-page-size + + +
+ + widgets.table.default-sort-order + + +
+
+
+ widgets.table.row-style + + + + + {{ 'widgets.table.use-row-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.ts new file mode 100644 index 0000000000..789323679b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/entities-table-widget-settings.component.ts @@ -0,0 +1,118 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-entities-table-widget-settings', + templateUrl: './entities-table-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class EntitiesTableWidgetSettingsComponent extends WidgetSettingsComponent { + + entitiesTableWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.entitiesTableWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + entitiesTitle: '', + enableSearch: true, + enableSelectColumnDisplay: true, + enableStickyHeader: true, + enableStickyAction: true, + reserveSpaceForHiddenAction: 'true', + displayEntityName: true, + entityNameColumnTitle: '', + displayEntityLabel: false, + entityLabelColumnTitle: '', + displayEntityType: true, + displayPagination: true, + defaultPageSize: 10, + defaultSortOrder: 'entityName', + useRowStyleFunction: false, + rowStyleFunction: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.entitiesTableWidgetSettingsForm = this.fb.group({ + entitiesTitle: [settings.entitiesTitle, []], + enableSearch: [settings.enableSearch, []], + enableSelectColumnDisplay: [settings.enableSelectColumnDisplay, []], + enableStickyHeader: [settings.enableStickyHeader, []], + enableStickyAction: [settings.enableStickyAction, []], + reserveSpaceForHiddenAction: [settings.reserveSpaceForHiddenAction, []], + displayEntityName: [settings.displayEntityName, []], + entityNameColumnTitle: [settings.entityNameColumnTitle, []], + displayEntityLabel: [settings.displayEntityLabel, []], + entityLabelColumnTitle: [settings.entityLabelColumnTitle, []], + displayEntityType: [settings.displayEntityType, []], + displayPagination: [settings.displayPagination, []], + defaultPageSize: [settings.defaultPageSize, [Validators.min(1)]], + defaultSortOrder: [settings.defaultSortOrder, []], + useRowStyleFunction: [settings.useRowStyleFunction, []], + rowStyleFunction: [settings.rowStyleFunction, [Validators.required]] + }); + } + + protected validatorTriggers(): string[] { + return ['useRowStyleFunction', 'displayPagination', 'displayEntityName', 'displayEntityLabel']; + } + + protected updateValidators(emitEvent: boolean) { + const useRowStyleFunction: boolean = this.entitiesTableWidgetSettingsForm.get('useRowStyleFunction').value; + const displayPagination: boolean = this.entitiesTableWidgetSettingsForm.get('displayPagination').value; + const displayEntityName: boolean = this.entitiesTableWidgetSettingsForm.get('displayEntityName').value; + const displayEntityLabel: boolean = this.entitiesTableWidgetSettingsForm.get('displayEntityLabel').value; + if (useRowStyleFunction) { + this.entitiesTableWidgetSettingsForm.get('rowStyleFunction').enable(); + } else { + this.entitiesTableWidgetSettingsForm.get('rowStyleFunction').disable(); + } + if (displayPagination) { + this.entitiesTableWidgetSettingsForm.get('defaultPageSize').enable(); + } else { + this.entitiesTableWidgetSettingsForm.get('defaultPageSize').disable(); + } + if (displayEntityName) { + this.entitiesTableWidgetSettingsForm.get('entityNameColumnTitle').enable(); + } else { + this.entitiesTableWidgetSettingsForm.get('entityNameColumnTitle').disable(); + } + if (displayEntityLabel) { + this.entitiesTableWidgetSettingsForm.get('entityLabelColumnTitle').enable(); + } else { + this.entitiesTableWidgetSettingsForm.get('entityLabelColumnTitle').disable(); + } + this.entitiesTableWidgetSettingsForm.get('rowStyleFunction').updateValueAndValidity({emitEvent}); + this.entitiesTableWidgetSettingsForm.get('defaultPageSize').updateValueAndValidity({emitEvent}); + this.entitiesTableWidgetSettingsForm.get('entityNameColumnTitle').updateValueAndValidity({emitEvent}); + this.entitiesTableWidgetSettingsForm.get('entityLabelColumnTitle').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.html new file mode 100644 index 0000000000..c95d3a8b98 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.html @@ -0,0 +1,25 @@ + +
+ + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.ts new file mode 100644 index 0000000000..1dc0f398e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/html-card-widget-settings.component.ts @@ -0,0 +1,54 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-html-card-widget-settings', + templateUrl: './html-card-widget-settings.component.html', + styleUrls: [] +}) +export class HtmlCardWidgetSettingsComponent extends WidgetSettingsComponent { + + htmlCardWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.htmlCardWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + cardHtml: '
HTML code here
', + cardCss: '.card {\n font-weight: bold; \n}' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.htmlCardWidgetSettingsForm = this.fb.group({ + cardHtml: [settings.cardHtml, [Validators.required]], + cardCss: [settings.cardCss, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.html new file mode 100644 index 0000000000..9aa9fcc68c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.html @@ -0,0 +1,73 @@ + + + +
+ +
+ {{ labelWidgetLabelFormGroup.get('pattern').value }} +
+
+ + +
+
+ +
+ +
+ + widgets.label-widget.label-pattern + + + {{ 'widgets.label-widget.label-pattern-required' | translate }} + + + +
+ widgets.label-widget.label-position +
+ + widgets.label-widget.x-pos + + + + widgets.label-widget.y-pos + + +
+
+ + +
+ widgets.label-widget.font-settings + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.scss new file mode 100644 index 0000000000..0df6cc0626 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.label-widget-label { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.label-widget-label { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.ts new file mode 100644 index 0000000000..594d292704 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-label.component.ts @@ -0,0 +1,113 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { WidgetFont } from '@home/components/widget/lib/settings/common/widget-font.component'; + +export interface LabelWidgetLabel { + pattern: string; + x: number; + y: number; + backgroundColor: string; + font: WidgetFont; +} + +@Component({ + selector: 'tb-label-widget-label', + templateUrl: './label-widget-label.component.html', + styleUrls: ['./label-widget-label.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => LabelWidgetLabelComponent), + multi: true + } + ] +}) +export class LabelWidgetLabelComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Output() + removeLabel = new EventEmitter(); + + private modelValue: LabelWidgetLabel; + + private propagateChange = null; + + public labelWidgetLabelFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.labelWidgetLabelFormGroup = this.fb.group({ + pattern: [null, [Validators.required]], + x: [null, [Validators.min(0), Validators.max(100)]], + y: [null, [Validators.min(0), Validators.max(100)]], + backgroundColor: [null, []], + font: [null, []] + }); + this.labelWidgetLabelFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.labelWidgetLabelFormGroup.disable({emitEvent: false}); + } else { + this.labelWidgetLabelFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: LabelWidgetLabel): void { + this.modelValue = value; + this.labelWidgetLabelFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + private updateModel() { + const value: LabelWidgetLabel = this.labelWidgetLabelFormGroup.value; + this.modelValue = value; + if (this.labelWidgetLabelFormGroup.valid) { + this.propagateChange(this.modelValue); + } else { + this.propagateChange(null); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.html new file mode 100644 index 0000000000..5c7598b7c6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.html @@ -0,0 +1,50 @@ + +
+ + +
+ widgets.label-widget.labels +
+
+
+ + +
+
+
+ widgets.label-widget.no-labels +
+
+ +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.ts new file mode 100644 index 0000000000..fbc42b4d11 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/label-widget-settings.component.ts @@ -0,0 +1,110 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { LabelWidgetLabel } from '@home/components/widget/lib/settings/cards/label-widget-label.component'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; + +@Component({ + selector: 'tb-label-widget-settings', + templateUrl: './label-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class LabelWidgetSettingsComponent extends WidgetSettingsComponent { + + labelWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.labelWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + backgroundImageUrl: 'data:image/svg+xml;base64,PHN2ZyBpZD0ic3ZnMiIgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTAwIiB3aWR0aD0iMTAwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgdmlld0JveD0iMCAwIDEwMCAxMDAiPgogPGcgaWQ9ImxheWVyMSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAtOTUyLjM2KSI+CiAgPHJlY3QgaWQ9InJlY3Q0Njg0IiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBoZWlnaHQ9Ijk5LjAxIiB3aWR0aD0iOTkuMDEiIHN0cm9rZT0iIzAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiB5PSI5NTIuODYiIHg9Ii40OTUwNSIgc3Ryb2tlLXdpZHRoPSIuOTkwMTAiIGZpbGw9IiNlZWUiLz4KICA8dGV4dCBpZD0idGV4dDQ2ODYiIHN0eWxlPSJ3b3JkLXNwYWNpbmc6MHB4O2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjptaWRkbGU7dGV4dC1hbGlnbjpjZW50ZXIiIGZvbnQtd2VpZ2h0PSJib2xkIiB4bWw6c3BhY2U9InByZXNlcnZlIiBmb250LXNpemU9IjEwcHgiIGxpbmUtaGVpZ2h0PSIxMjUlIiB5PSI5NzAuNzI4MDkiIHg9IjQ5LjM5NjQ3NyIgZm9udC1mYW1pbHk9IlJvYm90byIgZmlsbD0iIzY2NjY2NiI+PHRzcGFuIGlkPSJ0c3BhbjQ2OTAiIHg9IjUwLjY0NjQ3NyIgeT0iOTcwLjcyODA5Ij5JbWFnZSBiYWNrZ3JvdW5kIDwvdHNwYW4+PHRzcGFuIGlkPSJ0c3BhbjQ2OTIiIHg9IjQ5LjM5NjQ3NyIgeT0iOTgzLjIyODA5Ij5pcyBub3QgY29uZmlndXJlZDwvdHNwYW4+PC90ZXh0PgogIDxyZWN0IGlkPSJyZWN0NDY5NCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgaGVpZ2h0PSIxOS4zNiIgd2lkdGg9IjY5LjM2IiBzdHJva2U9IiMwMDAiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgeT0iOTkyLjY4IiB4PSIxNS4zMiIgc3Ryb2tlLXdpZHRoPSIuNjM5ODYiIGZpbGw9Im5vbmUiLz4KIDwvZz4KPC9zdmc+Cg==', + labels: [] + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.labelWidgetSettingsForm = this.fb.group({ + backgroundImageUrl: [settings.backgroundImageUrl, [Validators.required]], + labels: this.prepareLabelsFormArray(settings.labels) + }); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('labels', this.prepareLabelsFormArray(settings.labels), {emitEvent: false}); + } + + private prepareLabelsFormArray(labels: LabelWidgetLabel[] | undefined): FormArray { + const labelsControls: Array = []; + if (labels) { + labels.forEach((label) => { + labelsControls.push(this.fb.control(label, [Validators.required])); + }); + } + return this.fb.array(labelsControls); + } + + labelsFormArray(): FormArray { + return this.labelWidgetSettingsForm.get('labels') as FormArray; + } + + public trackByLabelControl(index: number, labelControl: AbstractControl): any { + return labelControl; + } + + public removeLabel(index: number) { + (this.labelWidgetSettingsForm.get('labels') as FormArray).removeAt(index); + } + + public addLabel() { + const label: LabelWidgetLabel = { + pattern: '${#0}', + x: 50, + y: 50, + backgroundColor: 'rgba(0,0,0,0)', + font: { + family: 'Roboto', + size: 6, + style: 'normal', + weight: '500', + color: '#fff' + } + }; + const labelsArray = this.labelWidgetSettingsForm.get('labels') as FormArray; + const labelControl = this.fb.control(label, [Validators.required]); + (labelControl as any).new = true; + labelsArray.push(labelControl); + this.labelWidgetSettingsForm.updateValueAndValidity(); + } + + labelDrop(event: CdkDragDrop) { + const labelsArray = this.labelWidgetSettingsForm.get('labels') as FormArray; + const label = labelsArray.at(event.previousIndex); + labelsArray.removeAt(event.previousIndex); + labelsArray.insert(event.currentIndex, label); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.html new file mode 100644 index 0000000000..3859a17e90 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.html @@ -0,0 +1,36 @@ + +
+ + {{ 'widgets.markdown.use-markdown-text-function' | translate }} + + + + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.ts new file mode 100644 index 0000000000..59667b7b77 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/markdown-widget-settings.component.ts @@ -0,0 +1,76 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-markdown-widget-settings', + templateUrl: './markdown-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class MarkdownWidgetSettingsComponent extends WidgetSettingsComponent { + + markdownWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.markdownWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + useMarkdownTextFunction: false, + markdownTextPattern: '# Markdown/HTML card \\n - **Current entity**: **${entityName}**. \\n - **Current value**: **${Random}**.', + markdownTextFunction: 'return \'# Some title\\\\n - Entity name: \' + data[0][\'entityName\'];', + markdownCss: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.markdownWidgetSettingsForm = this.fb.group({ + useMarkdownTextFunction: [settings.useMarkdownTextFunction, []], + markdownTextPattern: [settings.markdownTextPattern, []], + markdownTextFunction: [settings.qrCodeTextFunction, []], + markdownCss: [settings.markdownCss, []] + }); + } + + protected validatorTriggers(): string[] { + return ['useMarkdownTextFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const useMarkdownTextFunction: boolean = this.markdownWidgetSettingsForm.get('useMarkdownTextFunction').value; + if (useMarkdownTextFunction) { + this.markdownWidgetSettingsForm.get('markdownTextPattern').disable(); + this.markdownWidgetSettingsForm.get('markdownTextFunction').enable(); + } else { + this.markdownWidgetSettingsForm.get('markdownTextPattern').enable(); + this.markdownWidgetSettingsForm.get('markdownTextFunction').disable(); + } + this.markdownWidgetSettingsForm.get('markdownTextPattern').updateValueAndValidity({emitEvent}); + this.markdownWidgetSettingsForm.get('markdownTextFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.html new file mode 100644 index 0000000000..715d1f1fe6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.html @@ -0,0 +1,37 @@ + +
+ + {{ 'widgets.qr-code.use-qr-code-text-function' | translate }} + + + widgets.qr-code.qr-code-text-pattern + + + {{ 'widgets.qr-code.qr-code-text-pattern-required' | translate }} + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.ts new file mode 100644 index 0000000000..f5c204a136 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/qrcode-widget-settings.component.ts @@ -0,0 +1,74 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-qrcode-widget-settings', + templateUrl: './qrcode-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class QrCodeWidgetSettingsComponent extends WidgetSettingsComponent { + + qrCodeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.qrCodeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + qrCodeTextPattern: '${entityName}', + useQrCodeTextFunction: false, + qrCodeTextFunction: 'return data[0][\'entityName\'];' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.qrCodeWidgetSettingsForm = this.fb.group({ + qrCodeTextPattern: [settings.qrCodeTextPattern, [Validators.required]], + useQrCodeTextFunction: [settings.useQrCodeTextFunction, [Validators.required]], + qrCodeTextFunction: [settings.qrCodeTextFunction, [Validators.required]] + }); + } + + protected validatorTriggers(): string[] { + return ['useQrCodeTextFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const useQrCodeTextFunction: boolean = this.qrCodeWidgetSettingsForm.get('useQrCodeTextFunction').value; + if (useQrCodeTextFunction) { + this.qrCodeWidgetSettingsForm.get('qrCodeTextPattern').disable(); + this.qrCodeWidgetSettingsForm.get('qrCodeTextFunction').enable(); + } else { + this.qrCodeWidgetSettingsForm.get('qrCodeTextPattern').enable(); + this.qrCodeWidgetSettingsForm.get('qrCodeTextFunction').disable(); + } + this.qrCodeWidgetSettingsForm.get('qrCodeTextPattern').updateValueAndValidity({emitEvent}); + this.qrCodeWidgetSettingsForm.get('qrCodeTextFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.html new file mode 100644 index 0000000000..5fe97385c7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.html @@ -0,0 +1,30 @@ + +
+ + widgets.simple-card.label-position + + + {{ 'widgets.simple-card.label-position-left' | translate }} + + + {{ 'widgets.simple-card.label-position-top' | translate }} + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.ts new file mode 100644 index 0000000000..d690c4f434 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/simple-card-widget-settings.component.ts @@ -0,0 +1,52 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-simple-card-widget-settings', + templateUrl: './simple-card-widget-settings.component.html', + styleUrls: [] +}) +export class SimpleCardWidgetSettingsComponent extends WidgetSettingsComponent { + + simpleCardWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.simpleCardWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + labelPosition: 'left' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.simpleCardWidgetSettingsForm = this.fb.group({ + labelPosition: [settings.labelPosition, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.html new file mode 100644 index 0000000000..f8a2b852d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.html @@ -0,0 +1,69 @@ + +
+
+ widgets.table.cell-style + + + + + {{ 'widgets.table.use-cell-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.table.cell-content + + + + + {{ 'widgets.table.use-cell-content-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.ts new file mode 100644 index 0000000000..2330b95752 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-key-settings.component.ts @@ -0,0 +1,80 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-timeseries-table-key-settings', + templateUrl: './timeseries-table-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class TimeseriesTableKeySettingsComponent extends WidgetSettingsComponent { + + timeseriesTableKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.timeseriesTableKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + useCellStyleFunction: false, + cellStyleFunction: '', + useCellContentFunction: false, + cellContentFunction: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.timeseriesTableKeySettingsForm = this.fb.group({ + useCellStyleFunction: [settings.useCellStyleFunction, []], + cellStyleFunction: [settings.cellStyleFunction, [Validators.required]], + useCellContentFunction: [settings.useCellContentFunction, []], + cellContentFunction: [settings.cellContentFunction, [Validators.required]], + }); + } + + protected validatorTriggers(): string[] { + return ['useCellStyleFunction', 'useCellContentFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const useCellStyleFunction: boolean = this.timeseriesTableKeySettingsForm.get('useCellStyleFunction').value; + const useCellContentFunction: boolean = this.timeseriesTableKeySettingsForm.get('useCellContentFunction').value; + if (useCellStyleFunction) { + this.timeseriesTableKeySettingsForm.get('cellStyleFunction').enable(); + } else { + this.timeseriesTableKeySettingsForm.get('cellStyleFunction').disable(); + } + if (useCellContentFunction) { + this.timeseriesTableKeySettingsForm.get('cellContentFunction').enable(); + } else { + this.timeseriesTableKeySettingsForm.get('cellContentFunction').disable(); + } + this.timeseriesTableKeySettingsForm.get('cellStyleFunction').updateValueAndValidity({emitEvent}); + this.timeseriesTableKeySettingsForm.get('cellContentFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.html new file mode 100644 index 0000000000..84c1320222 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.html @@ -0,0 +1,76 @@ + +
+ + {{ 'widgets.table.show-latest-data-column' | translate }} + + + widgets.table.latest-data-column-order + + +
+ widgets.table.cell-style + + + + + {{ 'widgets.table.use-cell-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.table.cell-content + + + + + {{ 'widgets.table.use-cell-content-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.ts new file mode 100644 index 0000000000..1abba3ae0b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component.ts @@ -0,0 +1,96 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-timeseries-table-latest-key-settings', + templateUrl: './timeseries-table-latest-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class TimeseriesTableLatestKeySettingsComponent extends WidgetSettingsComponent { + + timeseriesTableLatestKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.timeseriesTableLatestKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + show: true, + useCellStyleFunction: false, + cellStyleFunction: '', + useCellContentFunction: false, + cellContentFunction: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.timeseriesTableLatestKeySettingsForm = this.fb.group({ + show: [settings.show, []], + order: [settings.order, []], + useCellStyleFunction: [settings.useCellStyleFunction, []], + cellStyleFunction: [settings.cellStyleFunction, [Validators.required]], + useCellContentFunction: [settings.useCellContentFunction, []], + cellContentFunction: [settings.cellContentFunction, [Validators.required]], + }); + } + + protected validatorTriggers(): string[] { + return ['show', 'useCellStyleFunction', 'useCellContentFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const show: boolean = this.timeseriesTableLatestKeySettingsForm.get('show').value; + if (show) { + this.timeseriesTableLatestKeySettingsForm.get('order').enable(); + this.timeseriesTableLatestKeySettingsForm.get('useCellStyleFunction').enable({emitEvent: false}); + this.timeseriesTableLatestKeySettingsForm.get('useCellContentFunction').enable({emitEvent: false}); + const useCellStyleFunction: boolean = this.timeseriesTableLatestKeySettingsForm.get('useCellStyleFunction').value; + const useCellContentFunction: boolean = this.timeseriesTableLatestKeySettingsForm.get('useCellContentFunction').value; + if (useCellStyleFunction) { + this.timeseriesTableLatestKeySettingsForm.get('cellStyleFunction').enable(); + } else { + this.timeseriesTableLatestKeySettingsForm.get('cellStyleFunction').disable(); + } + if (useCellContentFunction) { + this.timeseriesTableLatestKeySettingsForm.get('cellContentFunction').enable(); + } else { + this.timeseriesTableLatestKeySettingsForm.get('cellContentFunction').disable(); + } + } else { + this.timeseriesTableLatestKeySettingsForm.get('order').disable(); + this.timeseriesTableLatestKeySettingsForm.get('useCellStyleFunction').disable({emitEvent: false}); + this.timeseriesTableLatestKeySettingsForm.get('cellStyleFunction').disable(); + this.timeseriesTableLatestKeySettingsForm.get('useCellContentFunction').disable({emitEvent: false}); + this.timeseriesTableLatestKeySettingsForm.get('cellContentFunction').disable(); + } + this.timeseriesTableLatestKeySettingsForm.get('order').updateValueAndValidity({emitEvent}); + this.timeseriesTableLatestKeySettingsForm.get('cellStyleFunction').updateValueAndValidity({emitEvent}); + this.timeseriesTableLatestKeySettingsForm.get('cellContentFunction').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.html new file mode 100644 index 0000000000..c151a97402 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.html @@ -0,0 +1,96 @@ + +
+
+ widgets.table.common-table-settings +
+
+ + {{ 'widgets.table.enable-search' | translate }} + +
+
+ + {{ 'widgets.table.enable-sticky-header' | translate }} + + + {{ 'widgets.table.enable-sticky-action' | translate }} + +
+
+ + widgets.table.hidden-cell-button-display-mode + + + {{ 'widgets.table.show-empty-space-hidden-action' | translate }} + + + {{ 'widgets.table.dont-reserve-space-hidden-action' | translate }} + + + +
+ + {{ 'widgets.table.display-timestamp' | translate }} + + + {{ 'widgets.table.display-milliseconds' | translate }} + +
+ + {{ 'widgets.table.display-pagination' | translate }} + + + widgets.table.default-page-size + + +
+ + {{ 'widgets.table.use-entity-label-tab-name' | translate }} + + + {{ 'widgets.table.hide-empty-lines' | translate }} + +
+
+
+ widgets.table.row-style + + + + + {{ 'widgets.table.use-row-style-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.ts new file mode 100644 index 0000000000..d7a6c83e8d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component.ts @@ -0,0 +1,98 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-timeseries-table-widget-settings', + templateUrl: './timeseries-table-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class TimeseriesTableWidgetSettingsComponent extends WidgetSettingsComponent { + + timeseriesTableWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.timeseriesTableWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + enableSearch: true, + enableStickyHeader: true, + enableStickyAction: true, + reserveSpaceForHiddenAction: 'true', + showTimestamp: true, + showMilliseconds: false, + displayPagination: true, + useEntityLabel: false, + defaultPageSize: 10, + hideEmptyLines: false, + disableStickyHeader: false, + useRowStyleFunction: false, + rowStyleFunction: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.timeseriesTableWidgetSettingsForm = this.fb.group({ + enableSearch: [settings.enableSearch, []], + enableStickyHeader: [settings.enableStickyHeader, []], + enableStickyAction: [settings.enableStickyAction, []], + reserveSpaceForHiddenAction: [settings.reserveSpaceForHiddenAction, []], + showTimestamp: [settings.showTimestamp, []], + showMilliseconds: [settings.showMilliseconds, []], + displayPagination: [settings.displayPagination, []], + useEntityLabel: [settings.useEntityLabel, []], + defaultPageSize: [settings.defaultPageSize, [Validators.min(1)]], + hideEmptyLines: [settings.hideEmptyLines, []], + disableStickyHeader: [settings.disableStickyHeader, []], + useRowStyleFunction: [settings.useRowStyleFunction, []], + rowStyleFunction: [settings.rowStyleFunction, [Validators.required]] + }); + } + + protected validatorTriggers(): string[] { + return ['useRowStyleFunction', 'displayPagination']; + } + + protected updateValidators(emitEvent: boolean) { + const useRowStyleFunction: boolean = this.timeseriesTableWidgetSettingsForm.get('useRowStyleFunction').value; + const displayPagination: boolean = this.timeseriesTableWidgetSettingsForm.get('displayPagination').value; + if (useRowStyleFunction) { + this.timeseriesTableWidgetSettingsForm.get('rowStyleFunction').enable(); + } else { + this.timeseriesTableWidgetSettingsForm.get('rowStyleFunction').disable(); + } + if (displayPagination) { + this.timeseriesTableWidgetSettingsForm.get('defaultPageSize').enable(); + } else { + this.timeseriesTableWidgetSettingsForm.get('defaultPageSize').disable(); + } + this.timeseriesTableWidgetSettingsForm.get('rowStyleFunction').updateValueAndValidity({emitEvent}); + this.timeseriesTableWidgetSettingsForm.get('defaultPageSize').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.html new file mode 100644 index 0000000000..bd85fe47de --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.html @@ -0,0 +1,25 @@ + +
+
+ widgets.chart.common-settings + + {{ 'widgets.chart.show-tooltip' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.ts new file mode 100644 index 0000000000..9b027c3ec3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/chart-widget-settings.component.ts @@ -0,0 +1,52 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-chart-widget-settings', + templateUrl: './chart-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class ChartWidgetSettingsComponent extends WidgetSettingsComponent { + + chartWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.chartWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + showTooltip: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.chartWidgetSettingsForm = this.fb.group({ + showTooltip: [settings.showTooltip, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.html new file mode 100644 index 0000000000..8a25d692c5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.html @@ -0,0 +1,64 @@ + +
+
+ widgets.chart.common-settings + + {{ 'widgets.chart.show-tooltip' | translate }} + +
+
+ widgets.chart.border-settings +
+ + widgets.chart.border-width + + + + +
+
+
+ widgets.chart.legend-settings + + + + + {{ 'widgets.chart.display-legend' | translate }} + + + + widget-config.advanced-settings + + + +
+ + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.ts new file mode 100644 index 0000000000..171344c07e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component.ts @@ -0,0 +1,87 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-doughnut-chart-widget-settings', + templateUrl: './doughnut-chart-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class DoughnutChartWidgetSettingsComponent extends WidgetSettingsComponent { + + doughnutChartWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.doughnutChartWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + showTooltip: true, + borderWidth: 5, + borderColor: '#fff', + legend: { + display: true, + labelsFontColor: '#666' + } + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.doughnutChartWidgetSettingsForm = this.fb.group({ + + // Common settings + + showTooltip: [settings.showTooltip, []], + + // Border settings + + borderWidth: [settings.borderWidth, [Validators.min(0)]], + borderColor: [settings.borderColor, []], + + // Legend settings + + legend: this.fb.group({ + display: [settings.legend?.display, []], + labelsFontColor: [settings.legend?.labelsFontColor, []] + }) + }); + } + + protected validatorTriggers(): string[] { + return ['legend.display']; + } + + protected updateValidators(emitEvent: boolean) { + const displayLegend: boolean = this.doughnutChartWidgetSettingsForm.get('legend.display').value; + if (displayLegend) { + this.doughnutChartWidgetSettingsForm.get('legend.labelsFontColor').enable(); + } else { + this.doughnutChartWidgetSettingsForm.get('legend.labelsFontColor').disable(); + } + this.doughnutChartWidgetSettingsForm.get('legend.labelsFontColor').updateValueAndValidity({emitEvent}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.html new file mode 100644 index 0000000000..f96f2ddbff --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.html @@ -0,0 +1,24 @@ + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.ts new file mode 100644 index 0000000000..5882707eea --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-key-settings.component.ts @@ -0,0 +1,61 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { flotDataKeyDefaultSettings } from '@home/components/widget/lib/settings/chart/flot-key-settings.component'; + +@Component({ + selector: 'tb-flot-bar-key-settings', + templateUrl: './flot-bar-key-settings.component.html', + styleUrls: [] +}) +export class FlotBarKeySettingsComponent extends WidgetSettingsComponent { + + flotBarKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotBarKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return flotDataKeyDefaultSettings('bar'); + } + + protected onSettingsSet(settings: WidgetSettings) { + this.flotBarKeySettingsForm = this.fb.group({ + flotKeySettings: [settings.flotKeySettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + flotKeySettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.flotKeySettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.html new file mode 100644 index 0000000000..b91b716ce3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.html @@ -0,0 +1,23 @@ + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.ts new file mode 100644 index 0000000000..285c339edf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-bar-widget-settings.component.ts @@ -0,0 +1,61 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { flotDefaultSettings } from '@home/components/widget/lib/settings/chart/flot-widget-settings.component'; + +@Component({ + selector: 'tb-flot-bar-widget-settings', + templateUrl: './flot-bar-widget-settings.component.html', + styleUrls: [] +}) +export class FlotBarWidgetSettingsComponent extends WidgetSettingsComponent { + + flotBarWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotBarWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return flotDefaultSettings('bar'); + } + + protected onSettingsSet(settings: WidgetSettings) { + this.flotBarWidgetSettingsForm = this.fb.group({ + flotSettings: [settings.flotSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + flotSettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.flotSettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.html new file mode 100644 index 0000000000..9aec9b535f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.html @@ -0,0 +1,239 @@ + +
+
+ widgets.chart.common-settings + + {{ 'widgets.chart.data-is-hidden-by-default' | translate }} + + + {{ 'widgets.chart.disable-data-hiding' | translate }} + + + {{ 'widgets.chart.remove-from-legend' | translate }} + + + {{ 'widgets.chart.exclude-from-stacking' | translate }} + +
+
+ widgets.chart.line-settings + + + + + {{ 'widgets.chart.show-line' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.chart.line-width + + + + {{ 'widgets.chart.fill-line' | translate }} + +
+
+
+
+
+ widgets.chart.points-settings + + + + + {{ 'widgets.chart.show-points' | translate }} + + + + widget-config.advanced-settings + + + +
+
+ + widgets.chart.points-line-width + + + + widgets.chart.points-radius + + +
+ + widgets.chart.point-shape + + + {{ 'widgets.chart.point-shape-circle' | translate }} + + + {{ 'widgets.chart.point-shape-cross' | translate }} + + + {{ 'widgets.chart.point-shape-diamond' | translate }} + + + {{ 'widgets.chart.point-shape-square' | translate }} + + + {{ 'widgets.chart.point-shape-triangle' | translate }} + + + {{ 'widgets.chart.point-shape-custom' | translate }} + + + + + +
+
+
+
+
+ widgets.chart.tooltip-settings + + +
+
+ widgets.chart.yaxis-settings + + {{ 'widgets.chart.show-separate-axis' | translate }} + + + widgets.chart.axis-title + + +
+ + widgets.chart.min-scale-value + + + + widgets.chart.max-scale-value + + +
+ + widgets.chart.axis-position + + + {{ 'widgets.chart.axis-position-left' | translate }} + + + {{ 'widgets.chart.axis-position-right' | translate }} + + + +
+ widgets.chart.yaxis-tick-labels-settings +
+ + widgets.chart.tick-step-size + + + + widgets.chart.number-of-decimals + + +
+ + +
+
+
+ widgets.chart.thresholds +
+
+
+ + +
+
+
+ widgets.chart.no-thresholds +
+
+ +
+
+
+
+ widgets.chart.comparison-settings + + + + + {{ 'widgets.chart.show-values-for-comparison' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.chart.comparison-values-label + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.ts new file mode 100644 index 0000000000..a97ccc84a0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-key-settings.component.ts @@ -0,0 +1,333 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormArray, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { ChartType, TbFlotKeySettings, TbFlotKeyThreshold } from '@home/components/widget/lib/flot-widget.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { WidgetService } from '@core/http/widget.service'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; +import { IAliasController } from 'src/app/core/api/widget-api.models'; + +export function flotDataKeyDefaultSettings(chartType: ChartType): TbFlotKeySettings { + const settings: TbFlotKeySettings = { + // Common settings + hideDataByDefault: false, + disableDataHiding: false, + removeFromLegend: false, + excludeFromStacking: false, + + // Line settings + showLines: chartType === 'graph', + lineWidth: 1, + fillLines: false, + + // Points settings + showPoints: false, + showPointsLineWidth: 5, + showPointsRadius: 3, + showPointShape: 'circle', + pointShapeFormatter: 'var size = radius * Math.sqrt(Math.PI) / 2;\n' + + 'ctx.moveTo(x - size, y - size);\n' + + 'ctx.lineTo(x + size, y + size);\n' + + 'ctx.moveTo(x - size, y + size);\n' + + 'ctx.lineTo(x + size, y - size);', + + // Tooltip settings + tooltipValueFormatter: '', + + // Y axis settings + showSeparateAxis: false, + axisTitle: '', + axisMin: null, + axisMax: null, + axisPosition: 'left', + + // --> Y axis tick labels settings + axisTickSize: null, + axisTickDecimals: null, + axisTicksFormatter: '', + + // Thresholds + thresholds: [], + + // Comparison settings + comparisonSettings: { + showValuesForComparison: true, + comparisonValuesLabel: '', + color: '' + } + }; + return settings; +} + +@Component({ + selector: 'tb-flot-key-settings', + templateUrl: './flot-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => FlotKeySettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => FlotKeySettingsComponent), + multi: true, + } + ] +}) +export class FlotKeySettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + chartType: ChartType; + + @Input() + aliasController: IAliasController; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: TbFlotKeySettings; + + private propagateChange = null; + + public flotKeySettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.flotKeySettingsFormGroup = this.fb.group({ + + // Common settings + + hideDataByDefault: [false, []], + disableDataHiding: [false, []], + removeFromLegend: [false, []], + excludeFromStacking: [false, []], + + // Line settings + + showLines: [this.chartType === 'graph', []], + lineWidth: [1, [Validators.min(0)]], + fillLines: [false, []], + + // Points settings + + showPoints: [false, []], + showPointsLineWidth: [5, [Validators.min(0)]], + showPointsRadius: [3, [Validators.min(0)]], + showPointShape: ['circle', []], + pointShapeFormatter: ['', []], + + // Tooltip settings + + tooltipValueFormatter: ['', []], + + // Y axis settings + + showSeparateAxis: [false, []], + axisTitle: [null, []], + axisMin: [null, []], + axisMax: [null, []], + axisPosition: ['left', []], + + // --> Y axis tick labels settings + + axisTickSize: [null, [Validators.min(0)]], + axisTickDecimals: [null, [Validators.min(0)]], + axisTicksFormatter: ['', []], + + // Thresholds + + thresholds: this.fb.array([]), + + // Comparison settings + + comparisonSettings: this.fb.group({ + showValuesForComparison: [true, []], + comparisonValuesLabel: ['', []], + color: ['', []] + }) + + }); + + this.flotKeySettingsFormGroup.get('showLines').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + this.flotKeySettingsFormGroup.get('showPoints').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + this.flotKeySettingsFormGroup.get('comparisonSettings.showValuesForComparison').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + this.flotKeySettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.flotKeySettingsFormGroup.disable({emitEvent: false}); + } else { + this.flotKeySettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TbFlotKeySettings): void { + const thresholds = value?.thresholds; + this.modelValue = value; + this.flotKeySettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + const thresholdsControls: Array = []; + if (thresholds && thresholds.length) { + thresholds.forEach((threshold) => { + thresholdsControls.push(this.fb.control(threshold, [])); + }); + } + this.flotKeySettingsFormGroup.setControl('thresholds', this.fb.array(thresholdsControls), {emitEvent: false}); + this.updateValidators(false); + } + + validate(c: FormControl) { + return (this.flotKeySettingsFormGroup.valid) ? null : { + flotKeySettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: TbFlotKeySettings = this.flotKeySettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showLines: boolean = this.flotKeySettingsFormGroup.get('showLines').value; + const showPoints: boolean = this.flotKeySettingsFormGroup.get('showPoints').value; + const showValuesForComparison: boolean = this.flotKeySettingsFormGroup.get('comparisonSettings.showValuesForComparison').value; + + if (showLines) { + this.flotKeySettingsFormGroup.get('lineWidth').enable({emitEvent}); + this.flotKeySettingsFormGroup.get('fillLines').enable({emitEvent}); + } else { + this.flotKeySettingsFormGroup.get('lineWidth').disable({emitEvent}); + this.flotKeySettingsFormGroup.get('fillLines').disable({emitEvent}); + } + + if (showPoints) { + this.flotKeySettingsFormGroup.get('showPointsLineWidth').enable({emitEvent}); + this.flotKeySettingsFormGroup.get('showPointsRadius').enable({emitEvent}); + this.flotKeySettingsFormGroup.get('showPointShape').enable({emitEvent}); + this.flotKeySettingsFormGroup.get('pointShapeFormatter').enable({emitEvent}); + } else { + this.flotKeySettingsFormGroup.get('showPointsLineWidth').disable({emitEvent}); + this.flotKeySettingsFormGroup.get('showPointsRadius').disable({emitEvent}); + this.flotKeySettingsFormGroup.get('showPointShape').disable({emitEvent}); + this.flotKeySettingsFormGroup.get('pointShapeFormatter').disable({emitEvent}); + } + + if (showValuesForComparison) { + this.flotKeySettingsFormGroup.get('comparisonSettings.comparisonValuesLabel').enable({emitEvent}); + this.flotKeySettingsFormGroup.get('comparisonSettings.color').enable({emitEvent}); + } else { + this.flotKeySettingsFormGroup.get('comparisonSettings.comparisonValuesLabel').disable({emitEvent}); + this.flotKeySettingsFormGroup.get('comparisonSettings.color').disable({emitEvent}); + } + + this.flotKeySettingsFormGroup.get('lineWidth').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('fillLines').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('showPointsLineWidth').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('showPointsRadius').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('showPointShape').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('pointShapeFormatter').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('comparisonSettings.comparisonValuesLabel').updateValueAndValidity({emitEvent: false}); + this.flotKeySettingsFormGroup.get('comparisonSettings.color').updateValueAndValidity({emitEvent: false}); + } + + thresholdsFormArray(): FormArray { + return this.flotKeySettingsFormGroup.get('thresholds') as FormArray; + } + + public trackByThreshold(index: number, thresholdControl: AbstractControl): any { + return thresholdControl; + } + + public removeThreshold(index: number) { + (this.flotKeySettingsFormGroup.get('thresholds') as FormArray).removeAt(index); + } + + public addThreshold() { + const threshold: TbFlotKeyThreshold = { + thresholdValueSource: 'predefinedValue', + thresholdEntityAlias: null, + thresholdAttribute: null, + thresholdValue: null, + lineWidth: null, + color: null + }; + const thresholdsArray = this.flotKeySettingsFormGroup.get('thresholds') as FormArray; + const thresholdControl = this.fb.control(threshold, []); + (thresholdControl as any).new = true; + thresholdsArray.push(thresholdControl); + this.flotKeySettingsFormGroup.updateValueAndValidity(); + } + + thresholdDrop(event: CdkDragDrop) { + const thresholdsArray = this.flotKeySettingsFormGroup.get('thresholds') as FormArray; + const threshold = thresholdsArray.at(event.previousIndex); + thresholdsArray.removeAt(event.previousIndex); + thresholdsArray.insert(event.currentIndex, threshold); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.html new file mode 100644 index 0000000000..b5b9009bd6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.html @@ -0,0 +1,48 @@ + +
+
+ widgets.chart.threshold-settings + + + + + {{ 'widgets.chart.use-as-threshold' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.chart.threshold-line-width + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.ts new file mode 100644 index 0000000000..e3b4b5acf1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-latest-key-settings.component.ts @@ -0,0 +1,74 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-flot-latest-key-settings', + templateUrl: './flot-latest-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class FlotLatestKeySettingsComponent extends WidgetSettingsComponent { + + flotLatestKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotLatestKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + useAsThreshold: false, + thresholdLineWidth: null, + thresholdColor: null + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.flotLatestKeySettingsForm = this.fb.group({ + useAsThreshold: [settings.useAsThreshold, []], + thresholdLineWidth: [settings.thresholdLineWidth, [Validators.min(0)]], + thresholdColor: [settings.thresholdColor, []] + }); + } + + protected validatorTriggers(): string[] { + return ['useAsThreshold']; + } + + protected updateValidators(emitEvent: boolean) { + const useAsThreshold: boolean = this.flotLatestKeySettingsForm.get('useAsThreshold').value; + if (useAsThreshold) { + this.flotLatestKeySettingsForm.get('thresholdLineWidth').enable(); + this.flotLatestKeySettingsForm.get('thresholdColor').enable(); + } else { + this.flotLatestKeySettingsForm.get('thresholdLineWidth').disable(); + this.flotLatestKeySettingsForm.get('thresholdColor').disable(); + } + this.flotLatestKeySettingsForm.get('thresholdLineWidth').updateValueAndValidity({emitEvent}); + this.flotLatestKeySettingsForm.get('thresholdColor').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.html new file mode 100644 index 0000000000..fbc179599f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.html @@ -0,0 +1,24 @@ + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.ts new file mode 100644 index 0000000000..1ae2c4fc43 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-key-settings.component.ts @@ -0,0 +1,61 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { flotDataKeyDefaultSettings } from '@home/components/widget/lib/settings/chart/flot-key-settings.component'; + +@Component({ + selector: 'tb-flot-line-key-settings', + templateUrl: './flot-line-key-settings.component.html', + styleUrls: [] +}) +export class FlotLineKeySettingsComponent extends WidgetSettingsComponent { + + flotLineKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotLineKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return flotDataKeyDefaultSettings('graph'); + } + + protected onSettingsSet(settings: WidgetSettings) { + this.flotLineKeySettingsForm = this.fb.group({ + flotKeySettings: [settings.flotKeySettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + flotKeySettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.flotKeySettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.html new file mode 100644 index 0000000000..299627f9e2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.html @@ -0,0 +1,23 @@ + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.ts new file mode 100644 index 0000000000..d2b0e76ca6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-line-widget-settings.component.ts @@ -0,0 +1,62 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { flotDefaultSettings } from '@home/components/widget/lib/settings/chart/flot-widget-settings.component'; +import { deepClone } from '@core/utils'; + +@Component({ + selector: 'tb-flot-line-widget-settings', + templateUrl: './flot-line-widget-settings.component.html', + styleUrls: [] +}) +export class FlotLineWidgetSettingsComponent extends WidgetSettingsComponent { + + flotLineWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotLineWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return flotDefaultSettings('graph'); + } + + protected onSettingsSet(settings: WidgetSettings) { + this.flotLineWidgetSettingsForm = this.fb.group({ + flotSettings: [settings.flotSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + flotSettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.flotSettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.html new file mode 100644 index 0000000000..8649e5e97d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.html @@ -0,0 +1,31 @@ + +
+
+ widgets.chart.common-settings + + {{ 'widgets.chart.data-is-hidden-by-default' | translate }} + + + {{ 'widgets.chart.disable-data-hiding' | translate }} + + + {{ 'widgets.chart.remove-from-legend' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.ts new file mode 100644 index 0000000000..c9cab0cb06 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-key-settings.component.ts @@ -0,0 +1,60 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-flot-pie-key-settings', + templateUrl: './flot-pie-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class FlotPieKeySettingsComponent extends WidgetSettingsComponent { + + flotPieKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotPieKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + hideDataByDefault: false, + disableDataHiding: false, + removeFromLegend: false + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + + this.flotPieKeySettingsForm = this.fb.group({ + + // Common settings + + hideDataByDefault: [settings.hideDataByDefault, []], + disableDataHiding: [settings.disableDataHiding, []], + removeFromLegend: [settings.removeFromLegend, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.html new file mode 100644 index 0000000000..00f9573020 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.html @@ -0,0 +1,62 @@ + +
+
+ widgets.chart.common-pie-settings +
+ + widgets.chart.radius + + + + widgets.chart.inner-radius + + + + widgets.chart.tilt + + +
+ + {{ 'widgets.chart.show-labels' | translate }} + + + {{ 'widgets.chart.show-tooltip' | translate }} + +
+
+ widgets.chart.stroke-settings +
+ + widgets.chart.width-pixels + + + + +
+
+
+ widgets.chart.animation-settings + + {{ 'widgets.chart.animated-pie' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.ts new file mode 100644 index 0000000000..6ea9c18139 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-pie-widget-settings.component.ts @@ -0,0 +1,79 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-flot-pie-widget-settings', + templateUrl: './flot-pie-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class FlotPieWidgetSettingsComponent extends WidgetSettingsComponent { + + flotPieWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.flotPieWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + radius: 1, + innerRadius: 0, + tilt: 1, + stroke: { + color: '', + width: 0 + }, + showLabels: false, + showTooltip: true, + animatedPie: false + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + + this.flotPieWidgetSettingsForm = this.fb.group({ + + // Common pie settings + + radius: [settings.radius, [Validators.min(0)]], + innerRadius: [settings.innerRadius, [Validators.min(0)]], + tilt: [settings.tilt, [Validators.min(0)]], + + // Stroke settings + + stroke: this.fb.group({ + color: [settings.stroke?.color, []], + width: [settings.stroke?.width, [Validators.min(0)]] + }), + + showLabels: [settings.showLabels, []], + showTooltip: [settings.showTooltip, []], + + animatedPie: [settings.animatedPie, []], + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.html new file mode 100644 index 0000000000..46278cc45e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.html @@ -0,0 +1,58 @@ + + + +
+ +
+
{{ thresholdText() }}
+
+
+
+
+
+ + +
+
+ +
+ +
+ +
+ + widgets.chart.line-width + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.scss new file mode 100644 index 0000000000..06d9988e53 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.flot-threshold { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.flot-threshold { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.ts new file mode 100644 index 0000000000..61f3a16176 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-threshold.component.ts @@ -0,0 +1,136 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { ValueSourceProperty } from '@home/components/widget/lib/settings/common/value-source.component'; +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { isNumber } from '@core/utils'; +import { IAliasController } from '@core/api/widget-api.models'; +import { TbFlotKeyThreshold } from '@home/components/widget/lib/flot-widget.models'; + +@Component({ + selector: 'tb-flot-threshold', + templateUrl: './flot-threshold.component.html', + styleUrls: ['./flot-threshold.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => FlotThresholdComponent), + multi: true + } + ] +}) +export class FlotThresholdComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Input() + aliasController: IAliasController; + + @Output() + removeThreshold = new EventEmitter(); + + private modelValue: TbFlotKeyThreshold; + + private propagateChange = null; + + public thresholdFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.thresholdFormGroup = this.fb.group({ + valueSource: [null, []], + lineWidth: [null, [Validators.min(0)]], + color: [null, []] + }); + this.thresholdFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.thresholdFormGroup.disable({emitEvent: false}); + } else { + this.thresholdFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TbFlotKeyThreshold): void { + this.modelValue = value; + const valueSource: ValueSourceProperty = { + valueSource: value?.thresholdValueSource, + entityAlias: value?.thresholdEntityAlias, + attribute: value?.thresholdAttribute, + value: value?.thresholdValue + }; + this.thresholdFormGroup.patchValue( + {valueSource, lineWidth: value?.lineWidth, color: value?.color}, {emitEvent: false} + ); + } + + thresholdText(): string { + const value: ValueSourceProperty = this.thresholdFormGroup.get('valueSource').value; + return this.valueSourcePropertyText(value); + } + + private valueSourcePropertyText(source?: ValueSourceProperty): string { + if (source) { + if (source.valueSource === 'predefinedValue') { + return `${isNumber(source.value) ? source.value : 0}`; + } else if (source.valueSource === 'entityAttribute') { + const alias = source.entityAlias || 'Undefined'; + const key = source.attribute || 'Undefined'; + return `${alias}.${key}`; + } + } + return 'Undefined'; + } + + private updateModel() { + const value: {valueSource: ValueSourceProperty, lineWidth: number, color: string} = this.thresholdFormGroup.value; + this.modelValue = { + thresholdValueSource: value?.valueSource?.valueSource, + thresholdEntityAlias: value?.valueSource?.entityAlias, + thresholdAttribute: value?.valueSource?.attribute, + thresholdValue: value?.valueSource?.value, + lineWidth: value?.lineWidth, + color: value?.color + }; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.html new file mode 100644 index 0000000000..2cf14d066d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.html @@ -0,0 +1,333 @@ + +
+
+ widgets.chart.common-settings + + {{ 'widgets.chart.enable-stacking-mode' | translate }} + +
+ + widgets.chart.line-shadow-size + + + + {{ 'widgets.chart.display-smooth-lines' | translate }} + +
+
+ + widgets.chart.default-bar-width + + + + widgets.chart.bar-alignment + + + {{ 'widgets.chart.bar-alignment-left' | translate }} + + + {{ 'widgets.chart.bar-alignment-right' | translate }} + + + {{ 'widgets.chart.bar-alignment-center' | translate }} + + + +
+
+ + widgets.chart.default-font-size + + + + +
+ + widgets.chart.thresholds-line-width + + +
+
+ widgets.chart.tooltip-settings + + + + + {{ 'widgets.chart.show-tooltip' | translate }} + + + + widget-config.advanced-settings + + + +
+ + {{ 'widgets.chart.hover-individual-points' | translate }} + + + {{ 'widgets.chart.show-cumulative-values' | translate }} + + + {{ 'widgets.chart.hide-zero-false-values' | translate }} + + + +
+
+
+
+
+ widgets.chart.grid-settings + + {{ 'widgets.chart.show-vertical-lines' | translate }} + + + {{ 'widgets.chart.show-horizontal-lines' | translate }} + + + widgets.chart.grid-outline-border-width + + + + + + + + +
+
+ widgets.chart.xaxis-settings + + widgets.chart.axis-title + + +
+ widgets.chart.xaxis-tick-labels-settings + + + + + {{ 'widgets.chart.show-tick-labels' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+
+ widgets.chart.yaxis-settings + + widgets.chart.axis-title + + +
+ + widgets.chart.min-scale-value + + + + widgets.chart.max-scale-value + + +
+
+ widgets.chart.yaxis-tick-labels-settings + + + + + {{ 'widgets.chart.show-tick-labels' | translate }} + + + + widget-config.advanced-settings + + + + + +
+ + widgets.chart.tick-step-size + + + + widgets.chart.number-of-decimals + + +
+ + +
+
+
+
+
+ widgets.chart.comparison-settings + + + + + {{ 'widgets.chart.enable-comparison' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.chart.time-for-comparison + + + {{ 'widgets.chart.time-for-comparison-previous-interval' | translate }} + + + {{ 'widgets.chart.time-for-comparison-days' | translate }} + + + {{ 'widgets.chart.time-for-comparison-weeks' | translate }} + + + {{ 'widgets.chart.time-for-comparison-months' | translate }} + + + {{ 'widgets.chart.time-for-comparison-years' | translate }} + + + {{ 'widgets.chart.time-for-comparison-custom-interval' | translate }} + + + + + widgets.chart.custom-interval-value + + +
+ widgets.chart.comparison-x-axis-settings + + widgets.chart.axis-title + + + + widgets.chart.axis-position + + + {{ 'widgets.chart.axis-position-top' | translate }} + + + {{ 'widgets.chart.axis-position-bottom' | translate }} + + + + + {{ 'widgets.chart.show-tick-labels' | translate }} + +
+
+
+
+
+
+ widgets.chart.custom-legend-settings + + + + + {{ 'widgets.chart.enable-custom-legend' | translate }} + + + + widget-config.advanced-settings + + + +
+ widgets.chart.label-keys-list +
+
+
+ + +
+
+
+ widgets.chart.no-label-keys +
+
+ +
+
+
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.ts new file mode 100644 index 0000000000..8d00d55b63 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/flot-widget-settings.component.ts @@ -0,0 +1,410 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormArray, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { ChartType, TbFlotSettings } from '@home/components/widget/lib/flot-widget.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { ComparisonDuration } from '@shared/models/time/time.models'; +import { WidgetService } from '@core/http/widget.service'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; +import { + LabelDataKey, + labelDataKeyValidator +} from '@home/components/widget/lib/settings/chart/label-data-key.component'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; + +export function flotDefaultSettings(chartType: ChartType): Partial { + const settings: Partial = { + stack: false, + fontColor: '#545454', + fontSize: 10, + showTooltip: true, + tooltipIndividual: false, + tooltipCumulative: false, + hideZeros: false, + tooltipValueFormatter: '', + grid: { + verticalLines: true, + horizontalLines: true, + outlineWidth: 1, + color: '#545454', + backgroundColor: null, + tickColor: '#DDDDDD' + }, + xaxis: { + title: null, + showLabels: true, + color: null + }, + yaxis: { + min: null, + max: null, + title: null, + showLabels: true, + color: null, + tickSize: null, + tickDecimals: 0, + ticksFormatter: '' + } + }; + if (chartType === 'graph') { + settings.smoothLines = false; + settings.shadowSize = 4; + } + if (chartType === 'bar') { + settings.defaultBarWidth = 600; + settings.barAlignment = 'left'; + } + if (chartType === 'graph' || chartType === 'bar') { + settings.thresholdsLineWidth = null; + settings.comparisonEnabled = false; + settings.timeForComparison = 'previousInterval'; + settings.comparisonCustomIntervalValue = 7200000; + settings.xaxisSecond = { + title: null, + axisPosition: 'top', + showLabels: true + }; + settings.customLegendEnabled = false; + settings.dataKeysListForLabels = []; + } + return settings; +} + +@Component({ + selector: 'tb-flot-widget-settings', + templateUrl: './flot-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => FlotWidgetSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => FlotWidgetSettingsComponent), + multi: true, + } + ] +}) +export class FlotWidgetSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + chartType: ChartType; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: TbFlotSettings; + + private propagateChange = null; + + public flotSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.flotSettingsFormGroup = this.fb.group({ + + // Common settings + + stack: [false, []], + fontSize: [10, [Validators.min(0)]], + fontColor: ['#545454', []], + + // Tooltip settings + + showTooltip: [true, []], + tooltipIndividual: [false, []], + tooltipCumulative: [false, []], + hideZeros: [false, []], + tooltipValueFormatter: ['', []], + + // Grid settings + + grid: this.fb.group({ + verticalLines: [true, []], + horizontalLines: [true, []], + outlineWidth: [1, [Validators.min(0)]], + color: ['#545454', []], + backgroundColor: [null, []], + tickColor: ['#DDDDDD', []] + }), + + // X axis settings + + xaxis: this.fb.group({ + title: [null, []], + + // --> X axis tick labels settings + + showLabels: [true, []], + color: [null, []], + }), + + // Y axis settings + + yaxis: this.fb.group({ + min: [null, []], + max: [null, []], + title: [null, []], + + // --> Y axis tick labels settings + + showLabels: [true, []], + color: [null, []], + tickSize: [null, [Validators.min(0)]], + tickDecimals: [0, [Validators.min(0)]], + ticksFormatter: ['', []] + }) + }); + if (this.chartType === 'graph') { + // Common settings + this.flotSettingsFormGroup.addControl('shadowSize', this.fb.control(4, [Validators.min(0)])); + this.flotSettingsFormGroup.addControl('smoothLines', this.fb.control(false, [])); + } else if (this.chartType === 'bar') { + // Common settings + this.flotSettingsFormGroup.addControl('defaultBarWidth', this.fb.control(600, [Validators.min(0)])); + this.flotSettingsFormGroup.addControl('barAlignment', this.fb.control('left', [])); + } + if (this.chartType === 'graph' || this.chartType === 'bar') { + // Common settings + this.flotSettingsFormGroup.addControl('thresholdsLineWidth', this.fb.control(null, [Validators.min(0)])); + + // Comparison settings + + this.flotSettingsFormGroup.addControl('comparisonEnabled', this.fb.control(false, [])); + this.flotSettingsFormGroup.addControl('timeForComparison', this.fb.control('previousInterval', [])); + this.flotSettingsFormGroup.addControl('comparisonCustomIntervalValue', this.fb.control(7200000, [Validators.min(0)])); + + // --> Comparison X axis settings + + this.flotSettingsFormGroup.addControl('xaxisSecond', this.fb.group({ + axisPosition: ['top', []], + title: [null, []], + showLabels: [true, []] + })); + + // Custom legend settings + + this.flotSettingsFormGroup.addControl('customLegendEnabled', this.fb.control(false, [])); + this.flotSettingsFormGroup.addControl('dataKeysListForLabels', this.fb.control(this.fb.array([]), [])); + } + + this.flotSettingsFormGroup.get('showTooltip').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + this.flotSettingsFormGroup.get('xaxis.showLabels').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + this.flotSettingsFormGroup.get('yaxis.showLabels').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + + if (this.chartType === 'graph' || this.chartType === 'bar') { + this.flotSettingsFormGroup.get('comparisonEnabled').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.flotSettingsFormGroup.get('timeForComparison').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.flotSettingsFormGroup.get('customLegendEnabled').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + } + + this.flotSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.flotSettingsFormGroup.disable({emitEvent: false}); + } else { + this.flotSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TbFlotSettings): void { + const dataKeysListForLabels = value?.dataKeysListForLabels; + this.modelValue = value; + this.flotSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + const dataKeysListForLabelsControls: Array = []; + if (dataKeysListForLabels && dataKeysListForLabels.length) { + dataKeysListForLabels.forEach((labelDataKey) => { + dataKeysListForLabelsControls.push(this.fb.control(labelDataKey, [labelDataKeyValidator])); + }); + } + this.flotSettingsFormGroup.setControl('dataKeysListForLabels', this.fb.array(dataKeysListForLabelsControls), {emitEvent: false}); + this.updateValidators(false); + } + + validate(c: FormControl) { + return (this.flotSettingsFormGroup.valid) ? null : { + flotSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: TbFlotSettings = this.flotSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showTooltip: boolean = this.flotSettingsFormGroup.get('showTooltip').value; + const xaxisShowLabels: boolean = this.flotSettingsFormGroup.get('xaxis.showLabels').value; + const yaxisShowLabels: boolean = this.flotSettingsFormGroup.get('yaxis.showLabels').value; + + if (showTooltip) { + this.flotSettingsFormGroup.get('tooltipIndividual').enable({emitEvent}); + this.flotSettingsFormGroup.get('tooltipCumulative').enable({emitEvent}); + this.flotSettingsFormGroup.get('hideZeros').enable({emitEvent}); + this.flotSettingsFormGroup.get('tooltipValueFormatter').enable({emitEvent}); + } else { + this.flotSettingsFormGroup.get('tooltipIndividual').disable({emitEvent}); + this.flotSettingsFormGroup.get('tooltipCumulative').disable({emitEvent}); + this.flotSettingsFormGroup.get('hideZeros').disable({emitEvent}); + this.flotSettingsFormGroup.get('tooltipValueFormatter').disable({emitEvent}); + } + + if (xaxisShowLabels) { + this.flotSettingsFormGroup.get('xaxis.color').enable({emitEvent}); + } else { + this.flotSettingsFormGroup.get('xaxis.color').disable({emitEvent}); + } + + if (yaxisShowLabels) { + this.flotSettingsFormGroup.get('yaxis.color').enable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.tickSize').enable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.tickDecimals').enable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.ticksFormatter').enable({emitEvent}); + } else { + this.flotSettingsFormGroup.get('yaxis.color').disable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.tickSize').disable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.tickDecimals').disable({emitEvent}); + this.flotSettingsFormGroup.get('yaxis.ticksFormatter').disable({emitEvent}); + } + + this.flotSettingsFormGroup.get('tooltipIndividual').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('tooltipCumulative').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('hideZeros').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('tooltipValueFormatter').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('xaxis.color').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('yaxis.color').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('yaxis.tickSize').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('yaxis.tickDecimals').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('yaxis.ticksFormatter').updateValueAndValidity({emitEvent: false}); + + if (this.chartType === 'graph' || this.chartType === 'bar') { + const comparisonEnabled: boolean = this.flotSettingsFormGroup.get('comparisonEnabled').value; + const timeForComparison: ComparisonDuration = this.flotSettingsFormGroup.get('timeForComparison').value; + const customLegendEnabled: boolean = this.flotSettingsFormGroup.get('customLegendEnabled').value; + if (comparisonEnabled) { + this.flotSettingsFormGroup.get('timeForComparison').enable({emitEvent: false}); + if (timeForComparison === 'customInterval') { + this.flotSettingsFormGroup.get('comparisonCustomIntervalValue').enable({emitEvent}); + } else { + this.flotSettingsFormGroup.get('comparisonCustomIntervalValue').disable({emitEvent}); + } + } else { + this.flotSettingsFormGroup.get('timeForComparison').disable({emitEvent: false}); + this.flotSettingsFormGroup.get('comparisonCustomIntervalValue').disable({emitEvent}); + } + if (customLegendEnabled) { + this.flotSettingsFormGroup.get('dataKeysListForLabels').enable({emitEvent}); + } else { + this.flotSettingsFormGroup.get('dataKeysListForLabels').disable({emitEvent}); + } + + this.flotSettingsFormGroup.get('timeForComparison').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('comparisonCustomIntervalValue').updateValueAndValidity({emitEvent: false}); + this.flotSettingsFormGroup.get('dataKeysListForLabels').updateValueAndValidity({emitEvent: false}); + } + } + + dataKeysListForLabelsFormArray(): FormArray { + return this.flotSettingsFormGroup.get('dataKeysListForLabels') as FormArray; + } + + public trackByLabelDataKey(index: number, labelDataKeyControl: AbstractControl): any { + return labelDataKeyControl; + } + + public removeLabelDataKey(index: number) { + (this.flotSettingsFormGroup.get('dataKeysListForLabels') as FormArray).removeAt(index); + } + + public addLabelDataKey() { + const labelDataKey: LabelDataKey = { + name: null, + type: DataKeyType.attribute + }; + const dataKeysListForLabelsArray = this.flotSettingsFormGroup.get('dataKeysListForLabels') as FormArray; + const labelDataKeyControl = this.fb.control(labelDataKey, [labelDataKeyValidator]); + (labelDataKeyControl as any).new = true; + dataKeysListForLabelsArray.push(labelDataKeyControl); + this.flotSettingsFormGroup.updateValueAndValidity(); + } + + labelDataKeyDrop(event: CdkDragDrop) { + const dataKeysListForLabelsArray = this.flotSettingsFormGroup.get('dataKeysListForLabels') as FormArray; + const labelDataKey = dataKeysListForLabelsArray.at(event.previousIndex); + dataKeysListForLabelsArray.removeAt(event.previousIndex); + dataKeysListForLabelsArray.insert(event.currentIndex, labelDataKey); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.html new file mode 100644 index 0000000000..50dc16d6fb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.html @@ -0,0 +1,63 @@ + + + +
+ +
+ {{ labelDataKeyText() }} +
+
+ + +
+
+ +
+ +
+
+ + widgets.chart.key-name + + + {{ 'widgets.chart.key-name-required' | translate }} + + + + widgets.chart.key-type + + + {{ 'widgets.chart.key-type-attribute' | translate }} + + + {{ 'widgets.chart.key-type-timeseries' | translate }} + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.scss new file mode 100644 index 0000000000..d82e4b34b9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.label-data-key { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.label-data-key { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.ts new file mode 100644 index 0000000000..940c135c1e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/chart/label-data-key.component.ts @@ -0,0 +1,132 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormBuilder, + FormGroup, + NG_VALUE_ACCESSOR, ValidationErrors, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; + +export interface LabelDataKey { + name: string; + type: DataKeyType; +} + +export function labelDataKeyValidator(control: AbstractControl): ValidationErrors | null { + const labelDataKey: LabelDataKey = control.value; + if (!labelDataKey || !labelDataKey.name) { + return { + labelDataKey: true + }; + } + return null; +} + +@Component({ + selector: 'tb-label-data-key', + templateUrl: './label-data-key.component.html', + styleUrls: ['./label-data-key.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => LabelDataKeyComponent), + multi: true + } + ] +}) +export class LabelDataKeyComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Output() + removeLabelDataKey = new EventEmitter(); + + private modelValue: LabelDataKey; + + private propagateChange = null; + + public labelDataKeyFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.labelDataKeyFormGroup = this.fb.group({ + name: [null, [Validators.required]], + type: [DataKeyType.attribute, [Validators.required]] + }); + this.labelDataKeyFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.labelDataKeyFormGroup.disable({emitEvent: false}); + } else { + this.labelDataKeyFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: LabelDataKey): void { + this.modelValue = value; + this.labelDataKeyFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + labelDataKeyText(): string { + const name: string = this.labelDataKeyFormGroup.get('name').value || ''; + const type: DataKeyType = this.labelDataKeyFormGroup.get('type').value; + let typeStr: string; + if (type === DataKeyType.attribute) { + typeStr = this.translate.instant('widgets.chart.key-type-attribute'); + } else if (type === DataKeyType.timeseries) { + typeStr = this.translate.instant('widgets.chart.key-type-timeseries'); + } + return `${name} (${typeStr})`; + } + + private updateModel() { + const value: LabelDataKey = this.labelDataKeyFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.html new file mode 100644 index 0000000000..d4e1e669f6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.html @@ -0,0 +1,76 @@ + +
+ + widgets.value-source.value-source + + + {{ 'widgets.value-source.predefined-value' | translate }} + + + {{ 'widgets.value-source.entity-attribute' | translate }} + + + + + widgets.value-source.value + + +
+ + {{ 'widgets.value-source.source-entity-alias' | translate }} + + + + + + + + + + {{ 'widgets.value-source.source-entity-attribute' | translate }} + + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.ts new file mode 100644 index 0000000000..144904ca41 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/value-source.component.ts @@ -0,0 +1,255 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, HostBinding, Input, OnInit, ViewChild } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { IAliasController } from '@core/api/widget-api.models'; +import { Observable, of } from 'rxjs'; +import { catchError, map, mergeMap, publishReplay, refCount, tap } from 'rxjs/operators'; +import { DataKey } from '@shared/models/widget.models'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { EntityService } from '@core/http/entity.service'; + +export declare type ValueSource = 'predefinedValue' | 'entityAttribute'; + +export interface ValueSourceProperty { + valueSource: ValueSource; + entityAlias?: string; + attribute?: string; + value?: number; +} + +@Component({ + selector: 'tb-value-source', + templateUrl: './value-source.component.html', + styleUrls: [], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => ValueSourceComponent), + multi: true + } + ] +}) +export class ValueSourceComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @HostBinding('style.display') display = 'block'; + + @ViewChild('entityAliasInput') entityAliasInput: ElementRef; + + @ViewChild('keyInput') keyInput: ElementRef; + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + private modelValue: ValueSourceProperty; + + private propagateChange = null; + + public valueSourceFormGroup: FormGroup; + + filteredEntityAliases: Observable>; + aliasSearchText = ''; + + filteredKeys: Observable>; + keySearchText = ''; + + private latestKeySearchResult: Array = null; + private keysFetchObservable$: Observable> = null; + + private entityAliasList: Array = []; + + constructor(protected store: Store, + private translate: TranslateService, + private entityService: EntityService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.valueSourceFormGroup = this.fb.group({ + valueSource: ['predefinedValue', []], + entityAlias: [null, []], + attribute: [null, []], + value: [null, []] + }); + this.valueSourceFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.valueSourceFormGroup.get('valueSource').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + + this.filteredEntityAliases = this.valueSourceFormGroup.get('entityAlias').valueChanges + .pipe( + tap(() => { + this.latestKeySearchResult = null; + this.keysFetchObservable$ = null; + this.valueSourceFormGroup.get('attribute').setValue(this.valueSourceFormGroup.get('attribute').value); + }), + map(value => value ? value : ''), + mergeMap(name => this.fetchEntityAliases(name) ) + ); + + this.filteredKeys = this.valueSourceFormGroup.get('attribute').valueChanges + .pipe( + map(value => value ? value : ''), + mergeMap(name => this.fetchKeys(name) ) + ); + + if (this.aliasController) { + const entityAliases = this.aliasController.getEntityAliases(); + for (const aliasId of Object.keys(entityAliases)) { + this.entityAliasList.push(entityAliases[aliasId].alias); + } + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.valueSourceFormGroup.disable({emitEvent: false}); + } else { + this.valueSourceFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: ValueSourceProperty): void { + this.modelValue = value; + this.valueSourceFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + clearEntityAlias() { + this.valueSourceFormGroup.get('entityAlias').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.entityAliasInput.nativeElement.blur(); + this.entityAliasInput.nativeElement.focus(); + }, 0); + } + + clearKey() { + this.valueSourceFormGroup.get('attribute').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.keyInput.nativeElement.blur(); + this.keyInput.nativeElement.focus(); + }, 0); + } + + private fetchEntityAliases(searchText?: string): Observable> { + this.aliasSearchText = searchText; + let result = this.entityAliasList; + if (searchText && searchText.length) { + result = this.entityAliasList.filter((entityAlias) => entityAlias.toLowerCase().includes(searchText.toLowerCase())); + } + return of(result); + } + + private fetchKeys(searchText?: string): Observable> { + if (this.keySearchText !== searchText || this.latestKeySearchResult === null) { + this.keySearchText = searchText; + const dataKeyFilter = this.createKeyFilter(this.keySearchText); + return this.getKeys().pipe( + map(name => name.filter(dataKeyFilter)), + tap(res => this.latestKeySearchResult = res) + ); + } + return of(this.latestKeySearchResult); + } + + private getKeys() { + if (this.keysFetchObservable$ === null) { + let fetchObservable: Observable>; + let entityAliasId: string; + const entityAlias: string = this.valueSourceFormGroup.get('entityAlias').value; + if (entityAlias && this.aliasController) { + entityAliasId = this.aliasController.getEntityAliasId(entityAlias); + } + if (entityAliasId) { + const dataKeyTypes = [DataKeyType.attribute]; + fetchObservable = this.fetchEntityKeys(entityAliasId, dataKeyTypes); + } else { + fetchObservable = of([]); + } + this.keysFetchObservable$ = fetchObservable.pipe( + map((dataKeys) => dataKeys.map((dataKey) => dataKey.name)), + publishReplay(1), + refCount() + ); + } + return this.keysFetchObservable$; + } + + private fetchEntityKeys(entityAliasId: string, dataKeyTypes: Array): Observable> { + return this.aliasController.getAliasInfo(entityAliasId).pipe( + mergeMap((aliasInfo) => { + return this.entityService.getEntityKeysByEntityFilter( + aliasInfo.entityFilter, + dataKeyTypes, + {ignoreLoading: true, ignoreErrors: true} + ).pipe( + catchError(() => of([])) + ); + }), + catchError(() => of([] as Array)) + ); + } + + private createKeyFilter(query: string): (key: string) => boolean { + const lowercaseQuery = query.toLowerCase(); + return key => key.toLowerCase().startsWith(lowercaseQuery); + } + + private updateModel() { + const value: ValueSourceProperty = this.valueSourceFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const valueSource: ValueSource = this.valueSourceFormGroup.get('valueSource').value; + if (valueSource === 'predefinedValue') { + this.valueSourceFormGroup.get('entityAlias').disable({emitEvent}); + this.valueSourceFormGroup.get('attribute').disable({emitEvent}); + this.valueSourceFormGroup.get('value').enable({emitEvent}); + } else if (valueSource === 'entityAttribute') { + this.valueSourceFormGroup.get('entityAlias').enable({emitEvent}); + this.valueSourceFormGroup.get('attribute').enable({emitEvent}); + this.valueSourceFormGroup.get('value').disable({emitEvent}); + } + this.valueSourceFormGroup.get('entityAlias').updateValueAndValidity({emitEvent: false}); + this.valueSourceFormGroup.get('attribute').updateValueAndValidity({emitEvent: false}); + this.valueSourceFormGroup.get('value').updateValueAndValidity({emitEvent: false}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.html new file mode 100644 index 0000000000..e076dadf59 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.html @@ -0,0 +1,86 @@ + +
+
+ + widgets.widget-font.font-family + + + + {{ sizeTitle }} + + +
+
+ + widgets.widget-font.font-style + + + {{ 'widgets.widget-font.font-style-normal' | translate }} + + + {{ 'widgets.widget-font.font-style-italic' | translate }} + + + {{ 'widgets.widget-font.font-style-oblique' | translate }} + + + + + widgets.widget-font.font-weight + + + {{ 'widgets.widget-font.font-weight-normal' | translate }} + + + {{ 'widgets.widget-font.font-weight-bold' | translate }} + + + {{ 'widgets.widget-font.font-weight-bolder' | translate }} + + + {{ 'widgets.widget-font.font-weight-lighter' | translate }} + + 100 + 200 + 300 + 400 + 500 + 600 + 700 + 800 + 900 + + +
+
+ + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.ts new file mode 100644 index 0000000000..6600bb25a1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/widget-font.component.ts @@ -0,0 +1,114 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, HostBinding, Input, OnInit } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; + +export interface WidgetFont { + family: string; + size: number; + style: 'normal' | 'italic' | 'oblique'; + weight: 'normal' | 'bold' | 'bolder' | 'lighter' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; + color: string; + shadowColor?: string; +} + +@Component({ + selector: 'tb-widget-font', + templateUrl: './widget-font.component.html', + styleUrls: [], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => WidgetFontComponent), + multi: true + } + ] +}) +export class WidgetFontComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @HostBinding('style.display') display = 'block'; + + @Input() + disabled: boolean; + + @Input() + hasShadowColor = false; + + @Input() + sizeTitle = 'widgets.widget-font.size'; + + private modelValue: WidgetFont; + + private propagateChange = null; + + public widgetFontFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.widgetFontFormGroup = this.fb.group({ + family: [null, []], + size: [null, [Validators.min(1)]], + style: [null, []], + weight: [null, []], + color: [null, []] + }); + if (this.hasShadowColor) { + this.widgetFontFormGroup.addControl('shadowColor', this.fb.control(null, [])); + } + this.widgetFontFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.widgetFontFormGroup.disable({emitEvent: false}); + } else { + this.widgetFontFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: WidgetFont): void { + this.modelValue = value; + this.widgetFontFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + private updateModel() { + const value: WidgetFont = this.widgetFontFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.html new file mode 100644 index 0000000000..d60481fc8c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.html @@ -0,0 +1,41 @@ + + + {{ (keyType === dataKeyType.attribute + ? attributeLabel + : timeseriesLabel) | translate }} + + + + + + + + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.ts new file mode 100644 index 0000000000..46ce0034ee --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/device-key-autocomplete.component.ts @@ -0,0 +1,216 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnChanges, OnInit, SimpleChanges, ViewChild } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { Observable, of } from 'rxjs'; +import { IAliasController } from '@core/api/widget-api.models'; +import { catchError, map, mergeMap, publishReplay, refCount, tap } from 'rxjs/operators'; +import { DataKey } from '@shared/models/widget.models'; +import { EntityService } from '@core/http/entity.service'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; + +@Component({ + selector: 'tb-device-key-autocomplete', + templateUrl: './device-key-autocomplete.component.html', + styleUrls: [], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => DeviceKeyAutocompleteComponent), + multi: true + } + ] +}) +export class DeviceKeyAutocompleteComponent extends PageComponent implements OnInit, ControlValueAccessor, OnChanges { + + @ViewChild('keyInput') keyInput: ElementRef; + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + @Input() + targetDeviceAliasId: string; + + @Input() + keyType: DataKeyType; + + @Input() + attributeLabel = 'widgets.rpc.attribute-value-key'; + + @Input() + timeseriesLabel = 'widgets.rpc.timeseries-value-key'; + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + dataKeyType = DataKeyType; + + private modelValue: string; + + private propagateChange = null; + + public deviceKeyFormGroup: FormGroup; + + filteredKeys: Observable>; + keySearchText = ''; + + private latestKeySearchResult: Array = null; + private keysFetchObservable$: Observable> = null; + + constructor(protected store: Store, + private translate: TranslateService, + private entityService: EntityService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.deviceKeyFormGroup = this.fb.group({ + key: [null, this.required ? [Validators.required] : []] + }); + this.deviceKeyFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + + this.filteredKeys = this.deviceKeyFormGroup.get('key').valueChanges + .pipe( + map(value => value ? value : ''), + mergeMap(name => this.fetchKeys(name) ) + ); + } + + ngOnChanges(changes: SimpleChanges): void { + for (const propName of Object.keys(changes)) { + const change = changes[propName]; + if (!change.firstChange && change.currentValue !== change.previousValue) { + if (propName === 'targetDeviceAliasId' || propName === 'keyType') { + this.clearKeysCache(); + } + } + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.deviceKeyFormGroup.disable({emitEvent: false}); + } else { + this.deviceKeyFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: string): void { + this.modelValue = value; + this.deviceKeyFormGroup.patchValue( + {key: value}, {emitEvent: false} + ); + } + + clearKey() { + this.deviceKeyFormGroup.get('key').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.keyInput.nativeElement.blur(); + this.keyInput.nativeElement.focus(); + }, 0); + } + + onFocus() { + this.deviceKeyFormGroup.get('key').updateValueAndValidity({onlySelf: true, emitEvent: true}); + } + + private updateModel() { + const value: string = this.deviceKeyFormGroup.get('key').value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private clearKeysCache(): void { + this.latestKeySearchResult = null; + this.keysFetchObservable$ = null; + } + + private fetchKeys(searchText?: string): Observable> { + if (this.keySearchText !== searchText || this.latestKeySearchResult === null) { + this.keySearchText = searchText; + const dataKeyFilter = this.createKeyFilter(this.keySearchText); + return this.getKeys().pipe( + map(name => name.filter(dataKeyFilter)), + tap(res => this.latestKeySearchResult = res) + ); + } + return of(this.latestKeySearchResult); + } + + private getKeys() { + if (this.keysFetchObservable$ === null) { + let fetchObservable: Observable>; + if (this.targetDeviceAliasId) { + const dataKeyTypes = [this.keyType]; + fetchObservable = this.fetchEntityKeys(this.targetDeviceAliasId, dataKeyTypes); + } else { + fetchObservable = of([]); + } + this.keysFetchObservable$ = fetchObservable.pipe( + map((dataKeys) => dataKeys.map((dataKey) => dataKey.name)), + publishReplay(1), + refCount() + ); + } + return this.keysFetchObservable$; + } + + private fetchEntityKeys(entityAliasId: string, dataKeyTypes: Array): Observable> { + return this.aliasController.getAliasInfo(entityAliasId).pipe( + mergeMap((aliasInfo) => { + return this.entityService.getEntityKeysByEntityFilter( + aliasInfo.entityFilter, + dataKeyTypes, + {ignoreLoading: true, ignoreErrors: true} + ).pipe( + catchError(() => of([])) + ); + }), + catchError(() => of([] as Array)) + ); + } + + private createKeyFilter(query: string): (key: string) => boolean { + const lowercaseQuery = query.toLowerCase(); + return key => key.toLowerCase().startsWith(lowercaseQuery); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.html new file mode 100644 index 0000000000..1788a74446 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.html @@ -0,0 +1,81 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.knob-title + + +
+
+ widgets.rpc.value-settings + + widgets.rpc.initial-value + + +
+ + widgets.rpc.min-value + + + + widgets.rpc.max-value + + +
+ + widgets.rpc.get-value-method + + + + widgets.rpc.set-value-method + + +
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+ widgets.rpc.persistent-rpc-settings + + + + + {{ 'widgets.rpc.request-persistent' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.rpc.persistent-polling-interval + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.ts new file mode 100644 index 0000000000..dae3045110 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/knob-control-widget-settings.component.ts @@ -0,0 +1,95 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-knob-control-widget-settings', + templateUrl: './knob-control-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class KnobControlWidgetSettingsComponent extends WidgetSettingsComponent { + + knobControlWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.knobControlWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + minValue: 0, + maxValue: 100, + initialValue: 50, + getValueMethod: 'getValue', + setValueMethod: 'setValue', + requestTimeout: 500, + requestPersistent: false, + persistentPollingInterval: 5000 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.knobControlWidgetSettingsForm = this.fb.group({ + + // Common settings + + title: [settings.title, []], + + // Value settings + + initialValue: [settings.initialValue, []], + minValue: [settings.minValue, [Validators.required]], + maxValue: [settings.maxValue, [Validators.required]], + + getValueMethod: [settings.getValueMethod, [Validators.required]], + setValueMethod: [settings.setValueMethod, [Validators.required]], + + // RPC settings + + requestTimeout: [settings.requestTimeout, [Validators.min(0), Validators.required]], + + // --> Persistent RPC settings + + requestPersistent: [settings.requestPersistent, []], + persistentPollingInterval: [settings.persistentPollingInterval, [Validators.min(1000)]] + }); + } + + protected validatorTriggers(): string[] { + return ['requestPersistent']; + } + + protected updateValidators(emitEvent: boolean): void { + const requestPersistent: boolean = this.knobControlWidgetSettingsForm.get('requestPersistent').value; + if (requestPersistent) { + this.knobControlWidgetSettingsForm.get('persistentPollingInterval').enable({emitEvent}); + } else { + this.knobControlWidgetSettingsForm.get('persistentPollingInterval').disable({emitEvent}); + } + this.knobControlWidgetSettingsForm.get('persistentPollingInterval').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.html new file mode 100644 index 0000000000..c4e934eabe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.html @@ -0,0 +1,104 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.led-title + + + + +
+
+ widgets.rpc.value-settings + + {{ 'widgets.rpc.initial-value' | translate }} + +
+ widgets.rpc.check-status-settings + + {{ 'widgets.rpc.perform-rpc-status-check' | translate }} + + + widgets.rpc.retrieve-led-status-value-method + + + {{ 'widgets.rpc.retrieve-value-method-attribute' | translate }} + + + {{ 'widgets.rpc.retrieve-value-method-timeseries' | translate }} + + + + + + + widgets.rpc.check-status-method + + + + +
+
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+ widgets.rpc.persistent-rpc-settings + + + + + {{ 'widgets.rpc.request-persistent' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.rpc.persistent-polling-interval + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.ts new file mode 100644 index 0000000000..8ee8ebe127 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/led-indicator-widget-settings.component.ts @@ -0,0 +1,133 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { WidgetService } from '@core/http/widget.service'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; + +@Component({ + selector: 'tb-led-indicator-widget-settings', + templateUrl: './led-indicator-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class LedIndicatorWidgetSettingsComponent extends WidgetSettingsComponent { + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + get targetDeviceAliasId(): string { + const aliasIds = this.widget?.config?.targetDeviceAliasIds; + if (aliasIds && aliasIds.length) { + return aliasIds[0]; + } + return null; + } + + dataKeyType = DataKeyType; + + ledIndicatorWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.ledIndicatorWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + ledColor: 'green', + initialValue: false, + performCheckStatus: true, + checkStatusMethod: 'checkStatus', + retrieveValueMethod: 'attribute', + valueAttribute: 'value', + parseValueFunction: 'return data ? true : false;', + requestTimeout: 500, + requestPersistent: false, + persistentPollingInterval: 5000 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.ledIndicatorWidgetSettingsForm = this.fb.group({ + + // Common settings + + title: [settings.title, []], + ledColor: [settings.ledColor, []], + + // Value settings + + initialValue: [settings.initialValue, []], + + // --> Check status settings + + performCheckStatus: [settings.performCheckStatus, []], + retrieveValueMethod: [settings.retrieveValueMethod, []], + checkStatusMethod: [settings.checkStatusMethod, [Validators.required]], + valueAttribute: [settings.valueAttribute, [Validators.required]], + parseValueFunction: [settings.parseValueFunction, []], + + // RPC settings + + requestTimeout: [settings.requestTimeout, [Validators.min(0)]], + + // --> Persistent RPC settings + + requestPersistent: [settings.requestPersistent, []], + persistentPollingInterval: [settings.persistentPollingInterval, [Validators.min(1000)]] + }); + } + + protected validatorTriggers(): string[] { + return ['performCheckStatus', 'requestPersistent']; + } + + protected updateValidators(emitEvent: boolean): void { + const performCheckStatus: boolean = this.ledIndicatorWidgetSettingsForm.get('performCheckStatus').value; + const requestPersistent: boolean = this.ledIndicatorWidgetSettingsForm.get('requestPersistent').value; + if (performCheckStatus) { + this.ledIndicatorWidgetSettingsForm.get('valueAttribute').disable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('checkStatusMethod').enable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('requestTimeout').enable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('requestPersistent').enable({emitEvent: false}); + if (requestPersistent) { + this.ledIndicatorWidgetSettingsForm.get('persistentPollingInterval').enable({emitEvent}); + } else { + this.ledIndicatorWidgetSettingsForm.get('persistentPollingInterval').disable({emitEvent}); + } + } else { + this.ledIndicatorWidgetSettingsForm.get('valueAttribute').enable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('checkStatusMethod').disable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('requestTimeout').disable({emitEvent}); + this.ledIndicatorWidgetSettingsForm.get('requestPersistent').disable({emitEvent: false}); + this.ledIndicatorWidgetSettingsForm.get('persistentPollingInterval').disable({emitEvent}); + } + this.ledIndicatorWidgetSettingsForm.get('valueAttribute').updateValueAndValidity({emitEvent: false}); + this.ledIndicatorWidgetSettingsForm.get('checkStatusMethod').updateValueAndValidity({emitEvent: false}); + this.ledIndicatorWidgetSettingsForm.get('requestTimeout').updateValueAndValidity({emitEvent: false}); + this.ledIndicatorWidgetSettingsForm.get('requestPersistent').updateValueAndValidity({emitEvent: false}); + this.ledIndicatorWidgetSettingsForm.get('persistentPollingInterval').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.html new file mode 100644 index 0000000000..7961dddf1f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.html @@ -0,0 +1,111 @@ + +
+
+ widgets.persistent-table.general-settings +
+
+ + {{ 'widgets.persistent-table.enable-filter' | translate }} + +
+
+ + {{ 'widgets.persistent-table.enable-sticky-header' | translate }} + + + {{ 'widgets.persistent-table.enable-sticky-action' | translate }} + +
+
+
+ + {{ 'widgets.persistent-table.display-request-details' | translate }} + + + {{ 'widgets.persistent-table.allow-send-request' | translate }} + + + {{ 'widgets.persistent-table.allow-delete-request' | translate }} + +
+ + {{ 'widgets.table.display-pagination' | translate }} + + + widgets.table.default-page-size + + +
+ + widgets.table.default-sort-order + + +
+
+
+ widgets.persistent-table.columns-settings + + widgets.persistent-table.display-columns + + + {{ displayColumnFromValue(column)?.name }} + cancel + + + + + + + + +
+
+ widgets.persistent-table.no-columns-found +
+ + + {{ translate.get('widgets.persistent-table.no-columns-matching', + {column: truncate.transform(columnSearchText, true, 6, '...')}) | async }} + + +
+
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.ts new file mode 100644 index 0000000000..288a133cae --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/persistent-table-widget-settings.component.ts @@ -0,0 +1,221 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, ViewChild } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable, of, Subject } from 'rxjs'; +import { TruncatePipe } from '@shared/pipe/truncate.pipe'; +import { MatChipInputEvent, MatChipList } from '@angular/material/chips'; +import { MatAutocomplete, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; +import { map, mergeMap, share, startWith } from 'rxjs/operators'; +import { COMMA, ENTER, SEMICOLON } from '@angular/cdk/keycodes'; + +interface DisplayColumn { + name: string; + value: string; +} + +@Component({ + selector: 'tb-persistent-table-widget-settings', + templateUrl: './persistent-table-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class PersistentTableWidgetSettingsComponent extends WidgetSettingsComponent { + + @ViewChild('columnsChipList') columnsChipList: MatChipList; + @ViewChild('columnAutocomplete') columnAutocomplete: MatAutocomplete; + @ViewChild('columnInput') columnInput: ElementRef; + + displayColumns: Array = [ + {value: 'rpcId', name: this.translate.instant('widgets.persistent-table.rpc-id')}, + {value: 'messageType', name: this.translate.instant('widgets.persistent-table.message-type')}, + {value: 'status', name: this.translate.instant('widgets.persistent-table.status')}, + {value: 'method', name: this.translate.instant('widgets.persistent-table.method')}, + {value: 'createdTime', name: this.translate.instant('widgets.persistent-table.created-time')}, + {value: 'expirationTime', name: this.translate.instant('widgets.persistent-table.expiration-time')}, + ]; + + separatorKeysCodes = [ENTER, COMMA, SEMICOLON]; + + persistentTableWidgetSettingsForm: FormGroup; + + filteredDisplayColumns: Observable>; + + columnSearchText = ''; + + columnInputChange = new Subject(); + + constructor(protected store: Store, + public translate: TranslateService, + public truncate: TruncatePipe, + private fb: FormBuilder) { + super(store); + this.filteredDisplayColumns = this.columnInputChange + .pipe( + startWith(''), + map((value) => value ? value : ''), + mergeMap(name => this.fetchColumns(name) ), + share() + ); + } + + protected settingsForm(): FormGroup { + return this.persistentTableWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + enableFilter: true, + + enableStickyHeader: true, + enableStickyAction: true, + + displayDetails: true, + allowSendRequest: true, + allowDelete: true, + + displayPagination: true, + defaultPageSize: 10, + + defaultSortOrder: '-createdTime', + displayColumns: ['rpcId', 'messageType', 'status', 'method', 'createdTime', 'expirationTime'] + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.persistentTableWidgetSettingsForm = this.fb.group({ + enableFilter: [settings.enableFilter, []], + enableStickyHeader: [settings.enableStickyHeader, []], + enableStickyAction: [settings.enableStickyAction, []], + allowSendRequest: [settings.allowSendRequest, []], + allowDelete: [settings.allowDelete, []], + displayDetails: [settings.displayDetails, []], + displayPagination: [settings.displayPagination, []], + defaultPageSize: [settings.defaultPageSize, [Validators.min(1)]], + defaultSortOrder: [settings.defaultSortOrder, []], + displayColumns: [settings.displayColumns, [Validators.required]] + }); + } + + protected validateSettings(): boolean { + const displayColumns: string[] = this.persistentTableWidgetSettingsForm.get('displayColumns').value; + this.columnsChipList.errorState = !displayColumns?.length; + return super.validateSettings(); + } + + protected validatorTriggers(): string[] { + return ['displayPagination']; + } + + protected updateValidators(emitEvent: boolean) { + const displayPagination: boolean = this.persistentTableWidgetSettingsForm.get('displayPagination').value; + if (displayPagination) { + this.persistentTableWidgetSettingsForm.get('defaultPageSize').enable(); + } else { + this.persistentTableWidgetSettingsForm.get('defaultPageSize').disable(); + } + this.persistentTableWidgetSettingsForm.get('defaultPageSize').updateValueAndValidity({emitEvent}); + } + + private fetchColumns(searchText?: string): Observable> { + this.columnSearchText = searchText; + if (this.columnSearchText && this.columnSearchText.length) { + const search = this.columnSearchText.toUpperCase(); + return of(this.displayColumns.filter(column => column.name.toUpperCase().includes(search))); + } else { + return of(this.displayColumns); + } + } + + private addColumn(existingColumn: DisplayColumn): boolean { + if (existingColumn) { + const displayColumns: string[] = this.persistentTableWidgetSettingsForm.get('displayColumns').value; + const index = displayColumns.indexOf(existingColumn.value); + if (index === -1) { + displayColumns.push(existingColumn.value); + this.persistentTableWidgetSettingsForm.get('displayColumns').setValue(displayColumns); + this.persistentTableWidgetSettingsForm.get('displayColumns').markAsDirty(); + this.columnsChipList.errorState = false; + return true; + } + } + return false; + } + + displayColumnFromValue(columnValue: string): DisplayColumn | undefined { + return this.displayColumns.find((column) => column.value === columnValue); + } + + displayColumnFn(column?: DisplayColumn): string | undefined { + return column ? column.name : undefined; + } + + textIsNotEmpty(text: string): boolean { + return (text && text.length > 0); + } + + columnDrop(event: CdkDragDrop): void { + const displayColumns: string[] = this.persistentTableWidgetSettingsForm.get('displayColumns').value; + moveItemInArray(displayColumns, event.previousIndex, event.currentIndex); + this.persistentTableWidgetSettingsForm.get('displayColumns').setValue(displayColumns); + this.persistentTableWidgetSettingsForm.get('displayColumns').markAsDirty(); + } + + onColumnRemoved(column: string): void { + const displayColumns: string[] = this.persistentTableWidgetSettingsForm.get('displayColumns').value; + const index = displayColumns.indexOf(column); + if (index > -1) { + displayColumns.splice(index, 1); + this.persistentTableWidgetSettingsForm.get('displayColumns').setValue(displayColumns); + this.persistentTableWidgetSettingsForm.get('displayColumns').markAsDirty(); + this.columnsChipList.errorState = !displayColumns.length; + } + } + + onColumnInputFocus() { + this.columnInputChange.next(this.columnInput.nativeElement.value); + } + + addColumnFromChipInput(event: MatChipInputEvent): void { + const value = event.value; + if ((value || '').trim()) { + const columnName = value.trim().toUpperCase(); + const existingColumn = this.displayColumns.find(column => column.name.toUpperCase() === columnName); + if (this.addColumn(existingColumn)) { + this.clearColumnInput(''); + } + } + } + + columnSelected(event: MatAutocompleteSelectedEvent): void { + this.addColumn(event.option.value); + this.clearColumnInput(''); + } + + clearColumnInput(value: string = '') { + this.columnInput.nativeElement.value = value; + this.columnInputChange.next(null); + setTimeout(() => { + this.columnInput.nativeElement.blur(); + this.columnInput.nativeElement.focus(); + }, 0); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.html new file mode 100644 index 0000000000..30da5695d1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.html @@ -0,0 +1,31 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.switch-title + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.ts new file mode 100644 index 0000000000..cf7ee3bbb9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/round-switch-widget-settings.component.ts @@ -0,0 +1,79 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { switchRpcDefaultSettings } from '@home/components/widget/lib/settings/control/switch-rpc-settings.component'; +import { deepClone } from '@core/utils'; + +@Component({ + selector: 'tb-round-switch-widget-settings', + templateUrl: './round-switch-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class RoundSwitchWidgetSettingsComponent extends WidgetSettingsComponent { + + roundSwitchWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + get targetDeviceAliasId(): string { + const aliasIds = this.widget?.config?.targetDeviceAliasIds; + if (aliasIds && aliasIds.length) { + return aliasIds[0]; + } + return null; + } + + protected settingsForm(): FormGroup { + return this.roundSwitchWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + ...switchRpcDefaultSettings() + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.roundSwitchWidgetSettingsForm = this.fb.group({ + title: [settings.title, []], + switchRpcSettings: [settings.switchRpcSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const switchRpcSettings = deepClone(settings, ['title']); + return { + title: settings.title, + switchRpcSettings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + title: settings.title, + ...settings.switchRpcSettings + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.html new file mode 100644 index 0000000000..1f027eb8b2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.html @@ -0,0 +1,40 @@ + +
+
+ widgets.rpc.button-style + + {{ 'widgets.rpc.button-raised' | translate }} + + + {{ 'widgets.rpc.button-primary' | translate }} + +
+ + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.ts new file mode 100644 index 0000000000..e01c4df9e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-button-style.component.ts @@ -0,0 +1,98 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +export interface RpcButtonStyle { + isRaised: boolean; + isPrimary: boolean; + bgColor: string; + textColor: string; +} + +@Component({ + selector: 'tb-rpc-button-style', + templateUrl: './rpc-button-style.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => RpcButtonStyleComponent), + multi: true + } + ] +}) +export class RpcButtonStyleComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + private modelValue: RpcButtonStyle; + + private propagateChange = null; + + public rpcButtonStyleFormGroup: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.rpcButtonStyleFormGroup = this.fb.group({ + isRaised: [true, []], + isPrimary: [false, []], + bgColor: [null, []], + textColor: [null, []] + }); + this.rpcButtonStyleFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.rpcButtonStyleFormGroup.disable({emitEvent: false}); + } else { + this.rpcButtonStyleFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: RpcButtonStyle): void { + this.modelValue = value; + this.rpcButtonStyleFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + private updateModel() { + this.modelValue = this.rpcButtonStyleFormGroup.value; + this.propagateChange(this.modelValue); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.html new file mode 100644 index 0000000000..67d7caa29f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.html @@ -0,0 +1,27 @@ + + +
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.ts new file mode 100644 index 0000000000..d901ad2636 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-shell-widget-settings.component.ts @@ -0,0 +1,53 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-rpc-shell-widget-settings', + templateUrl: './rpc-shell-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class RpcShellWidgetSettingsComponent extends WidgetSettingsComponent { + + rpcShellWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.rpcShellWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + requestTimeout: 500 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.rpcShellWidgetSettingsForm = this.fb.group({ + // RPC settings + requestTimeout: [settings.requestTimeout, [Validators.min(0), Validators.required]] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.html new file mode 100644 index 0000000000..79c34bfdea --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.html @@ -0,0 +1,49 @@ + + +
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+ widgets.rpc.persistent-rpc-settings + + + + + {{ 'widgets.rpc.request-persistent' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.rpc.persistent-polling-interval + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.ts new file mode 100644 index 0000000000..906c0c71b3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component.ts @@ -0,0 +1,75 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-rpc-terminal-widget-settings', + templateUrl: './rpc-terminal-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class RpcTerminalWidgetSettingsComponent extends WidgetSettingsComponent { + + rpcTerminalWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.rpcTerminalWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + requestTimeout: 500, + requestPersistent: false, + persistentPollingInterval: 5000 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.rpcTerminalWidgetSettingsForm = this.fb.group({ + // RPC settings + + requestTimeout: [settings.requestTimeout, [Validators.min(0), Validators.required]], + + // --> Persistent RPC settings + + requestPersistent: [settings.requestPersistent, []], + persistentPollingInterval: [settings.persistentPollingInterval, [Validators.min(1000)]] + }); + } + + protected validatorTriggers(): string[] { + return ['requestPersistent']; + } + + protected updateValidators(emitEvent: boolean): void { + const requestPersistent: boolean = this.rpcTerminalWidgetSettingsForm.get('requestPersistent').value; + if (requestPersistent) { + this.rpcTerminalWidgetSettingsForm.get('persistentPollingInterval').enable({emitEvent}); + } else { + this.rpcTerminalWidgetSettingsForm.get('persistentPollingInterval').disable({emitEvent}); + } + this.rpcTerminalWidgetSettingsForm.get('persistentPollingInterval').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.html new file mode 100644 index 0000000000..c36a21c349 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.html @@ -0,0 +1,79 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.widget-title + + + + widgets.rpc.button-label + + +
+
+ widgets.rpc.rpc-settings + + {{ 'widgets.rpc.is-one-way-command' | translate }} + + + widgets.rpc.rpc-method + + + + + + widgets.rpc.request-timeout + + + + {{ 'widgets.rpc.show-rpc-error' | translate }} + +
+ widgets.rpc.persistent-rpc-settings + + + + + {{ 'widgets.rpc.request-persistent' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.rpc.persistent-polling-interval + + + + +
+
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.ts new file mode 100644 index 0000000000..051b780ca9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/send-rpc-widget-settings.component.ts @@ -0,0 +1,99 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { ContentType } from '@shared/models/constants'; + +@Component({ + selector: 'tb-send-rpc-widget-settings', + templateUrl: './send-rpc-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class SendRpcWidgetSettingsComponent extends WidgetSettingsComponent { + + sendRpcWidgetSettingsForm: FormGroup; + + contentTypes = ContentType; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.sendRpcWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + buttonText: 'Send RPC', + oneWayElseTwoWay: true, + showError: false, + methodName: 'rpcCommand', + methodParams: '{}', + requestTimeout: 5000, + requestPersistent: false, + persistentPollingInterval: 5000, + styleButton: { + isRaised: true, + isPrimary: false, + bgColor: null, + textColor: null + } + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.sendRpcWidgetSettingsForm = this.fb.group({ + title: [settings.title, []], + buttonText: [settings.buttonText, []], + + // RPC settings + + oneWayElseTwoWay: [settings.oneWayElseTwoWay, []], + methodName: [settings.methodName, []], + methodParams: [settings.methodParams, []], + requestTimeout: [settings.requestTimeout, [Validators.min(0)]], + showError: [settings.showError, []], + + // Persistent RPC settings + + requestPersistent: [settings.requestPersistent, []], + persistentPollingInterval: [settings.persistentPollingInterval, [Validators.min(1000)]], + + styleButton: [settings.styleButton, []] + }); + } + + protected validatorTriggers(): string[] { + return ['requestPersistent']; + } + + protected updateValidators(emitEvent: boolean): void { + const requestPersistent: boolean = this.sendRpcWidgetSettingsForm.get('requestPersistent').value; + if (requestPersistent) { + this.sendRpcWidgetSettingsForm.get('persistentPollingInterval').enable({emitEvent}); + } else { + this.sendRpcWidgetSettingsForm.get('persistentPollingInterval').disable({emitEvent}); + } + this.sendRpcWidgetSettingsForm.get('persistentPollingInterval').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.html new file mode 100644 index 0000000000..7e78ec91a1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.html @@ -0,0 +1,58 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.slide-toggle-label + + +
+ + widgets.rpc.label-position + + + {{ 'widgets.rpc.label-position-before' | translate }} + + + {{ 'widgets.rpc.label-position-after' | translate }} + + + + + widgets.rpc.slider-color + + + {{ 'widgets.rpc.slider-color-primary' | translate }} + + + {{ 'widgets.rpc.slider-color-accent' | translate }} + + + {{ 'widgets.rpc.slider-color-warn' | translate }} + + + +
+
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.ts new file mode 100644 index 0000000000..f95473dbb9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/slide-toggle-widget-settings.component.ts @@ -0,0 +1,87 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { switchRpcDefaultSettings } from '@home/components/widget/lib/settings/control/switch-rpc-settings.component'; +import { deepClone } from '@core/utils'; + +@Component({ + selector: 'tb-slide-toggle-widget-settings', + templateUrl: './slide-toggle-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class SlideToggleWidgetSettingsComponent extends WidgetSettingsComponent { + + slideToggleWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + get targetDeviceAliasId(): string { + const aliasIds = this.widget?.config?.targetDeviceAliasIds; + if (aliasIds && aliasIds.length) { + return aliasIds[0]; + } + return null; + } + + protected settingsForm(): FormGroup { + return this.slideToggleWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + labelPosition: 'after', + sliderColor: 'accent', + ...switchRpcDefaultSettings() + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.slideToggleWidgetSettingsForm = this.fb.group({ + title: [settings.title, []], + labelPosition: [settings.labelPosition, []], + sliderColor: [settings.sliderColor, []], + switchRpcSettings: [settings.switchRpcSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const switchRpcSettings = deepClone(settings, ['title', 'labelPosition', 'sliderColor']); + return { + title: settings.title, + labelPosition: settings.labelPosition, + sliderColor: settings.sliderColor, + switchRpcSettings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + title: settings.title, + labelPosition: settings.labelPosition, + sliderColor: settings.sliderColor, + ...settings.switchRpcSettings + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.html new file mode 100644 index 0000000000..da0b4237db --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.html @@ -0,0 +1,34 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.switch-title + + + + {{ 'widgets.rpc.show-on-off-labels' | translate }} + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.ts new file mode 100644 index 0000000000..65f09f2dd8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-control-widget-settings.component.ts @@ -0,0 +1,83 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { switchRpcDefaultSettings } from '@home/components/widget/lib/settings/control/switch-rpc-settings.component'; +import { deepClone } from '@core/utils'; + +@Component({ + selector: 'tb-switch-control-widget-settings', + templateUrl: './switch-control-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class SwitchControlWidgetSettingsComponent extends WidgetSettingsComponent { + + switchControlWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + get targetDeviceAliasId(): string { + const aliasIds = this.widget?.config?.targetDeviceAliasIds; + if (aliasIds && aliasIds.length) { + return aliasIds[0]; + } + return null; + } + + protected settingsForm(): FormGroup { + return this.switchControlWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + showOnOffLabels: true, + ...switchRpcDefaultSettings() + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.switchControlWidgetSettingsForm = this.fb.group({ + title: [settings.title, []], + showOnOffLabels: [settings.showOnOffLabels, []], + switchRpcSettings: [settings.switchRpcSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const switchRpcSettings = deepClone(settings, ['title', 'showOnOffLabels']); + return { + title: settings.title, + showOnOffLabels: settings.showOnOffLabels, + switchRpcSettings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + title: settings.title, + showOnOffLabels: settings.showOnOffLabels, + ...settings.switchRpcSettings + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.html new file mode 100644 index 0000000000..ec2228cc78 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.html @@ -0,0 +1,108 @@ + +
+
+ widgets.rpc.value-settings + + {{ 'widgets.rpc.initial-value' | translate }} + +
+ widgets.rpc.retrieve-value-settings + + widgets.rpc.retrieve-value-method + + + {{ 'widgets.rpc.retrieve-value-method-none' | translate }} + + + {{ 'widgets.rpc.retrieve-value-method-rpc' | translate }} + + + {{ 'widgets.rpc.retrieve-value-method-attribute' | translate }} + + + {{ 'widgets.rpc.retrieve-value-method-timeseries' | translate }} + + + + + + + widgets.rpc.get-value-method + + + + +
+
+ widgets.rpc.update-value-settings + + widgets.rpc.set-value-method + + + + +
+
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+ widgets.rpc.persistent-rpc-settings + + + + + {{ 'widgets.rpc.request-persistent' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.rpc.persistent-polling-interval + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.ts new file mode 100644 index 0000000000..711d0a0275 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/switch-rpc-settings.component.ts @@ -0,0 +1,219 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { WidgetService } from '@core/http/widget.service'; +import { IAliasController } from '@core/api/widget-api.models'; +import { EntityService } from '@core/http/entity.service'; + +export declare type RpcRetrieveValueMethod = 'none' | 'rpc' | 'attribute' | 'timeseries'; + +export interface SwitchRpcSettings { + initialValue: boolean; + retrieveValueMethod: RpcRetrieveValueMethod; + valueKey: string; + getValueMethod: string; + setValueMethod: string; + parseValueFunction: string; + convertValueFunction: string; + requestTimeout: number; + requestPersistent: boolean; + persistentPollingInterval: number; +} + +export function switchRpcDefaultSettings(): SwitchRpcSettings { + return { + initialValue: false, + retrieveValueMethod: 'rpc', + valueKey: 'value', + getValueMethod: 'getValue', + parseValueFunction: 'return data ? true : false;', + setValueMethod: 'setValue', + convertValueFunction: 'return value;', + requestTimeout: 500, + requestPersistent: false, + persistentPollingInterval: 5000 + }; +} + +@Component({ + selector: 'tb-switch-rpc-settings', + templateUrl: './switch-rpc-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => SwitchRpcSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => SwitchRpcSettingsComponent), + multi: true + } + ] +}) +export class SwitchRpcSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @ViewChild('keyInput') keyInput: ElementRef; + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + @Input() + targetDeviceAliasId: string; + + dataKeyType = DataKeyType; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: SwitchRpcSettings; + + private propagateChange = null; + + public switchRpcSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private entityService: EntityService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.switchRpcSettingsFormGroup = this.fb.group({ + + // Value settings + + initialValue: [false, []], + + // --> Retrieve value settings + + retrieveValueMethod: ['rpc', []], + valueKey: ['value', [Validators.required]], + getValueMethod: ['getValue', [Validators.required]], + parseValueFunction: ['return data ? true : false;', []], + + // --> Update value settings + + setValueMethod: ['setValue', [Validators.required]], + convertValueFunction: ['return value;', []], + + // RPC settings + + requestTimeout: [500, [Validators.min(0)]], + + // Persistent RPC settings + + requestPersistent: [false, []], + persistentPollingInterval: [5000, [Validators.min(1000)]], + }); + this.switchRpcSettingsFormGroup.get('retrieveValueMethod').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.switchRpcSettingsFormGroup.get('requestPersistent').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.switchRpcSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.switchRpcSettingsFormGroup.disable({emitEvent: false}); + } else { + this.switchRpcSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: SwitchRpcSettings): void { + this.modelValue = value; + this.switchRpcSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.switchRpcSettingsFormGroup.valid ? null : { + switchRpcSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: SwitchRpcSettings = this.switchRpcSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const retrieveValueMethod: RpcRetrieveValueMethod = this.switchRpcSettingsFormGroup.get('retrieveValueMethod').value; + const requestPersistent: boolean = this.switchRpcSettingsFormGroup.get('requestPersistent').value; + if (retrieveValueMethod === 'none') { + this.switchRpcSettingsFormGroup.get('valueKey').disable({emitEvent}); + this.switchRpcSettingsFormGroup.get('getValueMethod').disable({emitEvent}); + this.switchRpcSettingsFormGroup.get('parseValueFunction').disable({emitEvent}); + } else if (retrieveValueMethod === 'rpc') { + this.switchRpcSettingsFormGroup.get('valueKey').disable({emitEvent}); + this.switchRpcSettingsFormGroup.get('getValueMethod').enable({emitEvent}); + this.switchRpcSettingsFormGroup.get('parseValueFunction').enable({emitEvent}); + } else { + this.switchRpcSettingsFormGroup.get('valueKey').enable({emitEvent}); + this.switchRpcSettingsFormGroup.get('getValueMethod').disable({emitEvent}); + this.switchRpcSettingsFormGroup.get('parseValueFunction').enable({emitEvent}); + } + if (requestPersistent) { + this.switchRpcSettingsFormGroup.get('persistentPollingInterval').enable({emitEvent}); + } else { + this.switchRpcSettingsFormGroup.get('persistentPollingInterval').disable({emitEvent}); + } + this.switchRpcSettingsFormGroup.get('valueKey').updateValueAndValidity({emitEvent: false}); + this.switchRpcSettingsFormGroup.get('getValueMethod').updateValueAndValidity({emitEvent: false}); + this.switchRpcSettingsFormGroup.get('parseValueFunction').updateValueAndValidity({emitEvent: false}); + this.switchRpcSettingsFormGroup.get('persistentPollingInterval').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.html new file mode 100644 index 0000000000..ef9ee32174 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.html @@ -0,0 +1,51 @@ + + +
+
+ widgets.rpc.common-settings + + widgets.rpc.widget-title + + + + widgets.rpc.button-label + + + + widgets.rpc.device-attribute-scope + + + {{ 'widgets.rpc.server-attribute' | translate }} + + + {{ 'widgets.rpc.shared-attribute' | translate }} + + + + + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..6689112bf7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component.ts @@ -0,0 +1,68 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { ContentType } from '@shared/models/constants'; + +@Component({ + selector: 'tb-update-device-attribute-widget-settings', + templateUrl: './update-device-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateDeviceAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateDeviceAttributeWidgetSettingsForm: FormGroup; + + contentTypes = ContentType; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateDeviceAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + title: '', + buttonText: 'Update device attribute', + entityAttributeType: 'SERVER_SCOPE', + entityParameters: '{}', + styleButton: { + isRaised: true, + isPrimary: false, + bgColor: null, + textColor: null + } + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateDeviceAttributeWidgetSettingsForm = this.fb.group({ + title: [settings.title, []], + buttonText: [settings.buttonText, []], + entityAttributeType: [settings.entityAttributeType, []], + entityParameters: [settings.entityParameters, []], + styleButton: [settings.styleButton, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.html new file mode 100644 index 0000000000..519ef6bafa --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.html @@ -0,0 +1,146 @@ + +
+
+ widgets.date-range-navigator.date-range-picker-settings + + + + + {{ 'widgets.date-range-navigator.hide-date-range-picker' | translate }} + + + + widget-config.advanced-settings + + + +
+ + {{ 'widgets.date-range-navigator.picker-one-panel' | translate }} + + + {{ 'widgets.date-range-navigator.picker-auto-confirm' | translate }} + + + {{ 'widgets.date-range-navigator.picker-show-template' | translate }} + + + widgets.date-range-navigator.first-day-of-week + + +
+
+
+
+
+ widgets.date-range-navigator.interval-settings + + + + + {{ 'widgets.date-range-navigator.hide-interval' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.date-range-navigator.initial-interval + + + {{ 'widgets.date-range-navigator.interval-hour' | translate }} + + + {{ 'widgets.date-range-navigator.interval-day' | translate }} + + + {{ 'widgets.date-range-navigator.interval-week' | translate }} + + + {{ 'widgets.date-range-navigator.interval-two-weeks' | translate }} + + + {{ 'widgets.date-range-navigator.interval-month' | translate }} + + + {{ 'widgets.date-range-navigator.interval-three-months' | translate }} + + + {{ 'widgets.date-range-navigator.interval-six-months' | translate }} + + + + + +
+
+ widgets.date-range-navigator.step-settings + + + + + {{ 'widgets.date-range-navigator.hide-step-size' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.date-range-navigator.initial-step-size + + + {{ 'widgets.date-range-navigator.interval-hour' | translate }} + + + {{ 'widgets.date-range-navigator.interval-day' | translate }} + + + {{ 'widgets.date-range-navigator.interval-week' | translate }} + + + {{ 'widgets.date-range-navigator.interval-two-weeks' | translate }} + + + {{ 'widgets.date-range-navigator.interval-month' | translate }} + + + {{ 'widgets.date-range-navigator.interval-three-months' | translate }} + + + {{ 'widgets.date-range-navigator.interval-six-months' | translate }} + + + + + +
+ + {{ 'widgets.date-range-navigator.hide-labels' | translate }} + + + {{ 'widgets.date-range-navigator.use-session-storage' | translate }} + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.ts new file mode 100644 index 0000000000..b218fd7004 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component.ts @@ -0,0 +1,120 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-date-range-navigator-widget-settings', + templateUrl: './date-range-navigator-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class DateRangeNavigatorWidgetSettingsComponent extends WidgetSettingsComponent { + + dateRangeNavigatorWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.dateRangeNavigatorWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + hidePicker: false, + onePanel: false, + autoConfirm: false, + showTemplate: false, + firstDayOfWeek: 1, + hideInterval: false, + initialInterval: 'week', + hideStepSize: false, + stepSize: 'day', + hideLabels: false, + useSessionStorage: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.dateRangeNavigatorWidgetSettingsForm = this.fb.group({ + + // Date range picker settings + + hidePicker: [settings.hidePicker, []], + onePanel: [settings.onePanel, []], + autoConfirm: [settings.autoConfirm, []], + showTemplate: [settings.showTemplate, []], + firstDayOfWeek: [settings.firstDayOfWeek, [Validators.min(1), Validators.max(7)]], + + // Interval settings + + hideInterval: [settings.hideInterval, []], + initialInterval: [settings.initialInterval, []], + + // Step settings + + hideStepSize: [settings.hideStepSize, []], + stepSize: [settings.stepSize, []], + + hideLabels: [settings.hideLabels, []], + useSessionStorage: [settings.useSessionStorage, []], + }); + } + + protected validatorTriggers(): string[] { + return ['hidePicker', 'hideInterval', 'hideStepSize']; + } + + protected updateValidators(emitEvent: boolean) { + const hidePicker: boolean = this.dateRangeNavigatorWidgetSettingsForm.get('hidePicker').value; + const hideInterval: boolean = this.dateRangeNavigatorWidgetSettingsForm.get('hideInterval').value; + const hideStepSize: boolean = this.dateRangeNavigatorWidgetSettingsForm.get('hideStepSize').value; + if (hidePicker) { + this.dateRangeNavigatorWidgetSettingsForm.get('onePanel').disable(); + this.dateRangeNavigatorWidgetSettingsForm.get('autoConfirm').disable(); + this.dateRangeNavigatorWidgetSettingsForm.get('showTemplate').disable(); + this.dateRangeNavigatorWidgetSettingsForm.get('firstDayOfWeek').disable(); + } else { + this.dateRangeNavigatorWidgetSettingsForm.get('onePanel').enable(); + this.dateRangeNavigatorWidgetSettingsForm.get('autoConfirm').enable(); + this.dateRangeNavigatorWidgetSettingsForm.get('showTemplate').enable(); + this.dateRangeNavigatorWidgetSettingsForm.get('firstDayOfWeek').enable(); + } + if (hideInterval) { + this.dateRangeNavigatorWidgetSettingsForm.get('initialInterval').disable(); + } else { + this.dateRangeNavigatorWidgetSettingsForm.get('initialInterval').enable(); + } + if (hideStepSize) { + this.dateRangeNavigatorWidgetSettingsForm.get('stepSize').disable(); + } else { + this.dateRangeNavigatorWidgetSettingsForm.get('stepSize').enable(); + } + this.dateRangeNavigatorWidgetSettingsForm.get('onePanel').updateValueAndValidity({emitEvent}); + this.dateRangeNavigatorWidgetSettingsForm.get('autoConfirm').updateValueAndValidity({emitEvent}); + this.dateRangeNavigatorWidgetSettingsForm.get('showTemplate').updateValueAndValidity({emitEvent}); + this.dateRangeNavigatorWidgetSettingsForm.get('firstDayOfWeek').updateValueAndValidity({emitEvent}); + this.dateRangeNavigatorWidgetSettingsForm.get('initialInterval').updateValueAndValidity({emitEvent}); + this.dateRangeNavigatorWidgetSettingsForm.get('stepSize').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.html new file mode 100644 index 0000000000..dc1064fbf5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.html @@ -0,0 +1,26 @@ + +
+ + widgets.gateway.gateway-title + + + + {{ 'widgets.gateway.read-only' | translate }} + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.ts new file mode 100644 index 0000000000..e6c413fc2c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component.ts @@ -0,0 +1,54 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-gateway-config-single-device-widget-settings', + templateUrl: './gateway-config-single-device-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class GatewayConfigSingleDeviceWidgetSettingsComponent extends WidgetSettingsComponent { + + gatewayConfigSingleDeviceWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.gatewayConfigSingleDeviceWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + gatewayTitle: 'Gateway configuration (Single device)', + readOnly: false + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.gatewayConfigSingleDeviceWidgetSettingsForm = this.fb.group({ + gatewayTitle: [settings.gatewayTitle, []], + readOnly: [settings.readOnly, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.html new file mode 100644 index 0000000000..cc46041c01 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.html @@ -0,0 +1,45 @@ + +
+
+ widgets.gateway.general-settings + + widgets.gateway.widget-title + + + + widgets.gateway.default-archive-file-name + + + + widgets.gateway.device-type-for-new-gateway + + +
+
+ widgets.gateway.messages-settings + + widgets.gateway.save-config-success-message + + + + widgets.gateway.device-name-exists-message + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.ts new file mode 100644 index 0000000000..911b6b2c72 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component.ts @@ -0,0 +1,60 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-gateway-config-widget-settings', + templateUrl: './gateway-config-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class GatewayConfigWidgetSettingsComponent extends WidgetSettingsComponent { + + gatewayConfigWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.gatewayConfigWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: 'Gateway Configuration', + archiveFileName: 'gatewayConfiguration', + gatewayType: 'Gateway', + successfulSave: '', + gatewayNameExists: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.gatewayConfigWidgetSettingsForm = this.fb.group({ + widgetTitle: [settings.widgetTitle, []], + archiveFileName: [settings.archiveFileName, []], + gatewayType: [settings.gatewayType, []], + successfulSave: [settings.successfulSave, []], + gatewayNameExists: [settings.gatewayNameExists, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.html new file mode 100644 index 0000000000..3d3e6e81a4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.html @@ -0,0 +1,41 @@ + +
+ + widgets.gateway.events-title + + + + widgets.gateway.events-filter + + + {{eventFilter}} + cancel + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.ts new file mode 100644 index 0000000000..4241c1d7cd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component.ts @@ -0,0 +1,82 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { MatChipInputEvent } from '@angular/material/chips'; +import { COMMA, ENTER, SEMICOLON } from '@angular/cdk/keycodes'; + +@Component({ + selector: 'tb-gateway-events-widget-settings', + templateUrl: './gateway-events-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class GatewayEventsWidgetSettingsComponent extends WidgetSettingsComponent { + + separatorKeysCodes = [ENTER, COMMA, SEMICOLON]; + + gatewayEventsWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.gatewayEventsWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + eventsTitle: 'Gateway events form title', + eventsReg: [] + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.gatewayEventsWidgetSettingsForm = this.fb.group({ + eventsTitle: [settings.eventsTitle, []], + eventsReg: [settings.eventsReg, []] + }); + } + + removeEventFilter(eventFilter: string) { + const eventsFilter: string[] = this.gatewayEventsWidgetSettingsForm.get('eventsReg').value; + const index = eventsFilter.indexOf(eventFilter); + if (index > -1) { + eventsFilter.splice(index, 1); + this.gatewayEventsWidgetSettingsForm.get('eventsReg').setValue(eventsFilter); + this.gatewayEventsWidgetSettingsForm.get('eventsReg').markAsDirty(); + } + } + + addEventFilterFromInput(event: MatChipInputEvent) { + const value = event.value; + if ((value || '').trim()) { + const eventsFilter: string[] = this.gatewayEventsWidgetSettingsForm.get('eventsReg').value; + const index = eventsFilter.indexOf(value); + if (index === -1) { + eventsFilter.push(value); + this.gatewayEventsWidgetSettingsForm.get('eventsReg').setValue(eventsFilter); + this.gatewayEventsWidgetSettingsForm.get('eventsReg').markAsDirty(); + } + event.chipInput.clear(); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.html new file mode 100644 index 0000000000..3311c4d4e7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.html @@ -0,0 +1,178 @@ + +
+
+ widgets.gauge.ticks-settings + + widgets.gauge.major-ticks-names + + + {{tickName}} + cancel + + + + + + +
+ + widgets.gauge.minor-ticks-count + + + + +
+ + {{ 'widgets.gauge.show-stroke-ticks' | translate }} + +
+ widgets.gauge.major-ticks-font + +
+
+
+ widgets.gauge.plate-settings + + + + {{ 'widgets.gauge.show-plate-border' | translate }} + +
+ + + + widgets.gauge.border-width + + +
+
+
+ widgets.gauge.needle-settings + + widgets.gauge.needle-circle-size + + +
+ + + + +
+
+
+ widgets.gauge.animation-settings + + + + + {{ 'widgets.gauge.enable-animation' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.animation-duration + + + + widgets.gauge.animation-rule + + + {{ 'widgets.gauge.animation-linear' | translate }} + + + {{ 'widgets.gauge.animation-quad' | translate }} + + + {{ 'widgets.gauge.animation-quint' | translate }} + + + {{ 'widgets.gauge.animation-cycle' | translate }} + + + {{ 'widgets.gauge.animation-bounce' | translate }} + + + {{ 'widgets.gauge.animation-elastic' | translate }} + + + {{ 'widgets.gauge.animation-dequad' | translate }} + + + {{ 'widgets.gauge.animation-dequint' | translate }} + + + {{ 'widgets.gauge.animation-decycle' | translate }} + + + {{ 'widgets.gauge.animation-debounce' | translate }} + + + {{ 'widgets.gauge.animation-delastic' | translate }} + + + + + widgets.gauge.animation-target + + + {{ 'widgets.gauge.animation-target-needle' | translate }} + + + {{ 'widgets.gauge.animation-target-plate' | translate }} + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.ts new file mode 100644 index 0000000000..4f110e2e8e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component.ts @@ -0,0 +1,171 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Component } from '@angular/core'; +import { MatChipInputEvent } from '@angular/material/chips'; +import { COMMA, ENTER, SEMICOLON } from '@angular/cdk/keycodes'; +import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; + +@Component({ + selector: 'tb-analogue-compass-widget-settings', + templateUrl: './analogue-compass-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class AnalogueCompassWidgetSettingsComponent extends WidgetSettingsComponent { + + readonly separatorKeysCodes: number[] = [ENTER, COMMA, SEMICOLON]; + + analogueCompassWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + protected fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.analogueCompassWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + majorTicks: [], + minorTicks: 22, + showStrokeTicks: false, + needleCircleSize: 10, + showBorder: true, + borderOuterWidth: 10, + colorPlate: '#222', + colorMajorTicks: '#f5f5f5', + colorMinorTicks: '#ddd', + colorNeedle: '#f08080', + colorNeedleCircle: '#e8e8e8', + colorBorder: '#ccc', + majorTickFont: { + family: 'Roboto', + size: 20, + style: 'normal', + weight: '500', + color: '#ccc' + }, + animation: true, + animationDuration: 500, + animationRule: 'cycle', + animationTarget: 'needle' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.analogueCompassWidgetSettingsForm = this.fb.group({ + + // Ticks settings + majorTicks: [settings.majorTicks, []], + colorMajorTicks: [settings.colorMajorTicks, []], + minorTicks: [settings.minorTicks, [Validators.min(0)]], + colorMinorTicks: [settings.colorMinorTicks, []], + showStrokeTicks: [settings.showStrokeTicks, []], + majorTickFont: [settings.majorTickFont, []], + + // Plate settings + colorPlate: [settings.colorPlate, []], + showBorder: [settings.showBorder, []], + colorBorder: [settings.colorBorder, []], + borderOuterWidth: [settings.borderOuterWidth, [Validators.min(0)]], + + // Needle settings + needleCircleSize: [settings.needleCircleSize, [Validators.min(0)]], + colorNeedle: [settings.colorNeedle, []], + colorNeedleCircle: [settings.colorNeedleCircle, []], + + // Animation settings + animation: [settings.animation, []], + animationDuration: [settings.animationDuration, [Validators.min(0)]], + animationRule: [settings.animationRule, []], + animationTarget: [settings.animationTarget, []] + }); + } + + protected validatorTriggers(): string[] { + return ['showBorder', 'animation']; + } + + protected updateValidators(emitEvent: boolean) { + const showBorder: boolean = this.analogueCompassWidgetSettingsForm.get('showBorder').value; + const animation: boolean = this.analogueCompassWidgetSettingsForm.get('animation').value; + if (showBorder) { + this.analogueCompassWidgetSettingsForm.get('colorBorder').enable(); + this.analogueCompassWidgetSettingsForm.get('borderOuterWidth').enable(); + } else { + this.analogueCompassWidgetSettingsForm.get('colorBorder').disable(); + this.analogueCompassWidgetSettingsForm.get('borderOuterWidth').disable(); + } + if (animation) { + this.analogueCompassWidgetSettingsForm.get('animationDuration').enable(); + this.analogueCompassWidgetSettingsForm.get('animationRule').enable(); + this.analogueCompassWidgetSettingsForm.get('animationTarget').enable(); + } else { + this.analogueCompassWidgetSettingsForm.get('animationDuration').disable(); + this.analogueCompassWidgetSettingsForm.get('animationRule').disable(); + this.analogueCompassWidgetSettingsForm.get('animationTarget').disable(); + } + this.analogueCompassWidgetSettingsForm.get('colorBorder').updateValueAndValidity({emitEvent}); + this.analogueCompassWidgetSettingsForm.get('borderOuterWidth').updateValueAndValidity({emitEvent}); + this.analogueCompassWidgetSettingsForm.get('animationDuration').updateValueAndValidity({emitEvent}); + this.analogueCompassWidgetSettingsForm.get('animationRule').updateValueAndValidity({emitEvent}); + this.analogueCompassWidgetSettingsForm.get('animationTarget').updateValueAndValidity({emitEvent}); + } + + majorTicksNamesList(): string[] { + return this.analogueCompassWidgetSettingsForm.get('majorTicks').value; + } + + removeMajorTickName(tickName: string): void { + const tickNames: string[] = this.analogueCompassWidgetSettingsForm.get('majorTicks').value; + const index = tickNames.indexOf(tickName); + if (index >= 0) { + tickNames.splice(index, 1); + this.analogueCompassWidgetSettingsForm.get('majorTicks').setValue(tickNames); + this.analogueCompassWidgetSettingsForm.get('majorTicks').markAsDirty(); + } + } + + addMajorTickName(event: MatChipInputEvent): void { + const input = event.input; + const value = event.value; + + const tickNames: string[] = this.analogueCompassWidgetSettingsForm.get('majorTicks').value; + + if ((value || '').trim()) { + tickNames.push(value.trim()); + this.analogueCompassWidgetSettingsForm.get('majorTicks').setValue(tickNames); + this.analogueCompassWidgetSettingsForm.get('majorTicks').markAsDirty(); + } + + if (input) { + input.value = ''; + } + } + + majorTickNameDrop(event: CdkDragDrop): void { + const tickNames: string[] = this.analogueCompassWidgetSettingsForm.get('majorTicks').value; + moveItemInArray(tickNames, event.previousIndex, event.currentIndex); + this.analogueCompassWidgetSettingsForm.get('majorTicks').setValue(tickNames); + this.analogueCompassWidgetSettingsForm.get('majorTicks').markAsDirty(); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.html new file mode 100644 index 0000000000..fcce29b1b4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.html @@ -0,0 +1,353 @@ + +
+ + + + + + + + + + +
+ widgets.gauge.ticks-settings +
+ + widgets.gauge.min-value + + + + widgets.gauge.max-value + + +
+
+ + widgets.gauge.major-ticks-count + + + + +
+
+ + widgets.gauge.minor-ticks-count + + + + +
+
+ widgets.gauge.tick-numbers-font + +
+
+
+ widgets.gauge.unit-title-settings + + + + + {{ 'widgets.gauge.show-unit-title' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.unit-title + + +
+ widgets.gauge.title-font + +
+
+
+
+
+
+ widgets.gauge.units-settings +
+ widgets.gauge.units-font + +
+
+
+ widgets.gauge.value-box-settings + + + + + {{ 'widgets.gauge.show-value-box' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.value-int + + +
+ widgets.gauge.value-font + +
+
+ + + + +
+
+ + + + +
+
+
+
+
+
+ widgets.gauge.plate-settings + + + + {{ 'widgets.gauge.show-plate-border' | translate }} + +
+
+ widgets.gauge.needle-settings +
+ + + + +
+
+ + + + +
+
+
+ widgets.gauge.highlights-settings + + widgets.gauge.highlights-width + + +
+ widgets.gauge.highlights +
+
+
+ + +
+
+
+ widgets.gauge.no-highlights +
+
+ +
+
+
+
+
+ widgets.gauge.animation-settings + + + + + {{ 'widgets.gauge.enable-animation' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.animation-duration + + + + widgets.gauge.animation-rule + + + {{ 'widgets.gauge.animation-linear' | translate }} + + + {{ 'widgets.gauge.animation-quad' | translate }} + + + {{ 'widgets.gauge.animation-quint' | translate }} + + + {{ 'widgets.gauge.animation-cycle' | translate }} + + + {{ 'widgets.gauge.animation-bounce' | translate }} + + + {{ 'widgets.gauge.animation-elastic' | translate }} + + + {{ 'widgets.gauge.animation-dequad' | translate }} + + + {{ 'widgets.gauge.animation-dequint' | translate }} + + + {{ 'widgets.gauge.animation-decycle' | translate }} + + + {{ 'widgets.gauge.animation-debounce' | translate }} + + + {{ 'widgets.gauge.animation-delastic' | translate }} + + + +
+
+
+
+
+ + +
+ widgets.gauge.radial-gauge-settings +
+ + widgets.gauge.start-ticks-angle + + + + widgets.gauge.ticks-angle + + +
+ + widgets.gauge.needle-circle-size + + +
+
+ + +
+ widgets.gauge.linear-gauge-settings +
+ + widgets.gauge.bar-stroke-width + + + + +
+
+ + + + +
+
+ + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.ts new file mode 100644 index 0000000000..7262dea990 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component.ts @@ -0,0 +1,257 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { GaugeHighlight } from '@home/components/widget/lib/settings/gauge/gauge-highlight.component'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; + +export class AnalogueGaugeWidgetSettingsComponent extends WidgetSettingsComponent { + + analogueGaugeWidgetSettingsForm: FormGroup; + + ctx = { + settingsForm: null + }; + + constructor(protected store: Store, + protected fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.analogueGaugeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + startAngle: 45, + ticksAngle: 270, + needleCircleSize: 10, + minValue: 0, + maxValue: 100, + showUnitTitle: true, + unitTitle: null, + majorTicksCount: null, + minorTicks: 2, + valueBox: true, + valueInt: 3, + defaultColor: null, + colorPlate: '#fff', + colorMajorTicks: '#444', + colorMinorTicks: '#666', + colorNeedle: null, + colorNeedleEnd: null, + colorNeedleShadowUp: 'rgba(2,255,255,0.2)', + colorNeedleShadowDown: 'rgba(188,143,143,0.45)', + colorValueBoxRect: '#888', + colorValueBoxRectEnd: '#666', + colorValueBoxBackground: '#babab2', + colorValueBoxShadow: 'rgba(0,0,0,1)', + highlights: [], + highlightsWidth: 15, + showBorder: true, + numbersFont: { + family: 'Roboto', + size: 18, + style: 'normal', + weight: '500', + color: null + }, + titleFont: { + family: 'Roboto', + size: 24, + style: 'normal', + weight: '500', + color: '#888' + }, + unitsFont: { + family: 'Roboto', + size: 22, + style: 'normal', + weight: '500', + color: '#888' + }, + valueFont: { + family: 'Roboto', + size: 40, + style: 'normal', + weight: '500', + color: '#444', + shadowColor: 'rgba(0,0,0,0.3)' + }, + animation: true, + animationDuration: 500, + animationRule: 'cycle' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.analogueGaugeWidgetSettingsForm = this.fb.group({ + + // Radial gauge settings + startAngle: [settings.startAngle, [Validators.min(0), Validators.max(360)]], + ticksAngle: [settings.ticksAngle, [Validators.min(0), Validators.max(360)]], + needleCircleSize: [settings.needleCircleSize, [Validators.min(0)]], + + defaultColor: [settings.defaultColor, []], + + // Ticks settings + minValue: [settings.minValue, []], + maxValue: [settings.maxValue, []], + majorTicksCount: [settings.majorTicksCount, [Validators.min(0)]], + colorMajorTicks: [settings.colorMajorTicks, []], + minorTicks: [settings.majorTicksCount, [Validators.min(0)]], + colorMinorTicks: [settings.colorMinorTicks, []], + numbersFont: [settings.numbersFont, []], + + // Unit title settings + showUnitTitle: [settings.showUnitTitle, []], + unitTitle: [settings.unitTitle, []], + titleFont: [settings.titleFont, []], + + // Units settings + unitsFont: [settings.unitsFont, []], + + // Value box settings + valueBox: [settings.valueBox, []], + valueInt: [settings.valueInt, [Validators.min(0)]], + valueFont: [settings.valueFont, []], + colorValueBoxRect: [settings.colorValueBoxRect, []], + colorValueBoxRectEnd: [settings.colorValueBoxRectEnd, []], + colorValueBoxBackground: [settings.colorValueBoxBackground, []], + colorValueBoxShadow: [settings.colorValueBoxShadow, []], + + // Plate settings + showBorder: [settings.showBorder, []], + colorPlate: [settings.colorPlate, []], + + // Needle settings + colorNeedle: [settings.colorNeedle, []], + colorNeedleEnd: [settings.colorNeedleEnd, []], + colorNeedleShadowUp: [settings.colorNeedleShadowUp, []], + colorNeedleShadowDown: [settings.colorNeedleShadowDown, []], + + // Highlights settings + highlightsWidth: [settings.highlightsWidth, [Validators.min(0)]], + highlights: this.prepareHighlightsFormArray(settings.highlights), + + // Animation settings + animation: [settings.animation, []], + animationDuration: [settings.animationDuration, [Validators.min(0)]], + animationRule: [settings.animationRule, []], + }); + this.ctx.settingsForm = this.analogueGaugeWidgetSettingsForm; + } + + protected validatorTriggers(): string[] { + return ['showUnitTitle', 'valueBox', 'animation']; + } + + protected updateValidators(emitEvent: boolean) { + const showUnitTitle: boolean = this.analogueGaugeWidgetSettingsForm.get('showUnitTitle').value; + const valueBox: boolean = this.analogueGaugeWidgetSettingsForm.get('valueBox').value; + const animation: boolean = this.analogueGaugeWidgetSettingsForm.get('animation').value; + if (showUnitTitle) { + this.analogueGaugeWidgetSettingsForm.get('unitTitle').enable(); + this.analogueGaugeWidgetSettingsForm.get('titleFont').enable(); + } else { + this.analogueGaugeWidgetSettingsForm.get('unitTitle').disable(); + this.analogueGaugeWidgetSettingsForm.get('titleFont').disable(); + } + if (valueBox) { + this.analogueGaugeWidgetSettingsForm.get('valueInt').enable(); + this.analogueGaugeWidgetSettingsForm.get('valueFont').enable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRect').enable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRectEnd').enable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxBackground').enable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxShadow').enable(); + } else { + this.analogueGaugeWidgetSettingsForm.get('valueInt').disable(); + this.analogueGaugeWidgetSettingsForm.get('valueFont').disable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRect').disable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRectEnd').disable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxBackground').disable(); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxShadow').disable(); + } + if (animation) { + this.analogueGaugeWidgetSettingsForm.get('animationDuration').enable(); + this.analogueGaugeWidgetSettingsForm.get('animationRule').enable(); + } else { + this.analogueGaugeWidgetSettingsForm.get('animationDuration').disable(); + this.analogueGaugeWidgetSettingsForm.get('animationRule').disable(); + } + this.analogueGaugeWidgetSettingsForm.get('unitTitle').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('titleFont').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('valueInt').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('valueFont').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRect').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxRectEnd').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxBackground').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('colorValueBoxShadow').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('animationDuration').updateValueAndValidity({emitEvent}); + this.analogueGaugeWidgetSettingsForm.get('animationRule').updateValueAndValidity({emitEvent}); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('highlights', this.prepareHighlightsFormArray(settings.highlights), {emitEvent: false}); + } + + private prepareHighlightsFormArray(highlights: GaugeHighlight[] | undefined): FormArray { + const highlightsControls: Array = []; + if (highlights) { + highlights.forEach((highlight) => { + highlightsControls.push(this.fb.control(highlight, [Validators.required])); + }); + } + return this.fb.array(highlightsControls); + } + + highlightsFormArray(): FormArray { + return this.analogueGaugeWidgetSettingsForm.get('highlights') as FormArray; + } + + public trackByHighlightControl(index: number, highlightControl: AbstractControl): any { + return highlightControl; + } + + public removeHighlight(index: number) { + (this.analogueGaugeWidgetSettingsForm.get('highlights') as FormArray).removeAt(index); + } + + public addHighlight() { + const highlight: GaugeHighlight = { + from: null, + to: null, + color: null + }; + const highlightsArray = this.analogueGaugeWidgetSettingsForm.get('highlights') as FormArray; + const highlightControl = this.fb.control(highlight, [Validators.required]); + (highlightControl as any).new = true; + highlightsArray.push(highlightControl); + this.analogueGaugeWidgetSettingsForm.updateValueAndValidity(); + } + + highlightDrop(event: CdkDragDrop) { + const highlightsArray = this.analogueGaugeWidgetSettingsForm.get('highlights') as FormArray; + const highlight = highlightsArray.at(event.previousIndex); + highlightsArray.removeAt(event.previousIndex); + highlightsArray.insert(event.currentIndex, highlight); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-linear-gauge-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-linear-gauge-widget-settings.component.ts new file mode 100644 index 0000000000..d5a424cb6d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-linear-gauge-widget-settings.component.ts @@ -0,0 +1,66 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings } from '@shared/models/widget.models'; +import { FormBuilder, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { + AnalogueGaugeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component'; + +@Component({ + selector: 'tb-analogue-linear-gauge-widget-settings', + templateUrl: './analogue-gauge-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class AnalogueLinearGaugeWidgetSettingsComponent extends AnalogueGaugeWidgetSettingsComponent { + + gaugeType = 'linear'; + + constructor(protected store: Store, + protected fb: FormBuilder) { + super(store, fb); + } + + protected defaultSettings(): WidgetSettings { + const settings = super.defaultSettings(); + settings.barStrokeWidth = 2.5; + settings.colorBarStroke = null; + settings.colorBar = '#fff'; + settings.colorBarEnd = '#ddd'; + settings.colorBarProgress = null; + settings.colorBarProgressEnd = null; + return settings; + } + + protected onSettingsSet(settings: WidgetSettings) { + super.onSettingsSet(settings); + this.analogueGaugeWidgetSettingsForm.addControl('barStrokeWidth', + this.fb.control(settings.barStrokeWidth, [Validators.min(0)])); + this.analogueGaugeWidgetSettingsForm.addControl('colorBarStroke', + this.fb.control(settings.colorBarStroke, [])); + this.analogueGaugeWidgetSettingsForm.addControl('colorBar', + this.fb.control(settings.colorBar, [])); + this.analogueGaugeWidgetSettingsForm.addControl('colorBarEnd', + this.fb.control(settings.colorBarEnd, [])); + this.analogueGaugeWidgetSettingsForm.addControl('colorBarProgress', + this.fb.control(settings.colorBarProgress, [])); + this.analogueGaugeWidgetSettingsForm.addControl('colorBarProgressEnd', + this.fb.control(settings.colorBarProgressEnd, [])); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-radial-gauge-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-radial-gauge-widget-settings.component.ts new file mode 100644 index 0000000000..0641fb5ab3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/analogue-radial-gauge-widget-settings.component.ts @@ -0,0 +1,57 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings } from '@shared/models/widget.models'; +import { FormBuilder, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { + AnalogueGaugeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/analogue-gauge-widget-settings.component'; + +@Component({ + selector: 'tb-analogue-radial-gauge-widget-settings', + templateUrl: './analogue-gauge-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class AnalogueRadialGaugeWidgetSettingsComponent extends AnalogueGaugeWidgetSettingsComponent { + + gaugeType = 'radial'; + + constructor(protected store: Store, + protected fb: FormBuilder) { + super(store, fb); + } + + protected defaultSettings(): WidgetSettings { + const settings = super.defaultSettings(); + settings.startAngle = 45; + settings.ticksAngle = 270; + settings.needleCircleSize = 10; + return settings; + } + + protected onSettingsSet(settings: WidgetSettings) { + super.onSettingsSet(settings); + this.analogueGaugeWidgetSettingsForm.addControl('startAngle', + this.fb.control(settings.startAngle, [Validators.min(0), Validators.max(360)])); + this.analogueGaugeWidgetSettingsForm.addControl('ticksAngle', + this.fb.control(settings.ticksAngle, [Validators.min(0), Validators.max(360)])); + this.analogueGaugeWidgetSettingsForm.addControl('needleCircleSize', + this.fb.control(settings.needleCircleSize, [Validators.min(0)])); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.html new file mode 100644 index 0000000000..0a70e8b5d6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.html @@ -0,0 +1,382 @@ + +
+
+ widgets.gauge.common-settings +
+ + widgets.gauge.min-value + + + + widgets.gauge.max-value + + +
+ + widgets.gauge.gauge-type + + + {{ 'widgets.gauge.gauge-type-arc' | translate }} + + + {{ 'widgets.gauge.gauge-type-donut' | translate }} + + + {{ 'widgets.gauge.gauge-type-horizontal-bar' | translate }} + + + {{ 'widgets.gauge.gauge-type-vertical-bar' | translate }} + + + + + widgets.gauge.donut-start-angle + + + + +
+
+ widgets.gauge.bar-settings + + widgets.gauge.relative-bar-width + + + + widgets.gauge.neon-glow-brightness + + +
+ + widgets.gauge.stripes-thickness + + + + {{ 'widgets.gauge.rounded-line-cap' | translate }} + +
+
+ widgets.gauge.bar-color-settings + + + + {{ 'widgets.gauge.use-precise-level-color-values' | translate }} + +
+ widgets.gauge.bar-colors +
+
+
+
+ drag_handle +
+ + + +
+
+
+ widgets.gauge.no-bar-colors +
+
+ +
+
+
+
+ widgets.gauge.fixed-level-colors +
+
+
+ + +
+
+
+ widgets.gauge.no-bar-colors +
+
+ +
+
+
+
+
+
+ widgets.gauge.gauge-title-settings + + + + + {{ 'widgets.gauge.show-gauge-title' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.gauge-title + + +
+ widgets.gauge.gauge-title-font + +
+
+
+
+
+
+ widgets.gauge.unit-title-and-timestamp-settings +
+ + {{ 'widgets.gauge.show-unit-title' | translate }} + + + widgets.gauge.unit-title + + +
+
+ + {{ 'widgets.gauge.show-timestamp' | translate }} + + + widgets.gauge.timestamp-format + + +
+ + + + widget-config.advanced-settings + + + +
+ widgets.gauge.label-font + +
+
+
+
+
+ widgets.gauge.value-settings + + + + + {{ 'widgets.gauge.show-value' | translate }} + + + + widget-config.advanced-settings + + + +
+ widgets.gauge.value-font + +
+
+
+
+
+ widgets.gauge.min-max-settings + + + + + {{ 'widgets.gauge.show-min-max' | translate }} + + + + widget-config.advanced-settings + + + +
+ widgets.gauge.min-max-font + +
+
+
+
+
+ widgets.gauge.ticks-settings + + + + + {{ 'widgets.gauge.show-ticks' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.tick-width + + + + +
+ widgets.gauge.tick-values +
+
+
+ + + +
+
+
+ widgets.gauge.no-tick-values +
+
+ +
+
+
+
+
+
+
+
+ widgets.gauge.animation-settings + + + + + {{ 'widgets.gauge.enable-animation' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.gauge.animation-duration + + + + widgets.gauge.animation-rule + + + {{ 'widgets.gauge.animation-linear' | translate }} + + + {{ 'widgets.gauge.animation-quad' | translate }} + + + {{ 'widgets.gauge.animation-quint' | translate }} + + + {{ 'widgets.gauge.animation-cycle' | translate }} + + + {{ 'widgets.gauge.animation-bounce' | translate }} + + + {{ 'widgets.gauge.animation-elastic' | translate }} + + + {{ 'widgets.gauge.animation-dequad' | translate }} + + + {{ 'widgets.gauge.animation-dequint' | translate }} + + + {{ 'widgets.gauge.animation-decycle' | translate }} + + + {{ 'widgets.gauge.animation-debounce' | translate }} + + + {{ 'widgets.gauge.animation-delastic' | translate }} + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts new file mode 100644 index 0000000000..6b4cf54b15 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component.ts @@ -0,0 +1,388 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { Component } from '@angular/core'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { GaugeType } from '@home/components/widget/lib/canvas-digital-gauge'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; +import { + FixedColorLevel, + fixedColorLevelValidator +} from '@home/components/widget/lib/settings/gauge/fixed-color-level.component'; +import { ValueSourceProperty } from '@home/components/widget/lib/settings/common/value-source.component'; + +@Component({ + selector: 'tb-digital-gauge-widget-settings', + templateUrl: './digital-gauge-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class DigitalGaugeWidgetSettingsComponent extends WidgetSettingsComponent { + + digitalGaugeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + protected fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.digitalGaugeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + minValue: 0, + maxValue: 100, + gaugeType: 'arc', + donutStartAngle: 90, + neonGlowBrightness: 0, + dashThickness: 0, + roundedLineCap: false, + title: null, + showTitle: false, + unitTitle: null, + showUnitTitle: false, + showTimestamp: false, + timestampFormat: 'yyyy-MM-dd HH:mm:ss', + showValue: true, + showMinMax: true, + gaugeWidthScale: 0.75, + defaultColor: null, + gaugeColor: null, + useFixedLevelColor: false, + levelColors: [], + fixedLevelColors: [], + showTicks: false, + tickWidth: 4, + colorTicks: '#666', + ticksValue: [], + animation: true, + animationDuration: 500, + animationRule: 'linear', + titleFont: { + family: 'Roboto', + size: 12, + style: 'normal', + weight: '500', + color: null + }, + labelFont: { + family: 'Roboto', + size: 8, + style: 'normal', + weight: '500', + color: null + }, + valueFont: { + family: 'Roboto', + size: 18, + style: 'normal', + weight: '500', + color: null + }, + minMaxFont: { + family: 'Roboto', + size: 10, + style: 'normal', + weight: '500', + color: null + } + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.digitalGaugeWidgetSettingsForm = this.fb.group({ + + // Common gauge settings + minValue: [settings.minValue, []], + maxValue: [settings.maxValue, []], + gaugeType: [settings.gaugeType, []], + donutStartAngle: [settings.donutStartAngle, []], + defaultColor: [settings.defaultColor, []], + + // Gauge bar settings + gaugeWidthScale: [settings.gaugeWidthScale, [Validators.min(0)]], + neonGlowBrightness: [settings.neonGlowBrightness, [Validators.min(0), Validators.max(100)]], + dashThickness: [settings.dashThickness, [Validators.min(0)]], + roundedLineCap: [settings.roundedLineCap, []], + + // Gauge bar colors settings + gaugeColor: [settings.gaugeColor, []], + useFixedLevelColor: [settings.useFixedLevelColor, []], + levelColors: this.prepareLevelColorFormArray(settings.levelColors), + fixedLevelColors: this.prepareFixedLevelColorFormArray(settings.fixedLevelColors), + + // Title settings + showTitle: [settings.showTitle, []], + title: [settings.title, []], + titleFont: [settings.titleFont, []], + + // Unit title/timestamp settings + showUnitTitle: [settings.showUnitTitle, []], + unitTitle: [settings.unitTitle, []], + showTimestamp: [settings.showTimestamp, []], + timestampFormat: [settings.timestampFormat, []], + labelFont: [settings.labelFont, []], + + // Value settings + showValue: [settings.showValue, []], + valueFont: [settings.valueFont, []], + + // Min/max labels settings + showMinMax: [settings.showMinMax, []], + minMaxFont: [settings.minMaxFont, []], + + // Ticks settings + showTicks: [settings.showTicks, []], + tickWidth: [settings.tickWidth, [Validators.min(0)]], + colorTicks: [settings.colorTicks, []], + ticksValue: this.prepareTicksValueFormArray(settings.ticksValue), + + // Animation settings + animation: [settings.animation, []], + animationDuration: [settings.animationDuration, [Validators.min(0)]], + animationRule: [settings.animationRule, []] + + }); + } + + protected validatorTriggers(): string[] { + return ['gaugeType', 'showTitle', 'showUnitTitle', 'showValue', 'showMinMax', 'showTimestamp', 'useFixedLevelColor', 'showTicks', 'animation']; + } + + protected updateValidators(emitEvent: boolean) { + const gaugeType: GaugeType = this.digitalGaugeWidgetSettingsForm.get('gaugeType').value; + const showTitle: boolean = this.digitalGaugeWidgetSettingsForm.get('showTitle').value; + const showUnitTitle: boolean = this.digitalGaugeWidgetSettingsForm.get('showUnitTitle').value; + const showValue: boolean = this.digitalGaugeWidgetSettingsForm.get('showValue').value; + const showMinMax: boolean = this.digitalGaugeWidgetSettingsForm.get('showMinMax').value; + const showTimestamp: boolean = this.digitalGaugeWidgetSettingsForm.get('showTimestamp').value; + const useFixedLevelColor: boolean = this.digitalGaugeWidgetSettingsForm.get('useFixedLevelColor').value; + const showTicks: boolean = this.digitalGaugeWidgetSettingsForm.get('showTicks').value; + const animation: boolean = this.digitalGaugeWidgetSettingsForm.get('animation').value; + + if (gaugeType === 'donut') { + this.digitalGaugeWidgetSettingsForm.get('donutStartAngle').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('donutStartAngle').disable(); + } + if (showTitle) { + this.digitalGaugeWidgetSettingsForm.get('title').enable(); + this.digitalGaugeWidgetSettingsForm.get('titleFont').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('title').disable(); + this.digitalGaugeWidgetSettingsForm.get('titleFont').disable(); + } + if (showUnitTitle) { + this.digitalGaugeWidgetSettingsForm.get('unitTitle').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('unitTitle').disable(); + } + if (showTimestamp) { + this.digitalGaugeWidgetSettingsForm.get('timestampFormat').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('timestampFormat').disable(); + } + if (showUnitTitle || showTimestamp) { + this.digitalGaugeWidgetSettingsForm.get('labelFont').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('labelFont').disable(); + } + if (showValue) { + this.digitalGaugeWidgetSettingsForm.get('valueFont').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('valueFont').disable(); + } + if (showMinMax) { + this.digitalGaugeWidgetSettingsForm.get('minMaxFont').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('minMaxFont').disable(); + } + if (useFixedLevelColor) { + this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors').enable(); + this.digitalGaugeWidgetSettingsForm.get('levelColors').disable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors').disable(); + this.digitalGaugeWidgetSettingsForm.get('levelColors').enable(); + } + if (showTicks) { + this.digitalGaugeWidgetSettingsForm.get('tickWidth').enable(); + this.digitalGaugeWidgetSettingsForm.get('colorTicks').enable(); + this.digitalGaugeWidgetSettingsForm.get('ticksValue').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('tickWidth').disable(); + this.digitalGaugeWidgetSettingsForm.get('colorTicks').disable(); + this.digitalGaugeWidgetSettingsForm.get('ticksValue').disable(); + } + if (animation) { + this.digitalGaugeWidgetSettingsForm.get('animationDuration').enable(); + this.digitalGaugeWidgetSettingsForm.get('animationRule').enable(); + } else { + this.digitalGaugeWidgetSettingsForm.get('animationDuration').disable(); + this.digitalGaugeWidgetSettingsForm.get('animationRule').disable(); + } + this.digitalGaugeWidgetSettingsForm.get('donutStartAngle').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('title').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('titleFont').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('unitTitle').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('timestampFormat').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('labelFont').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('valueFont').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('minMaxFont').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('levelColors').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('tickWidth').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('colorTicks').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('ticksValue').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('animationDuration').updateValueAndValidity({emitEvent}); + this.digitalGaugeWidgetSettingsForm.get('animationRule').updateValueAndValidity({emitEvent}); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('levelColors', this.prepareLevelColorFormArray(settings.levelColors), {emitEvent: false}); + settingsForm.setControl('fixedLevelColors', this.prepareFixedLevelColorFormArray(settings.fixedLevelColors), {emitEvent: false}); + settingsForm.setControl('ticksValue', this.prepareTicksValueFormArray(settings.ticksValue), {emitEvent: false}); + } + + private prepareLevelColorFormArray(levelColors: string[] | undefined): FormArray { + const levelColorsControls: Array = []; + if (levelColors) { + levelColors.forEach((levelColor) => { + levelColorsControls.push(this.fb.control(levelColor, [Validators.required])); + }); + } + return this.fb.array(levelColorsControls); + } + + private prepareFixedLevelColorFormArray(fixedLevelColors: FixedColorLevel[] | undefined): FormArray { + const fixedLevelColorsControls: Array = []; + if (fixedLevelColors) { + fixedLevelColors.forEach((fixedLevelColor) => { + fixedLevelColorsControls.push(this.fb.control(fixedLevelColor, [fixedColorLevelValidator])); + }); + } + return this.fb.array(fixedLevelColorsControls); + } + + private prepareTicksValueFormArray(ticksValue: ValueSourceProperty[] | undefined): FormArray { + const ticksValueControls: Array = []; + if (ticksValue) { + ticksValue.forEach((tickValue) => { + ticksValueControls.push(this.fb.control(tickValue, [Validators.required])); + }); + } + return this.fb.array(ticksValueControls); + } + + levelColorsFormArray(): FormArray { + return this.digitalGaugeWidgetSettingsForm.get('levelColors') as FormArray; + } + + public trackByLevelColor(index: number, levelColorControl: AbstractControl): any { + return levelColorControl; + } + + public removeLevelColor(index: number) { + (this.digitalGaugeWidgetSettingsForm.get('levelColors') as FormArray).removeAt(index); + } + + public addLevelColor() { + const levelColorsArray = this.digitalGaugeWidgetSettingsForm.get('levelColors') as FormArray; + const levelColorControl = this.fb.control(null, []); + levelColorsArray.push(levelColorControl); + this.digitalGaugeWidgetSettingsForm.updateValueAndValidity(); + } + + levelColorDrop(event: CdkDragDrop) { + const levelColorsArray = this.digitalGaugeWidgetSettingsForm.get('levelColors') as FormArray; + const levelColor = levelColorsArray.at(event.previousIndex); + levelColorsArray.removeAt(event.previousIndex); + levelColorsArray.insert(event.currentIndex, levelColor); + } + + fixedLevelColorFormArray(): FormArray { + return this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors') as FormArray; + } + + public trackByFixedLevelColor(index: number, fixedLevelColorControl: AbstractControl): any { + return fixedLevelColorControl; + } + + public removeFixedLevelColor(index: number) { + (this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors') as FormArray).removeAt(index); + } + + public addFixedLevelColor() { + const fixedLevelColor: FixedColorLevel = { + from: { + valueSource: 'predefinedValue' + }, + to: { + valueSource: 'predefinedValue' + }, + color: null + }; + const fixedLevelColorsArray = this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors') as FormArray; + const fixedLevelColorControl = this.fb.control(fixedLevelColor, [fixedColorLevelValidator]); + (fixedLevelColorControl as any).new = true; + fixedLevelColorsArray.push(fixedLevelColorControl); + this.digitalGaugeWidgetSettingsForm.updateValueAndValidity(); + if (!this.digitalGaugeWidgetSettingsForm.valid) { + this.onSettingsChanged(this.digitalGaugeWidgetSettingsForm.value); + } + } + + fixedLevelColorDrop(event: CdkDragDrop) { + const fixedLevelColorsArray = this.digitalGaugeWidgetSettingsForm.get('fixedLevelColors') as FormArray; + const fixedLevelColor = fixedLevelColorsArray.at(event.previousIndex); + fixedLevelColorsArray.removeAt(event.previousIndex); + fixedLevelColorsArray.insert(event.currentIndex, fixedLevelColor); + } + + tickValuesFormArray(): FormArray { + return this.digitalGaugeWidgetSettingsForm.get('ticksValue') as FormArray; + } + + public trackByTickValue(index: number, tickValueControl: AbstractControl): any { + return tickValueControl; + } + + public removeTickValue(index: number) { + (this.digitalGaugeWidgetSettingsForm.get('ticksValue') as FormArray).removeAt(index); + } + + public addTickValue() { + const tickValue: ValueSourceProperty = { + valueSource: 'predefinedValue' + }; + const tickValuesArray = this.digitalGaugeWidgetSettingsForm.get('ticksValue') as FormArray; + const tickValueControl = this.fb.control(tickValue, []); + (tickValueControl as any).new = true; + tickValuesArray.push(tickValueControl); + this.digitalGaugeWidgetSettingsForm.updateValueAndValidity(); + } + + tickValueDrop(event: CdkDragDrop) { + const tickValuesArray = this.digitalGaugeWidgetSettingsForm.get('ticksValue') as FormArray; + const tickValue = tickValuesArray.at(event.previousIndex); + tickValuesArray.removeAt(event.previousIndex); + tickValuesArray.insert(event.currentIndex, tickValue); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.html new file mode 100644 index 0000000000..2ce85741d3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.html @@ -0,0 +1,60 @@ + + + +
+ +
+
{{ fixedColorLevelRangeText() }}
+
+
+
+
+
+ + +
+
+ +
+ +
+
+ widgets.gauge.from + +
+
+ widgets.gauge.to + +
+ + +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.scss new file mode 100644 index 0000000000..16c23f47c2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.fixed-color-level { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.fixed-color-level { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.ts new file mode 100644 index 0000000000..f289b235b4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/fixed-color-level.component.ts @@ -0,0 +1,147 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { ValueSourceProperty } from '@home/components/widget/lib/settings/common/value-source.component'; +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormBuilder, + FormGroup, + NG_VALUE_ACCESSOR, ValidationErrors, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { isNumber } from '@core/utils'; +import { IAliasController } from '@core/api/widget-api.models'; + +export interface FixedColorLevel { + from?: ValueSourceProperty; + to?: ValueSourceProperty; + color: string; +} + +export function fixedColorLevelValidator(control: AbstractControl): ValidationErrors | null { + const fixedColorLevel: FixedColorLevel = control.value; + if (!fixedColorLevel || !fixedColorLevel.color) { + return { + fixedColorLevel: true + }; + } + return null; +} + +@Component({ + selector: 'tb-fixed-color-level', + templateUrl: './fixed-color-level.component.html', + styleUrls: ['./fixed-color-level.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => FixedColorLevelComponent), + multi: true + } + ] +}) +export class FixedColorLevelComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Input() + aliasController: IAliasController; + + @Output() + removeFixedColorLevel = new EventEmitter(); + + private modelValue: FixedColorLevel; + + private propagateChange = null; + + public fixedColorLevelFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.fixedColorLevelFormGroup = this.fb.group({ + from: [null, []], + to: [null, []], + color: [null, [Validators.required]] + }); + this.fixedColorLevelFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.fixedColorLevelFormGroup.disable({emitEvent: false}); + } else { + this.fixedColorLevelFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: FixedColorLevel): void { + this.modelValue = value; + this.fixedColorLevelFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + fixedColorLevelRangeText(): string { + const value: FixedColorLevel = this.fixedColorLevelFormGroup.value; + const from = this.valueSourcePropertyText(value?.from); + const to = this.valueSourcePropertyText(value?.to); + return `${from} - ${to}`; + } + + private valueSourcePropertyText(source?: ValueSourceProperty): string { + if (source) { + if (source.valueSource === 'predefinedValue') { + return `${isNumber(source.value) ? source.value : 0}`; + } else if (source.valueSource === 'entityAttribute') { + const alias = source.entityAlias || 'Undefined'; + const key = source.attribute || 'Undefined'; + return `${alias}.${key}`; + } + } + return 'Undefined'; + } + + private updateModel() { + const value: FixedColorLevel = this.fixedColorLevelFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.html new file mode 100644 index 0000000000..13c6f6f7ef --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.html @@ -0,0 +1,61 @@ + + + +
+ +
+
{{ highlightRangeText() }}
+
+
+
+
+
+ + +
+
+ +
+ +
+
+ + widgets.gauge.highlight-from + + + + widgets.gauge.highlight-to + + +
+ + +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.scss new file mode 100644 index 0000000000..bbed5bf6eb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.gauge-highlight { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.gauge-highlight { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.ts new file mode 100644 index 0000000000..697600562e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/gauge-highlight.component.ts @@ -0,0 +1,116 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { isNumber } from '@core/utils'; + +export interface GaugeHighlight { + from: number; + to: number; + color: string; +} + +@Component({ + selector: 'tb-gauge-highlight', + templateUrl: './gauge-highlight.component.html', + styleUrls: ['./gauge-highlight.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => GaugeHighlightComponent), + multi: true + } + ] +}) +export class GaugeHighlightComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Output() + removeHighlight = new EventEmitter(); + + private modelValue: GaugeHighlight; + + private propagateChange = null; + + public gaugeHighlightFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.gaugeHighlightFormGroup = this.fb.group({ + from: [null, []], + to: [null, []], + color: [null, []] + }); + this.gaugeHighlightFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.gaugeHighlightFormGroup.disable({emitEvent: false}); + } else { + this.gaugeHighlightFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: GaugeHighlight): void { + this.modelValue = value; + this.gaugeHighlightFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + highlightRangeText(): string { + const value: GaugeHighlight = this.gaugeHighlightFormGroup.value; + const from = isNumber(value.from) ? value.from : 0; + const to = isNumber(value.to) ? value.to : 0; + return `${from} - ${to}`; + } + + private updateModel() { + const value: GaugeHighlight = this.gaugeHighlightFormGroup.value; + this.modelValue = value; + if (this.gaugeHighlightFormGroup.valid) { + this.propagateChange(this.modelValue); + } else { + this.propagateChange(null); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.html new file mode 100644 index 0000000000..6c0c87e076 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.html @@ -0,0 +1,44 @@ + + + +
+ +
+
{{ tickValueText() }}
+
+
+ + +
+
+ +
+ +
+ +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.scss new file mode 100644 index 0000000000..002203e3d3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.tick-value { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.tick-value { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.ts new file mode 100644 index 0000000000..7bf02ac9d0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gauge/tick-value.component.ts @@ -0,0 +1,120 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { ValueSourceProperty } from '@home/components/widget/lib/settings/common/value-source.component'; +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { isNumber } from '@core/utils'; +import { IAliasController } from '@core/api/widget-api.models'; + +@Component({ + selector: 'tb-tick-value', + templateUrl: './tick-value.component.html', + styleUrls: ['./tick-value.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TickValueComponent), + multi: true + } + ] +}) +export class TickValueComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Input() + aliasController: IAliasController; + + @Output() + removeTickValue = new EventEmitter(); + + private modelValue: ValueSourceProperty; + + private propagateChange = null; + + public tickValueFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.tickValueFormGroup = this.fb.group({ + tickValue: [null, []] + }); + this.tickValueFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.tickValueFormGroup.disable({emitEvent: false}); + } else { + this.tickValueFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: ValueSourceProperty): void { + this.modelValue = value; + this.tickValueFormGroup.patchValue( + {tickValue: value}, {emitEvent: false} + ); + } + + tickValueText(): string { + const value: ValueSourceProperty = this.tickValueFormGroup.get('tickValue').value; + return this.valueSourcePropertyText(value); + } + + private valueSourcePropertyText(source?: ValueSourceProperty): string { + if (source) { + if (source.valueSource === 'predefinedValue') { + return `${isNumber(source.value) ? source.value : 0}`; + } else if (source.valueSource === 'entityAttribute') { + const alias = source.entityAlias || 'Undefined'; + const key = source.attribute || 'Undefined'; + return `${alias}.${key}`; + } + } + return 'Undefined'; + } + + private updateModel() { + const value: ValueSourceProperty = this.tickValueFormGroup.get('tickValue').value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.html new file mode 100644 index 0000000000..cef8746c93 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.html @@ -0,0 +1,96 @@ + +
+
+ widgets.gpio.panel-settings + + +
+ widgets.gpio.gpio-switches +
+
+
+ + +
+
+
+ widgets.gpio.no-gpio-switches +
+
+ +
+
+
+
+
+ widgets.rpc.rpc-settings + + widgets.rpc.request-timeout + + +
+ widgets.gpio.gpio-status-request + + widgets.gpio.method-name + + + + +
+
+ widgets.gpio.gpio-status-change-request + + widgets.gpio.method-name + + + + +
+ + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.ts new file mode 100644 index 0000000000..b398394d1a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component.ts @@ -0,0 +1,145 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { GpioItem, gpioItemValidator } from '@home/components/widget/lib/settings/gpio/gpio-item.component'; +import { ContentType } from '@shared/models/constants'; + +@Component({ + selector: 'tb-gpio-control-widget-settings', + templateUrl: './gpio-control-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class GpioControlWidgetSettingsComponent extends WidgetSettingsComponent { + + gpioControlWidgetSettingsForm: FormGroup; + + contentTypes = ContentType; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.gpioControlWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + switchPanelBackgroundColor: '#008a00', + gpioList: [], + requestTimeout: 500, + gpioStatusRequest: { + method: 'getGpioStatus', + paramsBody: '{}' + }, + gpioStatusChangeRequest: { + method: 'setGpioStatus', + paramsBody: '{\n "pin": "{$pin}",\n "enabled": "{$enabled}"\n}' + }, + parseGpioStatusFunction: 'return body[pin] === true;' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.gpioControlWidgetSettingsForm = this.fb.group({ + + // Panel settings + + switchPanelBackgroundColor: [settings.switchPanelBackgroundColor, [Validators.required]], + + // --> GPIO switches + + gpioList: this.prepareGpioListFormArray(settings.gpioList), + + // RPC settings + + requestTimeout: [settings.requestTimeout, [Validators.min(0), Validators.required]], + + // --> GPIO status request + + gpioStatusRequest: this.fb.group({ + method: [settings.gpioStatusRequest?.method, [Validators.required]], + paramsBody: [settings.gpioStatusRequest?.paramsBody, [Validators.required]] + }, {validators: [Validators.required]}), + + // --> GPIO status change request + + gpioStatusChangeRequest: this.fb.group({ + method: [settings.gpioStatusChangeRequest?.method, [Validators.required]], + paramsBody: [settings.gpioStatusChangeRequest?.paramsBody, [Validators.required]] + }, {validators: [Validators.required]}), + + parseGpioStatusFunction: [settings.parseGpioStatusFunction, [Validators.required]] + }); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('gpioList', this.prepareGpioListFormArray(settings.gpioList), {emitEvent: false}); + } + + private prepareGpioListFormArray(gpioList: GpioItem[] | undefined): FormArray { + const gpioListControls: Array = []; + if (gpioList) { + gpioList.forEach((gpioItem) => { + gpioListControls.push(this.fb.control(gpioItem, [gpioItemValidator(false)])); + }); + } + return this.fb.array(gpioListControls, [(control: AbstractControl) => { + const gpioItems = control.value; + if (!gpioItems || !gpioItems.length) { + return { + gpioItems: true + }; + } + return null; + }]); + } + + gpioListFormArray(): FormArray { + return this.gpioControlWidgetSettingsForm.get('gpioList') as FormArray; + } + + public trackByGpioItem(index: number, gpioItemControl: AbstractControl): any { + return gpioItemControl; + } + + public removeGpioItem(index: number) { + (this.gpioControlWidgetSettingsForm.get('gpioList') as FormArray).removeAt(index); + } + + public addGpioItem() { + const gpioItem: GpioItem = { + pin: null, + label: null, + row: null, + col: null + }; + const gpioListArray = this.gpioControlWidgetSettingsForm.get('gpioList') as FormArray; + const gpioItemControl = this.fb.control(gpioItem, [gpioItemValidator(false)]); + (gpioItemControl as any).new = true; + gpioListArray.push(gpioItemControl); + this.gpioControlWidgetSettingsForm.updateValueAndValidity(); + if (!this.gpioControlWidgetSettingsForm.valid) { + this.onSettingsChanged(this.gpioControlWidgetSettingsForm.value); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.html new file mode 100644 index 0000000000..9ebbdeefd9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.html @@ -0,0 +1,73 @@ + + + +
+ +
+
+
+
+
+
+
+ + +
+
+ +
+ +
+
+ + widgets.gpio.pin + + + + widgets.gpio.label + + +
+
+ + widgets.gpio.row + + + + widgets.gpio.column + + +
+ + +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.scss new file mode 100644 index 0000000000..5190223be1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.gpio-item { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.gpio-item { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.ts new file mode 100644 index 0000000000..9d3c9ef8de --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-item.component.ts @@ -0,0 +1,150 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormBuilder, + FormGroup, + NG_VALUE_ACCESSOR, ValidationErrors, ValidatorFn, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { isNumber } from '@core/utils'; +import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; + +export interface GpioItem { + pin: number; + label: string; + row: number; + col: number; + color?: string; +} + +export function gpioItemValidator(hasColor: boolean): ValidatorFn { + return (control: AbstractControl) => { + const gpioItem: GpioItem = control.value; + if (!gpioItem + || !isNumber(gpioItem.pin) || gpioItem.pin < 1 + || !isNumber(gpioItem.row) || gpioItem.row < 0 + || !isNumber(gpioItem.col) || gpioItem.col < 0 || gpioItem.col > 1 + || !gpioItem.label + || (hasColor && !gpioItem.color) + ) { + return { + gpioItem: true + }; + } + return null; + }; +} + +@Component({ + selector: 'tb-gpio-item', + templateUrl: './gpio-item.component.html', + styleUrls: ['./gpio-item.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => GpioItemComponent), + multi: true + } + ] +}) +export class GpioItemComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Input() + hasColor = false; + + @Output() + removeGpioItem = new EventEmitter(); + + private modelValue: GpioItem; + + private propagateChange = null; + + public gpioItemFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private domSanitizer: DomSanitizer, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.gpioItemFormGroup = this.fb.group({ + pin: [null, [Validators.required, Validators.min(1)]], + label: [null, [Validators.required]], + row: [null, [Validators.required, Validators.min(0)]], + col: [null, [Validators.required, Validators.min(0), Validators.max(1)]] + }); + if (this.hasColor) { + this.gpioItemFormGroup.addControl('color', this.fb.control(null, [Validators.required])); + } + this.gpioItemFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.gpioItemFormGroup.disable({emitEvent: false}); + } else { + this.gpioItemFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: GpioItem): void { + this.modelValue = value; + this.gpioItemFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + gpioItemHtml(): SafeHtml { + const value: GpioItem = this.gpioItemFormGroup.value; + const pin = isNumber(value.pin) && value.pin > 0 ? value.pin : 'Undefined'; + const row = isNumber(value.row) && value.row > -1 ? value.row : 'Undefined'; + const col = isNumber(value.col) && value.col > -1 ? value.col : 'Undefined'; + const label = value.label || 'Undefined'; + return this.domSanitizer.bypassSecurityTrustHtml(`${label} (pin:${pin}) - [row:${row}:col:${col}]`); + } + + private updateModel() { + const value: GpioItem = this.gpioItemFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.html new file mode 100644 index 0000000000..1562e42496 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.html @@ -0,0 +1,55 @@ + +
+
+ widgets.gpio.panel-settings + + +
+ widgets.gpio.gpio-leds +
+
+
+ + +
+
+
+ widgets.gpio.no-gpio-leds +
+
+ +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.ts new file mode 100644 index 0000000000..d39ceade3e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component.ts @@ -0,0 +1,114 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { GpioItem, gpioItemValidator } from '@home/components/widget/lib/settings/gpio/gpio-item.component'; + +@Component({ + selector: 'tb-gpio-panel-widget-settings', + templateUrl: './gpio-panel-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class GpioPanelWidgetSettingsComponent extends WidgetSettingsComponent { + + gpioPanelWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.gpioPanelWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ledPanelBackgroundColor: '#008a00', + gpioList: [] + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.gpioPanelWidgetSettingsForm = this.fb.group({ + + // Panel settings + + ledPanelBackgroundColor: [settings.ledPanelBackgroundColor, [Validators.required]], + + // --> GPIO leds + + gpioList: this.prepareGpioListFormArray(settings.gpioList), + + }); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('gpioList', this.prepareGpioListFormArray(settings.gpioList), {emitEvent: false}); + } + + private prepareGpioListFormArray(gpioList: GpioItem[] | undefined): FormArray { + const gpioListControls: Array = []; + if (gpioList) { + gpioList.forEach((gpioItem) => { + gpioListControls.push(this.fb.control(gpioItem, [gpioItemValidator(true)])); + }); + } + return this.fb.array(gpioListControls, [(control: AbstractControl) => { + const gpioItems = control.value; + if (!gpioItems || !gpioItems.length) { + return { + gpioItems: true + }; + } + return null; + }]); + } + + gpioListFormArray(): FormArray { + return this.gpioPanelWidgetSettingsForm.get('gpioList') as FormArray; + } + + public trackByGpioItem(index: number, gpioItemControl: AbstractControl): any { + return gpioItemControl; + } + + public removeGpioItem(index: number) { + (this.gpioPanelWidgetSettingsForm.get('gpioList') as FormArray).removeAt(index); + } + + public addGpioItem() { + const gpioItem: GpioItem = { + pin: null, + label: null, + row: null, + col: null, + color: null + }; + const gpioListArray = this.gpioPanelWidgetSettingsForm.get('gpioList') as FormArray; + const gpioItemControl = this.fb.control(gpioItem, [gpioItemValidator(true)]); + (gpioItemControl as any).new = true; + gpioListArray.push(gpioItemControl); + this.gpioPanelWidgetSettingsForm.updateValueAndValidity(); + if (!this.gpioPanelWidgetSettingsForm.valid) { + this.onSettingsChanged(this.gpioPanelWidgetSettingsForm.value); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.html new file mode 100644 index 0000000000..68a1a6c5dc --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.html @@ -0,0 +1,53 @@ + + + +
+ +
+
+
+
+ + +
+
+ +
+ +
+
+ + widgets.input-widgets.option-value + + + + widgets.input-widgets.option-label + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.scss new file mode 100644 index 0000000000..36c8d7c154 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.scss @@ -0,0 +1,40 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + display: block; + .mat-expansion-panel { + box-shadow: none; + &.datakey-select-option { + border: 1px groove rgba(0, 0, 0, .25); + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + &.mat-expanded { + height: 48px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + &.datakey-select-option { + .mat-expansion-panel-body { + padding: 0 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.ts new file mode 100644 index 0000000000..6a1033a4e2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/datakey-select-option.component.ts @@ -0,0 +1,128 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core'; +import { + AbstractControl, + ControlValueAccessor, + FormBuilder, + FormGroup, + NG_VALUE_ACCESSOR, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; + +export interface DataKeySelectOption { + value: string; + label?: string; +} + +export function dataKeySelectOptionValidator(control: AbstractControl) { + const selectOption: DataKeySelectOption = control.value; + if (!selectOption || !selectOption.value) { + return { + dataKeySelectOption: true + }; + } + return null; +} + +@Component({ + selector: 'tb-datakey-select-option', + templateUrl: './datakey-select-option.component.html', + styleUrls: ['./datakey-select-option.component.scss', './../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => DataKeySelectOptionComponent), + multi: true + } + ] +}) +export class DataKeySelectOptionComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @Input() + disabled: boolean; + + @Input() + expanded = false; + + @Output() + removeSelectOption = new EventEmitter(); + + private modelValue: DataKeySelectOption; + + private propagateChange = null; + + public selectOptionFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private domSanitizer: DomSanitizer, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.selectOptionFormGroup = this.fb.group({ + value: [null, [Validators.required]], + label: [null, []] + }); + this.selectOptionFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.selectOptionFormGroup.disable({emitEvent: false}); + } else { + this.selectOptionFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: DataKeySelectOption): void { + this.modelValue = value; + this.selectOptionFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + selectOptionHtml(): SafeHtml { + const selectOption: DataKeySelectOption = this.selectOptionFormGroup.value; + const value = selectOption?.value || 'Undefined'; + const label = selectOption?.label || ''; + return this.domSanitizer.bypassSecurityTrustHtml(`${value} ${label ? '(' + label + ')' : ''}`); + } + + private updateModel() { + const value: DataKeySelectOption = this.selectOptionFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.html new file mode 100644 index 0000000000..9438d6d59f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.html @@ -0,0 +1,84 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + + + widgets.input-widgets.claim-button-label + + + + {{ 'widgets.input-widgets.show-secret-key-field' | translate }} + +
+
+ widgets.input-widgets.labels-settings + + + + + {{ 'widgets.input-widgets.show-labels' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.input-widgets.device-name-label + + + + widgets.input-widgets.secret-key-label + + +
+
+
+
+
+ widgets.input-widgets.messages-settings + + widgets.input-widgets.claim-device-success-message + + + + widgets.input-widgets.claim-device-not-found-message + + + + widgets.input-widgets.claim-device-failed-message + + + + widgets.input-widgets.claim-device-name-required-message + + + + widgets.input-widgets.claim-device-secret-key-required-message + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.ts new file mode 100644 index 0000000000..b245ce43bb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/device-claiming-widget-settings.component.ts @@ -0,0 +1,110 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-device-claiming-widget-settings', + templateUrl: './device-claiming-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class DeviceClaimingWidgetSettingsComponent extends WidgetSettingsComponent { + + deviceClaimingWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.deviceClaimingWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + labelClaimButon: '', + deviceSecret: false, + showLabel: true, + deviceLabel: '', + secretKeyLabel: '', + successfulClaimDevice: '', + deviceNotFound: '', + failedClaimDevice: '', + requiredErrorDevice: '', + requiredErrorSecretKey: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.deviceClaimingWidgetSettingsForm = this.fb.group({ + + // General settings + + widgetTitle: [settings.widgetTitle, []], + labelClaimButon: [settings.labelClaimButon, []], + deviceSecret: [settings.deviceSecret, []], + + // Labels settings + + showLabel: [settings.showLabel, []], + deviceLabel: [settings.deviceLabel, []], + secretKeyLabel: [settings.secretKeyLabel, []], + + // Message settings + + successfulClaimDevice: [settings.successfulClaimDevice, []], + deviceNotFound: [settings.deviceNotFound, []], + failedClaimDevice: [settings.failedClaimDevice, []], + requiredErrorDevice: [settings.requiredErrorDevice, []], + requiredErrorSecretKey: [settings.requiredErrorSecretKey, []] + }); + } + + protected validatorTriggers(): string[] { + return ['deviceSecret', 'showLabel']; + } + + protected updateValidators(emitEvent: boolean) { + const deviceSecret: boolean = this.deviceClaimingWidgetSettingsForm.get('deviceSecret').value; + const showLabel: boolean = this.deviceClaimingWidgetSettingsForm.get('showLabel').value; + if (deviceSecret) { + if (showLabel) { + this.deviceClaimingWidgetSettingsForm.get('secretKeyLabel').enable(); + } else { + this.deviceClaimingWidgetSettingsForm.get('secretKeyLabel').disable(); + } + this.deviceClaimingWidgetSettingsForm.get('requiredErrorSecretKey').enable(); + } else { + this.deviceClaimingWidgetSettingsForm.get('requiredErrorSecretKey').disable(); + this.deviceClaimingWidgetSettingsForm.get('secretKeyLabel').disable(); + } + if (showLabel) { + this.deviceClaimingWidgetSettingsForm.get('deviceLabel').enable(); + } else { + this.deviceClaimingWidgetSettingsForm.get('deviceLabel').disable(); + } + this.deviceClaimingWidgetSettingsForm.get('secretKeyLabel').updateValueAndValidity({emitEvent}); + this.deviceClaimingWidgetSettingsForm.get('deviceLabel').updateValueAndValidity({emitEvent}); + this.deviceClaimingWidgetSettingsForm.get('requiredErrorSecretKey').updateValueAndValidity({emitEvent}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.html new file mode 100644 index 0000000000..d838c59bf7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.html @@ -0,0 +1,59 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + +
+
+ widgets.input-widgets.image-settings +
+ + widgets.input-widgets.image-format + + + {{ 'widgets.input-widgets.image-format-jpeg' | translate }} + + + {{ 'widgets.input-widgets.image-format-png' | translate }} + + + {{ 'widgets.input-widgets.image-format-webp' | translate }} + + + + + widgets.input-widgets.image-quality + + +
+
+ + widgets.input-widgets.max-image-width + + + + widgets.input-widgets.max-image-height + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.ts new file mode 100644 index 0000000000..44664d6b67 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component.ts @@ -0,0 +1,67 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-photo-camera-input-widget-settings', + templateUrl: './photo-camera-input-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class PhotoCameraInputWidgetSettingsComponent extends WidgetSettingsComponent { + + photoCameraInputWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.photoCameraInputWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + + imageFormat: 'image/png', + imageQuality: 0.92, + maxWidth: 640, + maxHeight: 480 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.photoCameraInputWidgetSettingsForm = this.fb.group({ + + // General settings + + widgetTitle: [settings.widgetTitle, []], + + // Image settings + + imageFormat: [settings.imageFormat, []], + imageQuality: [settings.imageQuality, [Validators.min(0), Validators.max(1)]], + maxWidth: [settings.maxWidth, [Validators.min(1)]], + maxHeight: [settings.maxHeight, [Validators.min(1)]] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.html new file mode 100644 index 0000000000..14b63d2f14 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.html @@ -0,0 +1,47 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + +
+ + {{ 'widgets.input-widgets.show-label' | translate }} + + + widgets.input-widgets.label + + +
+
+ + {{ 'widgets.input-widgets.required' | translate }} + + + widgets.input-widgets.required-error-message + + +
+ + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.ts new file mode 100644 index 0000000000..6f12aa4463 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-attribute-general-settings.component.ts @@ -0,0 +1,172 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; + +export interface UpdateAttributeGeneralSettings { + widgetTitle: string; + showLabel: boolean; + labelValue?: string; + isRequired: boolean; + requiredErrorMessage: string; + showResultMessage: boolean; +} + +export function updateAttributeGeneralDefaultSettings(hasLabelValue = true): UpdateAttributeGeneralSettings { + const updateAttributeGeneralSettings: UpdateAttributeGeneralSettings = { + widgetTitle: '', + showLabel: true, + isRequired: true, + requiredErrorMessage: '', + showResultMessage: true + }; + if (hasLabelValue) { + updateAttributeGeneralSettings.labelValue = ''; + } + return updateAttributeGeneralSettings; +} + +@Component({ + selector: 'tb-update-attribute-general-settings', + templateUrl: './update-attribute-general-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => UpdateAttributeGeneralSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => UpdateAttributeGeneralSettingsComponent), + multi: true + } + ] +}) +export class UpdateAttributeGeneralSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + hasLabelValue = true; + + private modelValue: UpdateAttributeGeneralSettings; + + private propagateChange = null; + + public updateAttributeGeneralSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.updateAttributeGeneralSettingsFormGroup = this.fb.group({ + widgetTitle: ['', []], + showLabel: [true, []], + isRequired: [true, []], + requiredErrorMessage: ['', []], + showResultMessage: [true, []] + }); + if (this.hasLabelValue) { + this.updateAttributeGeneralSettingsFormGroup.addControl('labelValue', this.fb.control('', [])); + this.updateAttributeGeneralSettingsFormGroup.get('showLabel').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + } + this.updateAttributeGeneralSettingsFormGroup.get('isRequired').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateAttributeGeneralSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.updateAttributeGeneralSettingsFormGroup.disable({emitEvent: false}); + } else { + this.updateAttributeGeneralSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: UpdateAttributeGeneralSettings): void { + this.modelValue = value; + this.updateAttributeGeneralSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.updateAttributeGeneralSettingsFormGroup.valid ? null : { + updateAttributeGeneralSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: UpdateAttributeGeneralSettings = this.updateAttributeGeneralSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + if (this.hasLabelValue) { + const showLabel: boolean = this.updateAttributeGeneralSettingsFormGroup.get('showLabel').value; + if (showLabel) { + this.updateAttributeGeneralSettingsFormGroup.get('labelValue').enable({emitEvent}); + } else { + this.updateAttributeGeneralSettingsFormGroup.get('labelValue').disable({emitEvent}); + } + this.updateAttributeGeneralSettingsFormGroup.get('labelValue').updateValueAndValidity({emitEvent: false}); + } + + const isRequired: boolean = this.updateAttributeGeneralSettingsFormGroup.get('isRequired').value; + if (isRequired) { + this.updateAttributeGeneralSettingsFormGroup.get('requiredErrorMessage').enable({emitEvent}); + } else { + this.updateAttributeGeneralSettingsFormGroup.get('requiredErrorMessage').disable({emitEvent}); + } + this.updateAttributeGeneralSettingsFormGroup.get('requiredErrorMessage').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.html new file mode 100644 index 0000000000..d47e0a0d73 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.html @@ -0,0 +1,42 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + + + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+
+ widgets.input-widgets.checkbox-settings +
+ + widgets.input-widgets.true-label + + + + widgets.input-widgets.false-label + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..66eded1107 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component.ts @@ -0,0 +1,58 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-update-boolean-attribute-widget-settings', + templateUrl: './update-boolean-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateBooleanAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateBooleanAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateBooleanAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + showResultMessage: true, + trueValue: '', + falseValue: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateBooleanAttributeWidgetSettingsForm = this.fb.group({ + widgetTitle: [settings.widgetTitle, []], + showResultMessage: [settings.showResultMessage, []], + trueValue: [settings.trueValue, []], + falseValue: [settings.falseValue, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.html new file mode 100644 index 0000000000..5939daefc4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.html @@ -0,0 +1,30 @@ + + +
+ + +
+ widgets.input-widgets.datetime-field-settings + + {{ 'widgets.input-widgets.display-time-input' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..898a645330 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component.ts @@ -0,0 +1,73 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { deepClone } from '@core/utils'; +import { + updateAttributeGeneralDefaultSettings +} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component'; + +@Component({ + selector: 'tb-update-date-attribute-widget-settings', + templateUrl: './update-date-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateDateAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateDateAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateDateAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...updateAttributeGeneralDefaultSettings(false), + showTimeInput: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateDateAttributeWidgetSettingsForm = this.fb.group({ + updateAttributeGeneralSettings: [settings.updateAttributeGeneralSettings, []], + showTimeInput: [settings.showTimeInput, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const updateAttributeGeneralSettings = deepClone(settings, ['showTimeInput']); + return { + updateAttributeGeneralSettings, + showTimeInput: settings.showTimeInput + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + ...settings.updateAttributeGeneralSettings, + showTimeInput: settings.showTimeInput + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.html new file mode 100644 index 0000000000..8f5b543e41 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.html @@ -0,0 +1,36 @@ + + +
+ + +
+ widgets.input-widgets.double-field-settings +
+ + widgets.input-widgets.min-value + + + + widgets.input-widgets.max-value + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..ef71992aef --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component.ts @@ -0,0 +1,77 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { deepClone } from '@core/utils'; +import { + updateAttributeGeneralDefaultSettings +} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component'; + +@Component({ + selector: 'tb-update-double-attribute-widget-settings', + templateUrl: './update-double-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateDoubleAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateDoubleAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateDoubleAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...updateAttributeGeneralDefaultSettings(), + minValue: null, + maxValue: null + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateDoubleAttributeWidgetSettingsForm = this.fb.group({ + updateAttributeGeneralSettings: [settings.updateAttributeGeneralSettings, []], + minValue: [settings.minValue, []], + maxValue: [settings.maxValue, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const updateAttributeGeneralSettings = deepClone(settings, ['minValue', 'maxValue']); + return { + updateAttributeGeneralSettings, + minValue: settings.minValue, + maxValue: settings.maxValue + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + ...settings.updateAttributeGeneralSettings, + minValue: settings.minValue, + maxValue: settings.maxValue + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.html new file mode 100644 index 0000000000..ee86c62870 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.html @@ -0,0 +1,46 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + + + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+
+ widgets.input-widgets.image-input-settings +
+ + {{ 'widgets.input-widgets.display-preview' | translate }} + + + {{ 'widgets.input-widgets.display-clear-button' | translate }} + + + {{ 'widgets.input-widgets.display-apply-button' | translate }} + + + {{ 'widgets.input-widgets.display-discard-button' | translate }} + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..755fa6fc94 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component.ts @@ -0,0 +1,62 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-update-image-attribute-widget-settings', + templateUrl: './update-image-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateImageAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateImageAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateImageAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + showResultMessage: true, + displayPreview: true, + displayClearButton: false, + displayApplyButton: true, + displayDiscardButton: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateImageAttributeWidgetSettingsForm = this.fb.group({ + widgetTitle: [settings.widgetTitle, []], + showResultMessage: [settings.showResultMessage, []], + displayPreview: [settings.displayPreview, []], + displayClearButton: [settings.displayClearButton, []], + displayApplyButton: [settings.displayApplyButton, []], + displayDiscardButton: [settings.displayDiscardButton, []] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.html new file mode 100644 index 0000000000..0e5c1deccd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.html @@ -0,0 +1,36 @@ + + +
+ + +
+ widgets.input-widgets.integer-field-settings +
+ + widgets.input-widgets.min-value + + + + widgets.input-widgets.max-value + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..d06601b468 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component.ts @@ -0,0 +1,77 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { deepClone } from '@core/utils'; +import { + updateAttributeGeneralDefaultSettings +} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component'; + +@Component({ + selector: 'tb-update-integer-attribute-widget-settings', + templateUrl: './update-integer-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateIntegerAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateIntegerAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateIntegerAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...updateAttributeGeneralDefaultSettings(), + minValue: null, + maxValue: null, + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateIntegerAttributeWidgetSettingsForm = this.fb.group({ + updateAttributeGeneralSettings: [settings.updateAttributeGeneralSettings, []], + minValue: [settings.minValue, []], + maxValue: [settings.maxValue, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const updateAttributeGeneralSettings = deepClone(settings, ['minValue', 'maxValue']); + return { + updateAttributeGeneralSettings, + minValue: settings.minValue, + maxValue: settings.maxValue + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + ...settings.updateAttributeGeneralSettings, + minValue: settings.minValue, + maxValue: settings.maxValue + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.html new file mode 100644 index 0000000000..cd967cff33 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.html @@ -0,0 +1,68 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + +
+ + {{ 'widgets.input-widgets.show-label' | translate }} + + + widgets.input-widgets.label + + +
+ + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+
+ widgets.input-widgets.attribute-settings +
+ + widgets.input-widgets.widget-mode + + + {{ 'widgets.input-widgets.widget-mode-update-attribute' | translate }} + + + {{ 'widgets.input-widgets.widget-mode-update-timeseries' | translate }} + + + + + widgets.input-widgets.attribute-scope + + + {{ 'widgets.input-widgets.attribute-scope-server' | translate }} + + + {{ 'widgets.input-widgets.attribute-scope-shared' | translate }} + + + +
+ + {{ 'widgets.input-widgets.value-required' | translate }} + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..af0c8bf474 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component.ts @@ -0,0 +1,93 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-update-json-attribute-widget-settings', + templateUrl: './update-json-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateJsonAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateJsonAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateJsonAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + showLabel: true, + labelValue: '', + showResultMessage: true, + + widgetMode: 'ATTRIBUTE', + attributeScope: 'SERVER_SCOPE', + attributeRequired: true + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateJsonAttributeWidgetSettingsForm = this.fb.group({ + + // General settings + + widgetTitle: [settings.widgetTitle, []], + showLabel: [settings.showLabel, []], + labelValue: [settings.labelValue, []], + showResultMessage: [settings.showResultMessage, []], + + // Attribute settings + + widgetMode: [settings.widgetMode, []], + attributeScope: [settings.attributeScope, []], + attributeRequired: [settings.attributeRequired, []] + }); + } + + protected validatorTriggers(): string[] { + return ['showLabel', 'widgetMode']; + } + + protected updateValidators(emitEvent: boolean) { + const showLabel: boolean = this.updateJsonAttributeWidgetSettingsForm.get('showLabel').value; + const widgetMode: string = this.updateJsonAttributeWidgetSettingsForm.get('widgetMode').value; + + if (showLabel) { + this.updateJsonAttributeWidgetSettingsForm.get('labelValue').enable(); + } else { + this.updateJsonAttributeWidgetSettingsForm.get('labelValue').disable(); + } + if (widgetMode === 'ATTRIBUTE') { + this.updateJsonAttributeWidgetSettingsForm.get('attributeScope').enable(); + } else { + this.updateJsonAttributeWidgetSettingsForm.get('attributeScope').disable(); + } + this.updateJsonAttributeWidgetSettingsForm.get('labelValue').updateValueAndValidity({emitEvent}); + this.updateJsonAttributeWidgetSettingsForm.get('attributeScope').updateValueAndValidity({emitEvent}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.html new file mode 100644 index 0000000000..5afb4cfc9d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.html @@ -0,0 +1,84 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + + + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+ + widgets.input-widgets.latitude-key-name + + + + widgets.input-widgets.longitude-key-name + + +
+ + {{ 'widgets.input-widgets.show-get-location-button' | translate }} + + + {{ 'widgets.input-widgets.use-high-accuracy' | translate }} + +
+
+ widgets.input-widgets.location-fields-settings + + {{ 'widgets.input-widgets.show-label' | translate }} + +
+ + widgets.input-widgets.latitude-label + + + + widgets.input-widgets.longitude-label + + +
+ + widgets.input-widgets.input-fields-alignment + + + {{ 'widgets.input-widgets.input-fields-alignment-column' | translate }} + + + {{ 'widgets.input-widgets.input-fields-alignment-row' | translate }} + + + +
+ + {{ 'widgets.input-widgets.latitude-field-required' | translate }} + + + {{ 'widgets.input-widgets.longitude-field-required' | translate }} + +
+ + widgets.input-widgets.required-error-message + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..a9fa723f29 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component.ts @@ -0,0 +1,109 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-update-location-attribute-widget-settings', + templateUrl: './update-location-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateLocationAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateLocationAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateLocationAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + showResultMessage: true, + latKeyName: 'latitude', + lngKeyName: 'longitude', + showGetLocation: true, + enableHighAccuracy: false, + + showLabel: true, + latLabel: '', + lngLabel: '', + inputFieldsAlignment: 'column', + isLatRequired: true, + isLngRequired: true, + requiredErrorMessage: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateLocationAttributeWidgetSettingsForm = this.fb.group({ + + // General settings + + widgetTitle: [settings.widgetTitle, []], + showResultMessage: [settings.showResultMessage, []], + latKeyName: [settings.latKeyName, []], + lngKeyName: [settings.lngKeyName, []], + showGetLocation: [settings.showGetLocation, []], + enableHighAccuracy: [settings.enableHighAccuracy, []], + + // Location fields settings + + showLabel: [settings.showLabel, []], + latLabel: [settings.latLabel, []], + lngLabel: [settings.lngLabel, []], + inputFieldsAlignment: [settings.inputFieldsAlignment, []], + isLatRequired: [settings.isLatRequired, []], + isLngRequired: [settings.isLngRequired, []], + requiredErrorMessage: [settings.requiredErrorMessage, []] + }); + } + + protected validatorTriggers(): string[] { + return ['showLabel', 'isLatRequired', 'isLngRequired']; + } + + protected updateValidators(emitEvent: boolean) { + const showLabel: boolean = this.updateLocationAttributeWidgetSettingsForm.get('showLabel').value; + const isLatRequired: boolean = this.updateLocationAttributeWidgetSettingsForm.get('isLatRequired').value; + const isLngRequired: boolean = this.updateLocationAttributeWidgetSettingsForm.get('isLngRequired').value; + + if (showLabel) { + this.updateLocationAttributeWidgetSettingsForm.get('latLabel').enable(); + this.updateLocationAttributeWidgetSettingsForm.get('lngLabel').enable(); + } else { + this.updateLocationAttributeWidgetSettingsForm.get('latLabel').disable(); + this.updateLocationAttributeWidgetSettingsForm.get('lngLabel').disable(); + } + if (isLatRequired || isLngRequired) { + this.updateLocationAttributeWidgetSettingsForm.get('requiredErrorMessage').enable(); + } else { + this.updateLocationAttributeWidgetSettingsForm.get('requiredErrorMessage').disable(); + } + this.updateLocationAttributeWidgetSettingsForm.get('latLabel').updateValueAndValidity({emitEvent}); + this.updateLocationAttributeWidgetSettingsForm.get('lngLabel').updateValueAndValidity({emitEvent}); + this.updateLocationAttributeWidgetSettingsForm.get('requiredErrorMessage').updateValueAndValidity({emitEvent}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.html new file mode 100644 index 0000000000..2f47998fba --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.html @@ -0,0 +1,246 @@ + +
+ + {{ 'widgets.input-widgets.hide-input-field' | translate }} + +
+ widgets.input-widgets.general-settings +
+ + widgets.input-widgets.datakey-type + + + {{ 'widgets.input-widgets.datakey-type-server' | translate }} + + + {{ 'widgets.input-widgets.datakey-type-shared' | translate }} + + + {{ 'widgets.input-widgets.datakey-type-timeseries' | translate }} + + + + + widgets.input-widgets.datakey-value-type + + + {{ 'widgets.input-widgets.datakey-value-type-string' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-double' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-integer' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-boolean-checkbox' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-boolean-switch' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-date-time' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-date' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-time' | translate }} + + + {{ 'widgets.input-widgets.datakey-value-type-select' | translate }} + + + +
+ + {{ 'widgets.input-widgets.value-is-required' | translate }} + +
+ + widgets.input-widgets.ability-to-edit-attribute + + + {{ 'widgets.input-widgets.ability-to-edit-attribute-editable' | translate }} + + + {{ 'widgets.input-widgets.ability-to-edit-attribute-disabled' | translate }} + + + {{ 'widgets.input-widgets.ability-to-edit-attribute-readonly' | translate }} + + + + + widgets.input-widgets.disable-on-datakey-name + + +
+
+
+ widgets.input-widgets.slide-toggle-settings + + widgets.input-widgets.slide-toggle-label-position + + + {{ 'widgets.input-widgets.slide-toggle-label-position-after' | translate }} + + + {{ 'widgets.input-widgets.slide-toggle-label-position-before' | translate }} + + + +
+
+ widgets.input-widgets.select-options +
+
+
+ + +
+
+
+ widgets.input-widgets.no-select-options +
+
+ +
+
+
+
+ widgets.input-widgets.numeric-field-settings +
+ + widgets.input-widgets.step-interval + + + + widgets.input-widgets.min-value + + + + widgets.input-widgets.max-value + + +
+
+
+ widgets.input-widgets.error-messages + + widgets.input-widgets.required-error-message + + +
+ + widgets.input-widgets.min-value-error-message + + + + widgets.input-widgets.max-value-error-message + + +
+ + widgets.input-widgets.invalid-date-error-message + + +
+
+ widgets.input-widgets.icon-settings + + {{ 'widgets.input-widgets.use-custom-icon' | translate }} + + + + + +
+
+ widgets.input-widgets.value-conversion-settings +
+ widgets.input-widgets.get-value-settings + + + + + {{ 'widgets.input-widgets.use-get-value-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.input-widgets.set-value-settings + + + + + {{ 'widgets.input-widgets.use-set-value-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.ts new file mode 100644 index 0000000000..4884166be5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component.ts @@ -0,0 +1,250 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { + DataKeySelectOption, + dataKeySelectOptionValidator +} from '@home/components/widget/lib/settings/input/datakey-select-option.component'; +import { CdkDragDrop } from '@angular/cdk/drag-drop'; + +@Component({ + selector: 'tb-update-multiple-attributes-key-settings', + templateUrl: './update-multiple-attributes-key-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateMultipleAttributesKeySettingsComponent extends WidgetSettingsComponent { + + updateMultipleAttributesKeySettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateMultipleAttributesKeySettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + dataKeyHidden: false, + dataKeyType: 'server', + dataKeyValueType: 'string', + required: false, + isEditable: 'editable', + disabledOnDataKey: '', + + slideToggleLabelPosition: 'after', + selectOptions: [], + step: 1, + minValue: null, + maxValue: null, + + requiredErrorMessage: '', + minValueErrorMessage: '', + maxValueErrorMessage: '', + invalidDateErrorMessage: '', + + useCustomIcon: false, + icon: '', + customIcon: '', + + useGetValueFunction: false, + getValueFunctionBody: '', + useSetValueFunction: false, + setValueFunctionBody: '' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateMultipleAttributesKeySettingsForm = this.fb.group({ + + dataKeyHidden: [settings.dataKeyHidden, []], + + // General settings + + dataKeyType: [settings.dataKeyType, []], + dataKeyValueType: [settings.dataKeyValueType, []], + required: [settings.required, []], + isEditable: [settings.isEditable, []], + disabledOnDataKey: [settings.disabledOnDataKey, []], + + // Slide toggle settings + + slideToggleLabelPosition: [settings.slideToggleLabelPosition, []], + + // Select options + + selectOptions: this.prepareSelectOptionsFormArray(settings.selectOptions), + + // Numeric field settings + + step: [settings.step, [Validators.min(0)]], + minValue: [settings.minValue, []], + maxValue: [settings.maxValue, []], + + // Error messages + + requiredErrorMessage: [settings.requiredErrorMessage, []], + minValueErrorMessage: [settings.minValueErrorMessage, []], + maxValueErrorMessage: [settings.maxValueErrorMessage, []], + invalidDateErrorMessage: [settings.invalidDateErrorMessage, []], + + // Icon settings + + useCustomIcon: [settings.useCustomIcon, []], + icon: [settings.icon, []], + customIcon: [settings.customIcon, []], + + // Value conversion settings + + useGetValueFunction: [settings.useGetValueFunction, []], + getValueFunctionBody: [settings.getValueFunctionBody, []], + useSetValueFunction: [settings.useSetValueFunction, []], + setValueFunctionBody: [settings.setValueFunctionBody, []] + + }); + } + + protected validatorTriggers(): string[] { + return ['dataKeyHidden', 'dataKeyValueType', 'required', 'isEditable', 'useCustomIcon', 'useGetValueFunction', 'useSetValueFunction']; + } + + protected updateValidators(emitEvent: boolean) { + const dataKeyHidden: boolean = this.updateMultipleAttributesKeySettingsForm.get('dataKeyHidden').value; + const dataKeyValueType: string = this.updateMultipleAttributesKeySettingsForm.get('dataKeyValueType').value; + const required: boolean = this.updateMultipleAttributesKeySettingsForm.get('required').value; + const isEditable: string = this.updateMultipleAttributesKeySettingsForm.get('isEditable').value; + const useCustomIcon: boolean = this.updateMultipleAttributesKeySettingsForm.get('useCustomIcon').value; + const useGetValueFunction: boolean = this.updateMultipleAttributesKeySettingsForm.get('useGetValueFunction').value; + const useSetValueFunction: boolean = this.updateMultipleAttributesKeySettingsForm.get('useSetValueFunction').value; + + this.updateMultipleAttributesKeySettingsForm.disable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('dataKeyHidden').enable({emitEvent: false}); + + if (!dataKeyHidden) { + this.updateMultipleAttributesKeySettingsForm.get('dataKeyType').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('dataKeyValueType').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('required').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('isEditable').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('useCustomIcon').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('useGetValueFunction').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('useSetValueFunction').enable({emitEvent: false}); + + if (isEditable !== 'disabled') { + this.updateMultipleAttributesKeySettingsForm.get('disabledOnDataKey').enable({emitEvent: false}); + } + + if (dataKeyValueType === 'booleanSwitch') { + this.updateMultipleAttributesKeySettingsForm.get('slideToggleLabelPosition').enable({emitEvent: false}); + } else if (dataKeyValueType === 'select') { + this.updateMultipleAttributesKeySettingsForm.get('selectOptions').enable({emitEvent: false}); + } else if (dataKeyValueType === 'integer' || dataKeyValueType === 'double') { + this.updateMultipleAttributesKeySettingsForm.get('step').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('minValue').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('maxValue').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('minValueErrorMessage').enable({emitEvent: false}); + this.updateMultipleAttributesKeySettingsForm.get('maxValueErrorMessage').enable({emitEvent: false}); + } else if (dataKeyValueType === 'dateTime' || dataKeyValueType === 'date' || dataKeyValueType === 'time') { + this.updateMultipleAttributesKeySettingsForm.get('invalidDateErrorMessage').enable({emitEvent: false}); + } + if (required) { + this.updateMultipleAttributesKeySettingsForm.get('requiredErrorMessage').enable({emitEvent: false}); + } + if (useCustomIcon) { + this.updateMultipleAttributesKeySettingsForm.get('customIcon').enable({emitEvent: false}); + } else { + this.updateMultipleAttributesKeySettingsForm.get('icon').enable({emitEvent: false}); + } + if (useGetValueFunction) { + this.updateMultipleAttributesKeySettingsForm.get('getValueFunctionBody').enable({emitEvent: false}); + } + if (useSetValueFunction) { + this.updateMultipleAttributesKeySettingsForm.get('setValueFunctionBody').enable({emitEvent: false}); + } + } + this.updateMultipleAttributesKeySettingsForm.updateValueAndValidity({emitEvent: false}); + } + + protected doUpdateSettings(settingsForm: FormGroup, settings: WidgetSettings) { + settingsForm.setControl('selectOptions', this.prepareSelectOptionsFormArray(settings.selectOptions), {emitEvent: false}); + } + + private prepareSelectOptionsFormArray(selectOptions: DataKeySelectOption[] | undefined): FormArray { + const selectOptionsControls: Array = []; + if (selectOptions) { + selectOptions.forEach((selectOption) => { + selectOptionsControls.push(this.fb.control(selectOption, [dataKeySelectOptionValidator])); + }); + } + return this.fb.array(selectOptionsControls, [(control: AbstractControl) => { + const selectOptionItems = control.value; + if (!selectOptionItems || !selectOptionItems.length) { + return { + selectOptionItems: true + }; + } + return null; + }]); + } + + selectOptionsFormArray(): FormArray { + return this.updateMultipleAttributesKeySettingsForm.get('selectOptions') as FormArray; + } + + public trackBySelectOption(index: number, selectOptionControl: AbstractControl): any { + return selectOptionControl; + } + + public removeSelectOption(index: number) { + (this.updateMultipleAttributesKeySettingsForm.get('selectOptions') as FormArray).removeAt(index); + } + + public addSelectOption() { + const selectOption: DataKeySelectOption = { + value: null, + label: null + }; + const selectOptionsArray = this.updateMultipleAttributesKeySettingsForm.get('selectOptions') as FormArray; + const selectOptionControl = this.fb.control(selectOption, [dataKeySelectOptionValidator]); + (selectOptionControl as any).new = true; + selectOptionsArray.push(selectOptionControl); + this.updateMultipleAttributesKeySettingsForm.updateValueAndValidity(); + if (!this.updateMultipleAttributesKeySettingsForm.valid) { + this.onSettingsChanged(this.updateMultipleAttributesKeySettingsForm.value); + } + } + + selectOptionDrop(event: CdkDragDrop) { + const selectOptionsArray = this.updateMultipleAttributesKeySettingsForm.get('selectOptions') as FormArray; + const selectOption = selectOptionsArray.at(event.previousIndex); + selectOptionsArray.removeAt(event.previousIndex); + selectOptionsArray.insert(event.currentIndex, selectOption); + } + + displayErrorMessagesSection(): boolean { + const dataKeyHidden: boolean = this.updateMultipleAttributesKeySettingsForm.get('dataKeyHidden').value; + const required: boolean = this.updateMultipleAttributesKeySettingsForm.get('required').value; + const dataKeyValueType: string = this.updateMultipleAttributesKeySettingsForm.get('dataKeyValueType').value; + return !dataKeyHidden && (required || (['integer', 'double', 'dateTime', 'date', 'time'].includes(dataKeyValueType))); + } +} + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.html new file mode 100644 index 0000000000..327879ed03 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.html @@ -0,0 +1,94 @@ + +
+
+ widgets.input-widgets.general-settings + + widgets.input-widgets.widget-title + + + + {{ 'widgets.input-widgets.show-result-message' | translate }} + +
+
+ widgets.input-widgets.action-buttons + + + + + {{ 'widgets.input-widgets.show-action-buttons' | translate }} + + + + widget-config.advanced-settings + + + +
+ + {{ 'widgets.input-widgets.update-all-values' | translate }} + +
+ + widgets.input-widgets.save-button-label + + + + widgets.input-widgets.reset-button-label + + +
+
+
+
+
+
+ widgets.input-widgets.group-settings +
+ + {{ 'widgets.input-widgets.show-group-title' | translate }} + + + widgets.input-widgets.group-title + + +
+
+
+ widgets.input-widgets.fields-alignment +
+ + widgets.input-widgets.fields-alignment + + + {{ 'widgets.input-widgets.fields-alignment-row' | translate }} + + + {{ 'widgets.input-widgets.fields-alignment-column' | translate }} + + + + + widgets.input-widgets.fields-in-row + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.ts new file mode 100644 index 0000000000..167b6c5f49 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component.ts @@ -0,0 +1,117 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-update-multiple-attributes-widget-settings', + templateUrl: './update-multiple-attributes-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateMultipleAttributesWidgetSettingsComponent extends WidgetSettingsComponent { + + updateMultipleAttributesWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateMultipleAttributesWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + widgetTitle: '', + showResultMessage: true, + showActionButtons: true, + updateAllValues: false, + saveButtonLabel: '', + resetButtonLabel: '', + showGroupTitle: false, + groupTitle: '', + fieldsAlignment: 'row', + fieldsInRow: 2 + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateMultipleAttributesWidgetSettingsForm = this.fb.group({ + + // General settings + + widgetTitle: [settings.widgetTitle, []], + showResultMessage: [settings.showResultMessage, []], + + // Action button settings + + showActionButtons: [settings.showActionButtons, []], + updateAllValues: [settings.updateAllValues, []], + saveButtonLabel: [settings.saveButtonLabel, []], + resetButtonLabel: [settings.resetButtonLabel, []], + + // Group settings + + showGroupTitle: [settings.showGroupTitle, []], + groupTitle: [settings.groupTitle, []], + + // Fields alignment + + fieldsAlignment: [settings.fieldsAlignment, []], + fieldsInRow: [settings.fieldsInRow, [Validators.min(1)]], + }); + } + + protected validatorTriggers(): string[] { + return ['showActionButtons', 'showGroupTitle', 'fieldsAlignment']; + } + + protected updateValidators(emitEvent: boolean) { + const showActionButtons: boolean = this.updateMultipleAttributesWidgetSettingsForm.get('showActionButtons').value; + const showGroupTitle: boolean = this.updateMultipleAttributesWidgetSettingsForm.get('showGroupTitle').value; + const fieldsAlignment: string = this.updateMultipleAttributesWidgetSettingsForm.get('fieldsAlignment').value; + + if (showActionButtons) { + this.updateMultipleAttributesWidgetSettingsForm.get('updateAllValues').enable(); + this.updateMultipleAttributesWidgetSettingsForm.get('saveButtonLabel').enable(); + this.updateMultipleAttributesWidgetSettingsForm.get('resetButtonLabel').enable(); + } else { + this.updateMultipleAttributesWidgetSettingsForm.get('updateAllValues').disable(); + this.updateMultipleAttributesWidgetSettingsForm.get('saveButtonLabel').disable(); + this.updateMultipleAttributesWidgetSettingsForm.get('resetButtonLabel').disable(); + } + if (showGroupTitle) { + this.updateMultipleAttributesWidgetSettingsForm.get('groupTitle').enable(); + } else { + this.updateMultipleAttributesWidgetSettingsForm.get('groupTitle').disable(); + } + if (fieldsAlignment === 'row') { + this.updateMultipleAttributesWidgetSettingsForm.get('fieldsInRow').enable(); + } else { + this.updateMultipleAttributesWidgetSettingsForm.get('fieldsInRow').disable(); + } + this.updateMultipleAttributesWidgetSettingsForm.get('updateAllValues').updateValueAndValidity({emitEvent}); + this.updateMultipleAttributesWidgetSettingsForm.get('saveButtonLabel').updateValueAndValidity({emitEvent}); + this.updateMultipleAttributesWidgetSettingsForm.get('resetButtonLabel').updateValueAndValidity({emitEvent}); + this.updateMultipleAttributesWidgetSettingsForm.get('groupTitle').updateValueAndValidity({emitEvent}); + this.updateMultipleAttributesWidgetSettingsForm.get('fieldsInRow').updateValueAndValidity({emitEvent}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.html new file mode 100644 index 0000000000..f80d319dab --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.html @@ -0,0 +1,36 @@ + + +
+ + +
+ widgets.input-widgets.text-field-settings +
+ + widgets.input-widgets.min-length + + + + widgets.input-widgets.max-length + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.ts new file mode 100644 index 0000000000..13dd1ec453 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component.ts @@ -0,0 +1,77 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { deepClone } from '@core/utils'; +import { + updateAttributeGeneralDefaultSettings +} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component'; + +@Component({ + selector: 'tb-update-string-attribute-widget-settings', + templateUrl: './update-string-attribute-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class UpdateStringAttributeWidgetSettingsComponent extends WidgetSettingsComponent { + + updateStringAttributeWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.updateStringAttributeWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...updateAttributeGeneralDefaultSettings(), + minLength: null, + maxLength: null, + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.updateStringAttributeWidgetSettingsForm = this.fb.group({ + updateAttributeGeneralSettings: [settings.updateAttributeGeneralSettings, []], + minLength: [settings.minLength, [Validators.min(0)]], + maxLength: [settings.maxLength, [Validators.min(1)]] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const updateAttributeGeneralSettings = deepClone(settings, ['minLength', 'maxLength']); + return { + updateAttributeGeneralSettings, + minLength: settings.minLength, + maxLength: settings.maxLength + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + ...settings.updateAttributeGeneralSettings, + minLength: settings.minLength, + maxLength: settings.maxLength + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.html new file mode 100644 index 0000000000..3f480cc347 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.html @@ -0,0 +1,199 @@ + +
+
+ widgets.maps.circle-settings + + + + + {{ 'widgets.maps.show-circle' | translate }} + + + + widget-config.advanced-settings + + + + + + + {{ 'widgets.maps.enable-circle-edit' | translate }} + +
+ widgets.maps.circle-label + + + + + {{ 'widgets.maps.show-circle-label' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.use-circle-label-function' | translate }} + + + + + + + +
+
+ widgets.maps.circle-tooltip + + + + + {{ 'widgets.maps.show-circle-tooltip' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.maps.show-tooltip-action + + + {{showTooltipActionTranslations.get(action) | translate}} + + + + + {{ 'widgets.maps.auto-close-circle-tooltips' | translate }} + + + {{ 'widgets.maps.use-circle-tooltip-function' | translate }} + + + + + + + +
+
+ widgets.maps.circle-fill-color +
+ + + + widgets.maps.circle-fill-color-opacity + + +
+ + + + + {{ 'widgets.maps.use-circle-fill-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.maps.circle-stroke +
+ + + + widgets.maps.stroke-opacity + + + + widgets.maps.stroke-weight + + +
+ + + + + {{ 'widgets.maps.use-circle-stroke-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.ts new file mode 100644 index 0000000000..10ee46ce12 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/circle-settings.component.ts @@ -0,0 +1,243 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + CircleSettings, + ShowTooltipAction, + showTooltipActionTranslationMap +} from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; +import { Widget } from '@shared/models/widget.models'; + +@Component({ + selector: 'tb-circle-settings', + templateUrl: './circle-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => CircleSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => CircleSettingsComponent), + multi: true + } + ] +}) +export class CircleSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + widget: Widget; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: CircleSettings; + + private propagateChange = null; + + public circleSettingsFormGroup: FormGroup; + + showTooltipActions = Object.values(ShowTooltipAction); + + showTooltipActionTranslations = showTooltipActionTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.circleSettingsFormGroup = this.fb.group({ + showCircle: [null, []], + circleKeyName: [null, [Validators.required]], + editableCircle: [null, []], + showCircleLabel: [null, []], + useCircleLabelFunction: [null, []], + circleLabel: [null, []], + circleLabelFunction: [null, []], + showCircleTooltip: [null, []], + showCircleTooltipAction: [null, []], + autoCloseCircleTooltip: [null, []], + useCircleTooltipFunction: [null, []], + circleTooltipPattern: [null, []], + circleTooltipFunction: [null, []], + circleFillColor: [null, []], + circleFillColorOpacity: [null, [Validators.min(0), Validators.max(1)]], + useCircleFillColorFunction: [null, []], + circleFillColorFunction: [null, []], + circleStrokeColor: [null, []], + circleStrokeOpacity: [null, [Validators.min(0), Validators.max(1)]], + circleStrokeWeight: [null, [Validators.min(0)]], + useCircleStrokeColorFunction: [null, []], + circleStrokeColorFunction: [null, []] + }); + this.circleSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.circleSettingsFormGroup.get('showCircle').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('showCircleLabel').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('useCircleLabelFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('showCircleTooltip').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('useCircleTooltipFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('useCircleFillColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.circleSettingsFormGroup.get('useCircleStrokeColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.circleSettingsFormGroup.disable({emitEvent: false}); + } else { + this.circleSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: CircleSettings): void { + this.modelValue = value; + this.circleSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.circleSettingsFormGroup.valid ? null : { + circleSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: CircleSettings = this.circleSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showCircle: boolean = this.circleSettingsFormGroup.get('showCircle').value; + const showCircleLabel: boolean = this.circleSettingsFormGroup.get('showCircleLabel').value; + const useCircleLabelFunction: boolean = this.circleSettingsFormGroup.get('useCircleLabelFunction').value; + const showCircleTooltip: boolean = this.circleSettingsFormGroup.get('showCircleTooltip').value; + const useCircleTooltipFunction: boolean = this.circleSettingsFormGroup.get('useCircleTooltipFunction').value; + const useCircleFillColorFunction: boolean = this.circleSettingsFormGroup.get('useCircleFillColorFunction').value; + const useCircleStrokeColorFunction: boolean = this.circleSettingsFormGroup.get('useCircleStrokeColorFunction').value; + + this.circleSettingsFormGroup.disable({emitEvent: false}); + this.circleSettingsFormGroup.get('showCircle').enable({emitEvent: false}); + + if (showCircle) { + this.circleSettingsFormGroup.get('circleKeyName').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('editableCircle').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('showCircleLabel').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('showCircleTooltip').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleFillColor').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleFillColorOpacity').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('useCircleFillColorFunction').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleStrokeColor').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleStrokeOpacity').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleStrokeWeight').enable({emitEvent: false}); + this.circleSettingsFormGroup.get('useCircleStrokeColorFunction').enable({emitEvent: false}); + if (showCircleLabel) { + this.circleSettingsFormGroup.get('useCircleLabelFunction').enable({emitEvent: false}); + if (useCircleLabelFunction) { + this.circleSettingsFormGroup.get('circleLabelFunction').enable({emitEvent}); + this.circleSettingsFormGroup.get('circleLabel').disable({emitEvent}); + } else { + this.circleSettingsFormGroup.get('circleLabelFunction').disable({emitEvent}); + this.circleSettingsFormGroup.get('circleLabel').enable({emitEvent}); + } + } else { + this.circleSettingsFormGroup.get('useCircleLabelFunction').disable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleLabelFunction').disable({emitEvent}); + this.circleSettingsFormGroup.get('circleLabel').disable({emitEvent}); + } + if (showCircleTooltip) { + this.circleSettingsFormGroup.get('showCircleTooltipAction').enable({emitEvent}); + this.circleSettingsFormGroup.get('autoCloseCircleTooltip').enable({emitEvent}); + this.circleSettingsFormGroup.get('useCircleTooltipFunction').enable({emitEvent: false}); + if (useCircleTooltipFunction) { + this.circleSettingsFormGroup.get('circleTooltipFunction').enable({emitEvent}); + this.circleSettingsFormGroup.get('circleTooltipPattern').disable({emitEvent}); + } else { + this.circleSettingsFormGroup.get('circleTooltipFunction').disable({emitEvent}); + this.circleSettingsFormGroup.get('circleTooltipPattern').enable({emitEvent}); + } + } else { + this.circleSettingsFormGroup.get('showCircleTooltipAction').disable({emitEvent}); + this.circleSettingsFormGroup.get('autoCloseCircleTooltip').disable({emitEvent}); + this.circleSettingsFormGroup.get('useCircleTooltipFunction').disable({emitEvent: false}); + this.circleSettingsFormGroup.get('circleTooltipFunction').disable({emitEvent}); + this.circleSettingsFormGroup.get('circleTooltipPattern').disable({emitEvent}); + } + if (useCircleFillColorFunction) { + this.circleSettingsFormGroup.get('circleFillColorFunction').enable({emitEvent}); + } else { + this.circleSettingsFormGroup.get('circleFillColorFunction').disable({emitEvent}); + } + if (useCircleStrokeColorFunction) { + this.circleSettingsFormGroup.get('circleStrokeColorFunction').enable({emitEvent}); + } else { + this.circleSettingsFormGroup.get('circleStrokeColorFunction').disable({emitEvent}); + } + } + this.circleSettingsFormGroup.updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.html new file mode 100644 index 0000000000..8f199654e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.html @@ -0,0 +1,93 @@ + +
+
+ widgets.maps.common-map-settings +
+ + + + + + + + +
+ + + + widget-config.advanced-settings + + + +
+ + widgets.maps.default-map-zoom-level + + + + widgets.maps.default-map-center-position + + +
+
+
+ + {{ 'widgets.maps.disable-scroll-zooming' | translate }} + + + {{ 'widgets.maps.disable-zoom-control-buttons' | translate }} + + + {{ 'widgets.maps.fit-map-bounds' | translate }} + +
+
+ + {{ 'widgets.maps.use-default-map-center-position' | translate }} + +
+
+ + widgets.maps.entities-limit + + +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.ts new file mode 100644 index 0000000000..12a2e8cef7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/common-map-settings.component.ts @@ -0,0 +1,178 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { CommonMapSettings, MapProviders } from '@home/components/widget/lib/maps/map-models'; +import { Widget } from '@shared/models/widget.models'; + +@Component({ + selector: 'tb-common-map-settings', + templateUrl: './common-map-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => CommonMapSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => CommonMapSettingsComponent), + multi: true + } + ] +}) +export class CommonMapSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator, OnChanges { + + @Input() + disabled: boolean; + + @Input() + provider: MapProviders; + + @Input() + widget: Widget; + + mapProvider = MapProviders; + + private modelValue: CommonMapSettings; + + private propagateChange = null; + + public commonMapSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.commonMapSettingsFormGroup = this.fb.group({ + latKeyName: [null, [Validators.required]], + lngKeyName: [null, [Validators.required]], + xPosKeyName: [null, [Validators.required]], + yPosKeyName: [null, [Validators.required]], + defaultZoomLevel: [null, [Validators.min(0), Validators.max(20)]], + defaultCenterPosition: [null, []], + disableScrollZooming: [null, []], + disableZoomControl: [null, []], + fitMapBounds: [null, []], + useDefaultCenterPosition: [null, []], + mapPageSize: [null, [Validators.min(1), Validators.required]] + }); + this.commonMapSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.updateValidators(false); + } + + ngOnChanges(changes: SimpleChanges): void { + for (const propName of Object.keys(changes)) { + const change = changes[propName]; + if (!change.firstChange && change.currentValue !== change.previousValue) { + if (propName === 'provider') { + this.updateValidators(false); + } + } + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.commonMapSettingsFormGroup.disable({emitEvent: false}); + } else { + this.commonMapSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: CommonMapSettings): void { + this.modelValue = value; + this.commonMapSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.commonMapSettingsFormGroup.valid ? null : { + commonMapSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: CommonMapSettings = this.commonMapSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + if (this.provider === MapProviders.image) { + this.commonMapSettingsFormGroup.get('latKeyName').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('lngKeyName').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('defaultZoomLevel').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('useDefaultCenterPosition').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('defaultCenterPosition').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('fitMapBounds').disable({emitEvent}); + + this.commonMapSettingsFormGroup.get('xPosKeyName').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('yPosKeyName').enable({emitEvent}); + } else { + this.commonMapSettingsFormGroup.get('latKeyName').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('lngKeyName').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('defaultZoomLevel').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('useDefaultCenterPosition').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('defaultCenterPosition').enable({emitEvent}); + this.commonMapSettingsFormGroup.get('fitMapBounds').enable({emitEvent}); + + + this.commonMapSettingsFormGroup.get('xPosKeyName').disable({emitEvent}); + this.commonMapSettingsFormGroup.get('yPosKeyName').disable({emitEvent}); + } + this.commonMapSettingsFormGroup.get('latKeyName').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('lngKeyName').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('xPosKeyName').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('yPosKeyName').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('defaultZoomLevel').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('useDefaultCenterPosition').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('defaultCenterPosition').updateValueAndValidity({emitEvent: false}); + this.commonMapSettingsFormGroup.get('fitMapBounds').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.html new file mode 100644 index 0000000000..4f7623f2f7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.html @@ -0,0 +1,39 @@ + + + {{ label | translate }} + + + + + + + + diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.ts new file mode 100644 index 0000000000..5c31d495d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/datasources-key-autocomplete.component.ts @@ -0,0 +1,152 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable, of } from 'rxjs'; +import { map, mergeMap } from 'rxjs/operators'; +import { Datasource } from '@shared/models/widget.models'; +import { EntityService } from '@core/http/entity.service'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; + +@Component({ + selector: 'tb-datasources-key-autocomplete', + templateUrl: './datasources-key-autocomplete.component.html', + styleUrls: [], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => DatasourcesKeyAutocompleteComponent), + multi: true + } + ] +}) +export class DatasourcesKeyAutocompleteComponent extends PageComponent implements OnInit, ControlValueAccessor { + + @ViewChild('keyInput') keyInput: ElementRef; + + @Input() + disabled: boolean; + + @Input() + datasources: Array; + + @Input() + label = 'entity.key-name'; + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + private modelValue: string; + + private propagateChange = null; + + public keyFormGroup: FormGroup; + + filteredKeys: Observable>; + keySearchText = ''; + + constructor(protected store: Store, + private translate: TranslateService, + private entityService: EntityService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.keyFormGroup = this.fb.group({ + key: [null, this.required ? [Validators.required] : []] + }); + this.keyFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + + this.filteredKeys = this.keyFormGroup.get('key').valueChanges + .pipe( + map(value => value ? value : ''), + mergeMap(name => this.fetchKeys(name) ) + ); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.keyFormGroup.disable({emitEvent: false}); + } else { + this.keyFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: string): void { + this.modelValue = value; + this.keyFormGroup.patchValue( + {key: value}, {emitEvent: false} + ); + } + + clearKey() { + this.keyFormGroup.get('key').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.keyInput.nativeElement.blur(); + this.keyInput.nativeElement.focus(); + }, 0); + } + + onFocus() { + this.keyFormGroup.get('key').updateValueAndValidity({onlySelf: true, emitEvent: true}); + } + + private updateModel() { + this.modelValue = this.keyFormGroup.get('key').value; + this.propagateChange(this.modelValue); + } + + private fetchKeys(searchText?: string): Observable> { + this.keySearchText = searchText; + const dataKeyFilter = this.createKeyFilter(this.keySearchText); + return of(this.allKeys()).pipe( + map(name => name.filter(dataKeyFilter)) + ); + } + + private createKeyFilter(query: string): (key: string) => boolean { + const lowercaseQuery = query.toLowerCase(); + return key => key.toLowerCase().startsWith(lowercaseQuery); + } + + private allKeys(): string[] { + const allDataKeys = (this.datasources || []).map(ds => ds.dataKeys) + .reduce((accumulator, value) => accumulator.concat(value), []).map(dataKey => dataKey.label); + return [...new Set(allDataKeys)].sort((a, b) => a.localeCompare(b)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.html new file mode 100644 index 0000000000..7d718d4dcd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.html @@ -0,0 +1,31 @@ + +
+ + widgets.maps.google-maps-api-key + + + + widgets.maps.default-map-type + + + {{googleMapTypeTranslations.get(type) | translate}} + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.ts new file mode 100644 index 0000000000..d48c10bbd9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/google-map-provider-settings.component.ts @@ -0,0 +1,122 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + GoogleMapProviderSettings, + GoogleMapType, + googleMapTypeProviderTranslationMap +} from '@home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-google-map-provider-settings', + templateUrl: './google-map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => GoogleMapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => GoogleMapProviderSettingsComponent), + multi: true + } + ] +}) +export class GoogleMapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: GoogleMapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + googleMapTypes = Object.values(GoogleMapType); + + googleMapTypeTranslations = googleMapTypeProviderTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.providerSettingsFormGroup = this.fb.group({ + gmApiKey: [null, [Validators.required]], + gmDefaultMapType: [null, [Validators.required]] + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: GoogleMapProviderSettings): void { + this.modelValue = value; + this.providerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + googleMapProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: GoogleMapProviderSettings = this.providerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.html new file mode 100644 index 0000000000..530a3b615e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.html @@ -0,0 +1,40 @@ + +
+ + widgets.maps.map-layer + + + {{hereMapProviderTranslations.get(provider) | translate}} + + + +
+
+ widgets.maps.credentials + + widgets.maps.here-app-id + + + + widgets.maps.here-app-code + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.ts new file mode 100644 index 0000000000..6bf6c32d10 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/here-map-provider-settings.component.ts @@ -0,0 +1,125 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + HereMapProvider, + HereMapProviderSettings, + hereMapProviderTranslationMap +} from '@home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-here-map-provider-settings', + templateUrl: './here-map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => HereMapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => HereMapProviderSettingsComponent), + multi: true + } + ] +}) +export class HereMapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: HereMapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + hereMapProviders = Object.values(HereMapProvider); + + hereMapProviderTranslations = hereMapProviderTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.providerSettingsFormGroup = this.fb.group({ + mapProviderHere: [null, [Validators.required]], + credentials: this.fb.group({ + app_id: [null, [Validators.required]], + app_code: [null, [Validators.required]] + }) + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: HereMapProviderSettings): void { + this.modelValue = value; + this.providerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + hereMapProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: HereMapProviderSettings = this.providerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.html new file mode 100644 index 0000000000..a8c5318142 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.html @@ -0,0 +1,71 @@ + +
+ + +
+ widgets.maps.image-map-background-from-entity-attribute +
+ + widgets.maps.image-url-source-entity-alias + + + + + + + + + + widgets.maps.image-url-source-entity-attribute + + + + + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.ts new file mode 100644 index 0000000000..c9a6947b43 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/image-map-provider-settings.component.ts @@ -0,0 +1,253 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { ImageMapProviderSettings } from '@home/components/widget/lib/maps/map-models'; +import { IAliasController } from '@core/api/widget-api.models'; +import { Observable, of } from 'rxjs'; +import { catchError, map, mergeMap, publishReplay, refCount, startWith, tap } from 'rxjs/operators'; +import { DataKey } from '@shared/models/widget.models'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { EntityService } from '@core/http/entity.service'; + +@Component({ + selector: 'tb-image-map-provider-settings', + templateUrl: './image-map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => ImageMapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => ImageMapProviderSettingsComponent), + multi: true + } + ] +}) +export class ImageMapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @ViewChild('entityAliasInput') entityAliasInput: ElementRef; + + @ViewChild('keyInput') keyInput: ElementRef; + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + private modelValue: ImageMapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + filteredEntityAliases: Observable>; + aliasSearchText = ''; + + filteredKeys: Observable>; + keySearchText = ''; + + private latestKeySearchResult: Array = null; + private keysFetchObservable$: Observable> = null; + + private entityAliasList: Array = []; + + constructor(protected store: Store, + private translate: TranslateService, + private entityService: EntityService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.providerSettingsFormGroup = this.fb.group({ + mapImageUrl: [null, []], + imageEntityAlias: [null, []], + imageUrlAttribute: [null, []] + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + + this.filteredEntityAliases = this.providerSettingsFormGroup.get('imageEntityAlias').valueChanges + .pipe( + tap((value) => { + if (this.modelValue?.imageEntityAlias !== value) { + this.latestKeySearchResult = null; + this.keysFetchObservable$ = null; + this.providerSettingsFormGroup.get('imageUrlAttribute').setValue(this.providerSettingsFormGroup.get('imageUrlAttribute').value); + } + }), + map(value => value ? value : ''), + mergeMap(name => this.fetchEntityAliases(name) ) + ); + + this.filteredKeys = this.providerSettingsFormGroup.get('imageUrlAttribute').valueChanges + .pipe( + map(value => value ? value : ''), + mergeMap(name => this.fetchKeys(name) ) + ); + + if (this.aliasController) { + const entityAliases = this.aliasController.getEntityAliases(); + for (const aliasId of Object.keys(entityAliases)) { + this.entityAliasList.push(entityAliases[aliasId].alias); + } + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: ImageMapProviderSettings): void { + this.modelValue = value; + this.providerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + imageMapProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: ImageMapProviderSettings = this.providerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + clearEntityAlias() { + this.providerSettingsFormGroup.get('imageEntityAlias').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.entityAliasInput.nativeElement.blur(); + this.entityAliasInput.nativeElement.focus(); + }, 0); + } + + onEntityAliasFocus() { + this.providerSettingsFormGroup.get('imageEntityAlias').updateValueAndValidity({onlySelf: true, emitEvent: true}); + } + + clearKey() { + this.providerSettingsFormGroup.get('imageUrlAttribute').patchValue(null, {emitEvent: true}); + setTimeout(() => { + this.keyInput.nativeElement.blur(); + this.keyInput.nativeElement.focus(); + }, 0); + } + + onKeyFocus() { + this.providerSettingsFormGroup.get('imageUrlAttribute').updateValueAndValidity({onlySelf: true, emitEvent: true}); + } + + private fetchEntityAliases(searchText?: string): Observable> { + this.aliasSearchText = searchText; + let result = this.entityAliasList; + if (searchText && searchText.length) { + result = this.entityAliasList.filter((entityAlias) => entityAlias.toLowerCase().includes(searchText.toLowerCase())); + } + return of(result); + } + + private fetchKeys(searchText?: string): Observable> { + if (this.keySearchText !== searchText || this.latestKeySearchResult === null) { + this.keySearchText = searchText; + const dataKeyFilter = this.createKeyFilter(this.keySearchText); + return this.getKeys().pipe( + map(name => name.filter(dataKeyFilter)), + tap(res => this.latestKeySearchResult = res) + ); + } + return of(this.latestKeySearchResult); + } + + private getKeys() { + if (this.keysFetchObservable$ === null) { + let fetchObservable: Observable>; + let entityAliasId: string; + const entityAlias: string = this.providerSettingsFormGroup.get('imageEntityAlias').value; + if (entityAlias && this.aliasController) { + entityAliasId = this.aliasController.getEntityAliasId(entityAlias); + } + if (entityAliasId) { + const dataKeyTypes = [DataKeyType.attribute]; + fetchObservable = this.fetchEntityKeys(entityAliasId, dataKeyTypes); + } else { + fetchObservable = of([]); + } + this.keysFetchObservable$ = fetchObservable.pipe( + map((dataKeys) => dataKeys.map((dataKey) => dataKey.name)), + publishReplay(1), + refCount() + ); + } + return this.keysFetchObservable$; + } + + private fetchEntityKeys(entityAliasId: string, dataKeyTypes: Array): Observable> { + return this.aliasController.getAliasInfo(entityAliasId).pipe( + mergeMap((aliasInfo) => { + return this.entityService.getEntityKeysByEntityFilter( + aliasInfo.entityFilter, + dataKeyTypes, + {ignoreLoading: true, ignoreErrors: true} + ).pipe( + catchError(() => of([])) + ); + }), + catchError(() => of([] as Array)) + ); + } + + private createKeyFilter(query: string): (key: string) => boolean { + const lowercaseQuery = query.toLowerCase(); + return key => key.toLowerCase().startsWith(lowercaseQuery); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.html new file mode 100644 index 0000000000..9dfa9f9db8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.html @@ -0,0 +1,52 @@ + +
+
+ widgets.maps.editor-settings + + {{ 'widgets.maps.enable-snapping' | translate }} + + + {{ 'widgets.maps.init-draggable-mode' | translate }} + + + + + + {{ 'widgets.maps.hide-all-edit-buttons' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.hide-draw-buttons' | translate }} + + + {{ 'widgets.maps.hide-edit-buttons' | translate }} + + + {{ 'widgets.maps.hide-remove-button' | translate }} + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.ts new file mode 100644 index 0000000000..02d47a686d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-editor-settings.component.ts @@ -0,0 +1,141 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { MapEditorSettings } from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-map-editor-settings', + templateUrl: './map-editor-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MapEditorSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => MapEditorSettingsComponent), + multi: true + } + ] +}) +export class MapEditorSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: MapEditorSettings; + + private propagateChange = null; + + public mapEditorSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.mapEditorSettingsFormGroup = this.fb.group({ + snappable: [null, []], + initDragMode: [null, []], + hideAllControlButton: [null, []], + hideDrawControlButton: [null, []], + hideEditControlButton: [null, []], + hideRemoveControlButton: [null, []], + }); + this.mapEditorSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.mapEditorSettingsFormGroup.get('hideAllControlButton').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.mapEditorSettingsFormGroup.disable({emitEvent: false}); + } else { + this.mapEditorSettingsFormGroup.enable({emitEvent: false}); + this.updateValidators(false); + } + } + + writeValue(value: MapEditorSettings): void { + this.modelValue = value; + this.mapEditorSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.mapEditorSettingsFormGroup.valid ? null : { + mapEditorSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: MapEditorSettings = this.mapEditorSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const hideAllControlButton: boolean = this.mapEditorSettingsFormGroup.get('hideAllControlButton').value; + if (hideAllControlButton) { + this.mapEditorSettingsFormGroup.get('hideDrawControlButton').disable({emitEvent}); + this.mapEditorSettingsFormGroup.get('hideEditControlButton').disable({emitEvent}); + this.mapEditorSettingsFormGroup.get('hideRemoveControlButton').disable({emitEvent}); + } else { + this.mapEditorSettingsFormGroup.get('hideDrawControlButton').enable({emitEvent}); + this.mapEditorSettingsFormGroup.get('hideEditControlButton').enable({emitEvent}); + this.mapEditorSettingsFormGroup.get('hideRemoveControlButton').enable({emitEvent}); + } + this.mapEditorSettingsFormGroup.get('hideDrawControlButton').updateValueAndValidity({emitEvent: false}); + this.mapEditorSettingsFormGroup.get('hideEditControlButton').updateValueAndValidity({emitEvent: false}); + this.mapEditorSettingsFormGroup.get('hideRemoveControlButton').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.html new file mode 100644 index 0000000000..9eef35e732 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.html @@ -0,0 +1,51 @@ + +
+
+ widgets.maps.map-provider-settings + + widgets.maps.map-provider + + + {{mapProviderTranslations.get(provider) | translate}} + + + + + + + + + + + + + +
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.ts new file mode 100644 index 0000000000..51e95ec42b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-provider-settings.component.ts @@ -0,0 +1,204 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + GoogleMapProviderSettings, + HereMapProviderSettings, + ImageMapProviderSettings, + MapProviders, + MapProviderSettings, + mapProviderTranslationMap, + OpenStreetMapProviderSettings, + TencentMapProviderSettings +} from '@home/components/widget/lib/maps/map-models'; +import { extractType } from '@core/utils'; +import { keys } from 'ts-transformer-keys'; +import { IAliasController } from '@core/api/widget-api.models'; + +@Component({ + selector: 'tb-map-provider-settings', + templateUrl: './map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => MapProviderSettingsComponent), + multi: true + } + ] +}) +export class MapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + aliasController: IAliasController; + + @Input() + disabled: boolean; + + @Input() + ignoreImageMap = false; + + private modelValue: MapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + mapProviders = Object.values(MapProviders); + + mapProvider = MapProviders; + + mapProviderTranslations = mapProviderTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + if (this.ignoreImageMap) { + this.mapProviders = this.mapProviders.filter((provider) => provider !== MapProviders.image); + } + this.providerSettingsFormGroup = this.fb.group({ + provider: [null, [Validators.required]], + googleProviderSettings: [null, []], + openstreetProviderSettings: [null, []], + hereProviderSettings: [null, []], + imageMapProviderSettings: [null, []], + tencentMapProviderSettings: [null, []] + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.providerSettingsFormGroup.get('provider').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: MapProviderSettings): void { + this.modelValue = value; + const provider = value?.provider; + const googleProviderSettings = extractType(value, keys()); + const openstreetProviderSettings = extractType(value, keys()); + const hereProviderSettings = extractType(value, keys()); + const imageMapProviderSettings = extractType(value, keys()); + const tencentMapProviderSettings = extractType(value, keys()); + this.providerSettingsFormGroup.patchValue( + { + provider, + googleProviderSettings, + openstreetProviderSettings, + hereProviderSettings, + imageMapProviderSettings, + tencentMapProviderSettings + }, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + mapProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: { + provider: MapProviders, + googleProviderSettings: GoogleMapProviderSettings, + openstreetProviderSettings: OpenStreetMapProviderSettings, + hereProviderSettings: HereMapProviderSettings, + imageMapProviderSettings: ImageMapProviderSettings, + tencentMapProviderSettings: TencentMapProviderSettings + } = this.providerSettingsFormGroup.value; + this.modelValue = { + provider: value.provider, + ...value.googleProviderSettings, + ...value.openstreetProviderSettings, + ...value.hereProviderSettings, + ...value.imageMapProviderSettings, + ...value.tencentMapProviderSettings + }; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const provider: MapProviders = this.providerSettingsFormGroup.get('provider').value; + this.providerSettingsFormGroup.disable({emitEvent: false}); + this.providerSettingsFormGroup.get('provider').enable({emitEvent: false}); + switch (provider) { + case MapProviders.google: + this.providerSettingsFormGroup.get('googleProviderSettings').enable({emitEvent}); + this.providerSettingsFormGroup.get('googleProviderSettings').updateValueAndValidity({emitEvent: false}); + break; + case MapProviders.openstreet: + this.providerSettingsFormGroup.get('openstreetProviderSettings').enable({emitEvent}); + this.providerSettingsFormGroup.get('openstreetProviderSettings').updateValueAndValidity({emitEvent: false}); + break; + case MapProviders.here: + this.providerSettingsFormGroup.get('hereProviderSettings').enable({emitEvent}); + this.providerSettingsFormGroup.get('hereProviderSettings').updateValueAndValidity({emitEvent: false}); + break; + case MapProviders.image: + this.providerSettingsFormGroup.get('imageMapProviderSettings').enable({emitEvent}); + this.providerSettingsFormGroup.get('imageMapProviderSettings').updateValueAndValidity({emitEvent: false}); + break; + case MapProviders.tencent: + this.providerSettingsFormGroup.get('tencentMapProviderSettings').enable({emitEvent}); + this.providerSettingsFormGroup.get('tencentMapProviderSettings').updateValueAndValidity({emitEvent: false}); + break; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.html new file mode 100644 index 0000000000..74a96d9dc7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.html @@ -0,0 +1,53 @@ + +
+ + + + + + + + + + + + + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.ts new file mode 100644 index 0000000000..b2652d9c69 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-settings.component.ts @@ -0,0 +1,217 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + CircleSettings, + CommonMapSettings, + MapEditorSettings, + MapProviders, + MapProviderSettings, + MarkerClusteringSettings, + MarkersSettings, + PolygonSettings, + PolylineSettings, + UnitedMapSettings +} from '@home/components/widget/lib/maps/map-models'; +import { extractType } from '@core/utils'; +import { keys } from 'ts-transformer-keys'; +import { IAliasController } from '@core/api/widget-api.models'; +import { Widget } from '@shared/models/widget.models'; + +@Component({ + selector: 'tb-map-settings', + templateUrl: './map-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MapSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => MapSettingsComponent), + multi: true + } + ] +}) +export class MapSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + @Input() + widget: Widget; + + @Input() + routeMap = false; + + mapProvider = MapProviders; + + private modelValue: UnitedMapSettings; + + private propagateChange = null; + + public mapSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.mapSettingsFormGroup = this.fb.group({ + mapProviderSettings: [null, []], + commonMapSettings: [null, []], + markersSettings: [null, []], + polygonSettings: [null, []], + circleSettings: [null, []], + }); + if (this.routeMap) { + this.mapSettingsFormGroup.addControl('routeMapSettings', this.fb.control(null, [])); + } else { + this.mapSettingsFormGroup.addControl('markerClusteringSettings', this.fb.control(null, [])); + } + this.mapSettingsFormGroup.addControl('mapEditorSettings', this.fb.control(null, [])); + this.mapSettingsFormGroup.get('mapProviderSettings').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.mapSettingsFormGroup.get('markersSettings').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.mapSettingsFormGroup.get('polygonSettings').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.mapSettingsFormGroup.get('circleSettings').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.mapSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.mapSettingsFormGroup.disable({emitEvent: false}); + } else { + this.mapSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: UnitedMapSettings): void { + this.modelValue = value; + const mapProviderSettings = extractType(value, keys()); + const commonMapSettings = extractType(value, keys()); + const markersSettings = extractType(value, keys()); + const polygonSettings = extractType(value, keys()); + const circleSettings = extractType(value, keys()); + const mapEditorSettings = extractType(value, keys()); + const formValue = { + mapProviderSettings, + commonMapSettings, + markersSettings, + polygonSettings, + circleSettings, + mapEditorSettings + } as any; + if (this.routeMap) { + formValue.routeMapSettings = extractType(value, ['strokeWeight', 'strokeOpacity']); + } else { + formValue.markerClusteringSettings = extractType(value, keys()); + } + this.mapSettingsFormGroup.patchValue( formValue, {emitEvent: false} ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.mapSettingsFormGroup.valid ? null : { + mapSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value = this.mapSettingsFormGroup.value; + this.modelValue = { + ...value.mapProviderSettings, + ...value.commonMapSettings, + ...value.markersSettings, + ...value.polygonSettings, + ...value.circleSettings, + ...value.mapEditorSettings + }; + if (this.routeMap) { + this.modelValue = {...this.modelValue, ...value.routeMapSettings}; + } else { + this.modelValue = {...this.modelValue, ...value.markerClusteringSettings}; + } + this.propagateChange(this.modelValue); + } + + displayEditorSettings(): boolean { + const markersSettings: MarkersSettings = this.mapSettingsFormGroup.get('markersSettings').value; + const polygonSettings: PolygonSettings = this.mapSettingsFormGroup.get('polygonSettings').value; + const circleSettings: CircleSettings = this.mapSettingsFormGroup.get('circleSettings').value; + return markersSettings?.draggableMarker || polygonSettings?.editablePolygon || circleSettings?.editableCircle; + } + + private updateValidators(emitEvent?: boolean): void { + const displayEditorSettings = this.displayEditorSettings(); + if (displayEditorSettings) { + this.mapSettingsFormGroup.get('mapEditorSettings').enable({emitEvent}); + } else { + this.mapSettingsFormGroup.get('mapEditorSettings').disable({emitEvent}); + } + if (!this.routeMap) { + const mapProviderSettings: MapProviderSettings = this.mapSettingsFormGroup.get('mapProviderSettings').value; + if (mapProviderSettings?.provider === MapProviders.image) { + this.mapSettingsFormGroup.get('markerClusteringSettings').disable({emitEvent}); + } else { + this.mapSettingsFormGroup.get('markerClusteringSettings').enable({emitEvent}); + } + this.mapSettingsFormGroup.get('markerClusteringSettings').updateValueAndValidity({emitEvent: false}); + } + this.mapSettingsFormGroup.get('mapEditorSettings').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.html new file mode 100644 index 0000000000..fa4807ea63 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.html @@ -0,0 +1,24 @@ + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.ts new file mode 100644 index 0000000000..01d4287bb9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/map-widget-settings.component.ts @@ -0,0 +1,63 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { defaultMapSettings } from 'src/app/modules/home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-map-widget-settings', + templateUrl: './map-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class MapWidgetSettingsComponent extends WidgetSettingsComponent { + + mapWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.mapWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...defaultMapSettings + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.mapWidgetSettingsForm = this.fb.group({ + mapSettings: [settings.mapSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + mapSettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.mapSettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.html new file mode 100644 index 0000000000..9ceb172090 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.html @@ -0,0 +1,70 @@ + +
+
+ widgets.maps.markers-clustering-settings + + + + + {{ 'widgets.maps.use-map-markers-clustering' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.zoom-on-cluster-click' | translate }} + +
+ + widgets.maps.max-cluster-zoom + + + + widgets.maps.max-cluster-radius-pixels + + +
+
+ + {{ 'widgets.maps.cluster-zoom-animation' | translate }} + + + {{ 'widgets.maps.show-markers-bounds-on-cluster-mouse-over' | translate }} + +
+ + {{ 'widgets.maps.spiderfy-max-zoom-level' | translate }} + +
+ widgets.maps.load-optimization + + {{ 'widgets.maps.cluster-chunked-loading' | translate }} + + + {{ 'widgets.maps.cluster-markers-lazy-load' | translate }} + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.ts new file mode 100644 index 0000000000..f1ca781bed --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/marker-clustering-settings.component.ts @@ -0,0 +1,141 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { MarkerClusteringSettings } from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-marker-clustering-settings', + templateUrl: './marker-clustering-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MarkerClusteringSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => MarkerClusteringSettingsComponent), + multi: true + } + ] +}) +export class MarkerClusteringSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: MarkerClusteringSettings; + + private propagateChange = null; + + public markerClusteringSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.markerClusteringSettingsFormGroup = this.fb.group({ + useClusterMarkers: [null, []], + zoomOnClick: [null, []], + maxZoom: [null, [Validators.min(0), Validators.max(18)]], + maxClusterRadius: [null, [Validators.min(0)]], + animate: [null, []], + spiderfyOnMaxZoom: [null, []], + showCoverageOnHover: [null, []], + chunkedLoading: [null, []], + removeOutsideVisibleBounds: [null, []] + }); + this.markerClusteringSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.markerClusteringSettingsFormGroup.get('useClusterMarkers').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.markerClusteringSettingsFormGroup.disable({emitEvent: false}); + } else { + this.markerClusteringSettingsFormGroup.enable({emitEvent: false}); + this.updateValidators(false); + } + } + + writeValue(value: MarkerClusteringSettings): void { + this.modelValue = value; + this.markerClusteringSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.markerClusteringSettingsFormGroup.valid ? null : { + markerClusteringSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: MarkerClusteringSettings = this.markerClusteringSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const useClusterMarkers: boolean = this.markerClusteringSettingsFormGroup.get('useClusterMarkers').value; + + this.markerClusteringSettingsFormGroup.disable({emitEvent: false}); + this.markerClusteringSettingsFormGroup.get('useClusterMarkers').enable({emitEvent: false}); + + if (useClusterMarkers) { + this.markerClusteringSettingsFormGroup.enable({emitEvent: false}); + } + this.markerClusteringSettingsFormGroup.updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.html new file mode 100644 index 0000000000..ea955f5f7f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.html @@ -0,0 +1,197 @@ + +
+
+ widgets.maps.markers-settings +
+ + widgets.maps.marker-offset-x + + + + widgets.maps.marker-offset-y + + +
+ + + + {{ 'widgets.maps.draggable-marker' | translate }} + +
+ widgets.maps.label + + + + + {{ 'widgets.maps.show-label' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.use-label-function' | translate }} + + + + + + + +
+
+ widgets.maps.tooltip + + + + + {{ 'widgets.maps.show-tooltip' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.maps.show-tooltip-action + + + {{showTooltipActionTranslations.get(action) | translate}} + + + + + {{ 'widgets.maps.auto-close-tooltips' | translate }} + + + {{ 'widgets.maps.use-tooltip-function' | translate }} + + + + + +
+ + widgets.maps.tooltip-offset-x + + + + widgets.maps.tooltip-offset-y + + +
+
+
+
+
+ widgets.maps.color + + + + + + + {{ 'widgets.maps.use-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.maps.marker-image + + + + + {{ 'widgets.maps.use-marker-image-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + widgets.maps.custom-marker-image-size + + + + + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.ts new file mode 100644 index 0000000000..f877372c40 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/markers-settings.component.ts @@ -0,0 +1,264 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + MapProviders, + MarkersSettings, ShowTooltipAction, showTooltipActionTranslationMap +} from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-markers-settings', + templateUrl: './markers-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MarkersSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => MarkersSettingsComponent), + multi: true + } + ] +}) +export class MarkersSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator, OnChanges { + + @Input() + disabled: boolean; + + @Input() + provider: MapProviders; + + mapProvider = MapProviders; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: MarkersSettings; + + private propagateChange = null; + + public markersSettingsFormGroup: FormGroup; + + showTooltipActions = Object.values(ShowTooltipAction); + + showTooltipActionTranslations = showTooltipActionTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.markersSettingsFormGroup = this.fb.group({ + markerOffsetX: [null, []], + markerOffsetY: [null, []], + posFunction: [null, []], + draggableMarker: [null, []], + showLabel: [null, []], + useLabelFunction: [null, []], + label: [null, []], + labelFunction: [null, []], + showTooltip: [null, []], + showTooltipAction: [null, []], + autocloseTooltip: [null, []], + useTooltipFunction: [null, []], + tooltipPattern: [null, []], + tooltipFunction: [null, []], + tooltipOffsetX: [null, []], + tooltipOffsetY: [null, []], + color: [null, []], + useColorFunction: [null, []], + colorFunction: [null, []], + useMarkerImageFunction: [null, []], + markerImage: [null, []], + markerImageSize: [null, [Validators.min(1)]], + markerImageFunction: [null, []], + markerImages: [null, []] + }); + this.markersSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.markersSettingsFormGroup.get('showLabel').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.markersSettingsFormGroup.get('useLabelFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.markersSettingsFormGroup.get('showTooltip').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.markersSettingsFormGroup.get('useTooltipFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.markersSettingsFormGroup.get('useColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.markersSettingsFormGroup.get('useMarkerImageFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + ngOnChanges(changes: SimpleChanges): void { + for (const propName of Object.keys(changes)) { + const change = changes[propName]; + if (!change.firstChange && change.currentValue !== change.previousValue) { + if (propName === 'provider') { + this.updateValidators(false); + } + } + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.markersSettingsFormGroup.disable({emitEvent: false}); + } else { + this.markersSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: MarkersSettings): void { + this.modelValue = value; + this.markersSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.markersSettingsFormGroup.valid ? null : { + markersSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: MarkersSettings = this.markersSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showLabel: boolean = this.markersSettingsFormGroup.get('showLabel').value; + const useLabelFunction: boolean = this.markersSettingsFormGroup.get('useLabelFunction').value; + const showTooltip: boolean = this.markersSettingsFormGroup.get('showTooltip').value; + const useTooltipFunction: boolean = this.markersSettingsFormGroup.get('useTooltipFunction').value; + const useColorFunction: boolean = this.markersSettingsFormGroup.get('useColorFunction').value; + const useMarkerImageFunction: boolean = this.markersSettingsFormGroup.get('useMarkerImageFunction').value; + if (this.provider === MapProviders.image) { + this.markersSettingsFormGroup.get('posFunction').enable({emitEvent}); + } else { + this.markersSettingsFormGroup.get('posFunction').disable({emitEvent}); + } + if (showLabel) { + this.markersSettingsFormGroup.get('useLabelFunction').enable({emitEvent: false}); + if (useLabelFunction) { + this.markersSettingsFormGroup.get('labelFunction').enable({emitEvent}); + this.markersSettingsFormGroup.get('label').disable({emitEvent}); + } else { + this.markersSettingsFormGroup.get('labelFunction').disable({emitEvent}); + this.markersSettingsFormGroup.get('label').enable({emitEvent}); + } + } else { + this.markersSettingsFormGroup.get('useLabelFunction').disable({emitEvent: false}); + this.markersSettingsFormGroup.get('labelFunction').disable({emitEvent}); + this.markersSettingsFormGroup.get('label').disable({emitEvent}); + } + if (showTooltip) { + this.markersSettingsFormGroup.get('showTooltipAction').enable({emitEvent}); + this.markersSettingsFormGroup.get('autocloseTooltip').enable({emitEvent}); + this.markersSettingsFormGroup.get('useTooltipFunction').enable({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipOffsetX').enable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipOffsetY').enable({emitEvent}); + if (useTooltipFunction) { + this.markersSettingsFormGroup.get('tooltipFunction').enable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipPattern').disable({emitEvent}); + } else { + this.markersSettingsFormGroup.get('tooltipFunction').disable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipPattern').enable({emitEvent}); + } + } else { + this.markersSettingsFormGroup.get('showTooltipAction').disable({emitEvent}); + this.markersSettingsFormGroup.get('autocloseTooltip').disable({emitEvent}); + this.markersSettingsFormGroup.get('useTooltipFunction').disable({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipFunction').disable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipPattern').disable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipOffsetX').disable({emitEvent}); + this.markersSettingsFormGroup.get('tooltipOffsetY').disable({emitEvent}); + } + if (useColorFunction) { + this.markersSettingsFormGroup.get('colorFunction').enable({emitEvent}); + } else { + this.markersSettingsFormGroup.get('colorFunction').disable({emitEvent}); + } + if (useMarkerImageFunction) { + this.markersSettingsFormGroup.get('markerImageFunction').enable({emitEvent}); + this.markersSettingsFormGroup.get('markerImages').enable({emitEvent}); + this.markersSettingsFormGroup.get('markerImage').disable({emitEvent}); + this.markersSettingsFormGroup.get('markerImageSize').disable({emitEvent}); + } else { + this.markersSettingsFormGroup.get('markerImageFunction').disable({emitEvent}); + this.markersSettingsFormGroup.get('markerImages').disable({emitEvent}); + this.markersSettingsFormGroup.get('markerImage').enable({emitEvent}); + this.markersSettingsFormGroup.get('markerImageSize').enable({emitEvent}); + } + this.markersSettingsFormGroup.get('posFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('useLabelFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('labelFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('label').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('showTooltipAction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('autocloseTooltip').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('useTooltipFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipPattern').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipOffsetX').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('tooltipOffsetY').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('colorFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('markerImageFunction').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('markerImages').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('markerImage').updateValueAndValidity({emitEvent: false}); + this.markersSettingsFormGroup.get('markerImageSize').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.html new file mode 100644 index 0000000000..a53db66706 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.html @@ -0,0 +1,46 @@ + +
+ + widgets.maps.openstreet-provider + + + {{openStreetMapProviderTranslations.get(provider) | translate}} + + + + + + + + {{ 'widgets.maps.use-custom-provider' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.maps.custom-provider-tile-url + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.ts new file mode 100644 index 0000000000..6d7ba24af1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/openstreet-map-provider-settings.component.ts @@ -0,0 +1,139 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + OpenStreetMapProvider, + OpenStreetMapProviderSettings, + openStreetMapProviderTranslationMap +} from '@home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-openstreet-map-provider-settings', + templateUrl: './openstreet-map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => OpenStreetMapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => OpenStreetMapProviderSettingsComponent), + multi: true + } + ] +}) +export class OpenStreetMapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: OpenStreetMapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + mapProviders = Object.values(OpenStreetMapProvider); + + openStreetMapProviderTranslations = openStreetMapProviderTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.providerSettingsFormGroup = this.fb.group({ + mapProvider: [null, [Validators.required]], + useCustomProvider: [null, []], + customProviderTileUrl: [null, [Validators.required]] + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.providerSettingsFormGroup.get('useCustomProvider').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + this.updateValidators(false); + } + } + + writeValue(value: OpenStreetMapProviderSettings): void { + this.modelValue = value; + this.providerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + openStreetProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: OpenStreetMapProviderSettings = this.providerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const useCustomProvider: boolean = this.providerSettingsFormGroup.get('useCustomProvider').value; + if (useCustomProvider) { + this.providerSettingsFormGroup.get('customProviderTileUrl').enable({emitEvent}); + } else { + this.providerSettingsFormGroup.get('customProviderTileUrl').disable({emitEvent}); + } + this.providerSettingsFormGroup.get('customProviderTileUrl').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.html new file mode 100644 index 0000000000..8f3f74b1ff --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.html @@ -0,0 +1,199 @@ + +
+
+ widgets.maps.polygon-settings + + + + + {{ 'widgets.maps.show-polygon' | translate }} + + + + widget-config.advanced-settings + + + + + + + {{ 'widgets.maps.enable-polygon-edit' | translate }} + +
+ widgets.maps.polygon-label + + + + + {{ 'widgets.maps.show-polygon-label' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.use-polygon-label-function' | translate }} + + + + + + + +
+
+ widgets.maps.polygon-tooltip + + + + + {{ 'widgets.maps.show-polygon-tooltip' | translate }} + + + + widget-config.advanced-settings + + + + + widgets.maps.show-tooltip-action + + + {{showTooltipActionTranslations.get(action) | translate}} + + + + + {{ 'widgets.maps.auto-close-polygon-tooltips' | translate }} + + + {{ 'widgets.maps.use-polygon-tooltip-function' | translate }} + + + + + + + +
+
+ widgets.maps.polygon-color +
+ + + + widgets.maps.polygon-opacity + + +
+ + + + + {{ 'widgets.maps.use-polygon-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+ widgets.maps.polygon-stroke +
+ + + + widgets.maps.stroke-opacity + + + + widgets.maps.stroke-weight + + +
+ + + + + {{ 'widgets.maps.use-polygon-stroke-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.ts new file mode 100644 index 0000000000..9c375350c7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/polygon-settings.component.ts @@ -0,0 +1,243 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + PolygonSettings, + ShowTooltipAction, + showTooltipActionTranslationMap +} from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; +import { Widget } from '@shared/models/widget.models'; + +@Component({ + selector: 'tb-polygon-settings', + templateUrl: './polygon-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => PolygonSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => PolygonSettingsComponent), + multi: true + } + ] +}) +export class PolygonSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + widget: Widget; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: PolygonSettings; + + private propagateChange = null; + + public polygonSettingsFormGroup: FormGroup; + + showTooltipActions = Object.values(ShowTooltipAction); + + showTooltipActionTranslations = showTooltipActionTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.polygonSettingsFormGroup = this.fb.group({ + showPolygon: [null, []], + polygonKeyName: [null, [Validators.required]], + editablePolygon: [null, []], + showPolygonLabel: [null, []], + usePolygonLabelFunction: [null, []], + polygonLabel: [null, []], + polygonLabelFunction: [null, []], + showPolygonTooltip: [null, []], + showPolygonTooltipAction: [null, []], + autoClosePolygonTooltip: [null, []], + usePolygonTooltipFunction: [null, []], + polygonTooltipPattern: [null, []], + polygonTooltipFunction: [null, []], + polygonColor: [null, []], + polygonOpacity: [null, [Validators.min(0), Validators.max(1)]], + usePolygonColorFunction: [null, []], + polygonColorFunction: [null, []], + polygonStrokeColor: [null, []], + polygonStrokeOpacity: [null, [Validators.min(0), Validators.max(1)]], + polygonStrokeWeight: [null, [Validators.min(0)]], + usePolygonStrokeColorFunction: [null, []], + polygonStrokeColorFunction: [null, []] + }); + this.polygonSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.polygonSettingsFormGroup.get('showPolygon').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('showPolygonLabel').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('usePolygonLabelFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('showPolygonTooltip').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('usePolygonTooltipFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('usePolygonColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.polygonSettingsFormGroup.get('usePolygonStrokeColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.polygonSettingsFormGroup.disable({emitEvent: false}); + } else { + this.polygonSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: PolygonSettings): void { + this.modelValue = value; + this.polygonSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.polygonSettingsFormGroup.valid ? null : { + polygonSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: PolygonSettings = this.polygonSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showPolygon: boolean = this.polygonSettingsFormGroup.get('showPolygon').value; + const showPolygonLabel: boolean = this.polygonSettingsFormGroup.get('showPolygonLabel').value; + const usePolygonLabelFunction: boolean = this.polygonSettingsFormGroup.get('usePolygonLabelFunction').value; + const showPolygonTooltip: boolean = this.polygonSettingsFormGroup.get('showPolygonTooltip').value; + const usePolygonTooltipFunction: boolean = this.polygonSettingsFormGroup.get('usePolygonTooltipFunction').value; + const usePolygonColorFunction: boolean = this.polygonSettingsFormGroup.get('usePolygonColorFunction').value; + const usePolygonStrokeColorFunction: boolean = this.polygonSettingsFormGroup.get('usePolygonStrokeColorFunction').value; + + this.polygonSettingsFormGroup.disable({emitEvent: false}); + this.polygonSettingsFormGroup.get('showPolygon').enable({emitEvent: false}); + + if (showPolygon) { + this.polygonSettingsFormGroup.get('polygonKeyName').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('editablePolygon').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('showPolygonLabel').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('showPolygonTooltip').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonColor').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonOpacity').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('usePolygonColorFunction').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonStrokeColor').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonStrokeOpacity').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonStrokeWeight').enable({emitEvent: false}); + this.polygonSettingsFormGroup.get('usePolygonStrokeColorFunction').enable({emitEvent: false}); + if (showPolygonLabel) { + this.polygonSettingsFormGroup.get('usePolygonLabelFunction').enable({emitEvent: false}); + if (usePolygonLabelFunction) { + this.polygonSettingsFormGroup.get('polygonLabelFunction').enable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonLabel').disable({emitEvent}); + } else { + this.polygonSettingsFormGroup.get('polygonLabelFunction').disable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonLabel').enable({emitEvent}); + } + } else { + this.polygonSettingsFormGroup.get('usePolygonLabelFunction').disable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonLabelFunction').disable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonLabel').disable({emitEvent}); + } + if (showPolygonTooltip) { + this.polygonSettingsFormGroup.get('showPolygonTooltipAction').enable({emitEvent}); + this.polygonSettingsFormGroup.get('autoClosePolygonTooltip').enable({emitEvent}); + this.polygonSettingsFormGroup.get('usePolygonTooltipFunction').enable({emitEvent: false}); + if (usePolygonTooltipFunction) { + this.polygonSettingsFormGroup.get('polygonTooltipFunction').enable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonTooltipPattern').disable({emitEvent}); + } else { + this.polygonSettingsFormGroup.get('polygonTooltipFunction').disable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonTooltipPattern').enable({emitEvent}); + } + } else { + this.polygonSettingsFormGroup.get('showPolygonTooltipAction').disable({emitEvent}); + this.polygonSettingsFormGroup.get('autoClosePolygonTooltip').disable({emitEvent}); + this.polygonSettingsFormGroup.get('usePolygonTooltipFunction').disable({emitEvent: false}); + this.polygonSettingsFormGroup.get('polygonTooltipFunction').disable({emitEvent}); + this.polygonSettingsFormGroup.get('polygonTooltipPattern').disable({emitEvent}); + } + if (usePolygonColorFunction) { + this.polygonSettingsFormGroup.get('polygonColorFunction').enable({emitEvent}); + } else { + this.polygonSettingsFormGroup.get('polygonColorFunction').disable({emitEvent}); + } + if (usePolygonStrokeColorFunction) { + this.polygonSettingsFormGroup.get('polygonStrokeColorFunction').enable({emitEvent}); + } else { + this.polygonSettingsFormGroup.get('polygonStrokeColorFunction').disable({emitEvent}); + } + } + this.polygonSettingsFormGroup.updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.html new file mode 100644 index 0000000000..eb52ea2d8d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.html @@ -0,0 +1,32 @@ + +
+
+ widgets.maps.route-map-settings +
+ + widgets.maps.stroke-weight + + + + widgets.maps.stroke-opacity + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.ts new file mode 100644 index 0000000000..5d9ed7774a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-settings.component.ts @@ -0,0 +1,115 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { PolylineSettings } from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-route-map-settings', + templateUrl: './route-map-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => RouteMapSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => RouteMapSettingsComponent), + multi: true + } + ] +}) +export class RouteMapSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: PolylineSettings; + + private propagateChange = null; + + public routeMapSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.routeMapSettingsFormGroup = this.fb.group({ + strokeWeight: [null, [Validators.min(0)]], + strokeOpacity: [null, [Validators.min(0), Validators.max(1)]] + }); + this.routeMapSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.routeMapSettingsFormGroup.disable({emitEvent: false}); + } else { + this.routeMapSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: PolylineSettings): void { + this.modelValue = value; + this.routeMapSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + public validate(c: FormControl) { + return this.routeMapSettingsFormGroup.valid ? null : { + routeMapSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: PolylineSettings = this.routeMapSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.html new file mode 100644 index 0000000000..e453c69407 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.html @@ -0,0 +1,24 @@ + +
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.ts new file mode 100644 index 0000000000..0b45405dcf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/route-map-widget-settings.component.ts @@ -0,0 +1,63 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { defaultMapSettings } from 'src/app/modules/home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-route-map-widget-settings', + templateUrl: './route-map-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class RouteMapWidgetSettingsComponent extends WidgetSettingsComponent { + + routeMapWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.routeMapWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...defaultMapSettings + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.routeMapWidgetSettingsForm = this.fb.group({ + mapSettings: [settings.mapSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + return { + mapSettings: settings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return settings.mapSettings; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.html new file mode 100644 index 0000000000..2132ea69cb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.html @@ -0,0 +1,31 @@ + +
+ + widgets.maps.tencent-maps-api-key + + + + widgets.maps.default-map-type + + + {{tencentMapTypeTranslations.get(type) | translate}} + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.ts new file mode 100644 index 0000000000..b52bce6ff2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/tencent-map-provider-settings.component.ts @@ -0,0 +1,122 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + TencentMapProviderSettings, + TencentMapType, + tencentMapTypeProviderTranslationMap +} from '@home/components/widget/lib/maps/map-models'; + +@Component({ + selector: 'tb-tencent-map-provider-settings', + templateUrl: './tencent-map-provider-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TencentMapProviderSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TencentMapProviderSettingsComponent), + multi: true + } + ] +}) +export class TencentMapProviderSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + private modelValue: TencentMapProviderSettings; + + private propagateChange = null; + + public providerSettingsFormGroup: FormGroup; + + tencentMapTypes = Object.values(TencentMapType); + + tencentMapTypeTranslations = tencentMapTypeProviderTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.providerSettingsFormGroup = this.fb.group({ + tmApiKey: [null, [Validators.required]], + tmDefaultMapType: [null, [Validators.required]] + }); + this.providerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.providerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.providerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TencentMapProviderSettings): void { + this.modelValue = value; + this.providerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + } + + public validate(c: FormControl) { + return this.providerSettingsFormGroup.valid ? null : { + tencentMapProviderSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: TencentMapProviderSettings = this.providerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.html new file mode 100644 index 0000000000..7173ab31c5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.html @@ -0,0 +1,94 @@ + +
+
+ widgets.maps.trip-animation-settings + + widgets.maps.normalization-step + + +
+ + + + +
+
+ widgets.maps.tooltip + + + + + {{ 'widgets.maps.show-tooltip' | translate }} + + + + widget-config.advanced-settings + + + +
+ + + + + + widgets.maps.tooltip-opacity + + +
+ + {{ 'widgets.maps.auto-close-tooltip' | translate }} + + + {{ 'widgets.maps.use-tooltip-function' | translate }} + + + + + +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.ts new file mode 100644 index 0000000000..d144b36b0b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-common-settings.component.ts @@ -0,0 +1,173 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { TripAnimationCommonSettings } from '@home/components/widget/lib/maps/map-models'; +import { Widget } from '@shared/models/widget.models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-trip-animation-common-settings', + templateUrl: './trip-animation-common-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TripAnimationCommonSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TripAnimationCommonSettingsComponent), + multi: true + } + ] +}) +export class TripAnimationCommonSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + widget: Widget; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: TripAnimationCommonSettings; + + private propagateChange = null; + + public tripAnimationCommonSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.tripAnimationCommonSettingsFormGroup = this.fb.group({ + normalizationStep: [null, [Validators.min(1)]], + latKeyName: [null, [Validators.required]], + lngKeyName: [null, [Validators.required]], + showTooltip: [null, []], + tooltipColor: [null, []], + tooltipFontColor: [null, []], + tooltipOpacity: [null, [Validators.min(0), Validators.max(1)]], + autocloseTooltip: [null, []], + useTooltipFunction: [null, []], + tooltipPattern: [null, []], + tooltipFunction: [null, []], + }); + this.tripAnimationCommonSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.tripAnimationCommonSettingsFormGroup.get('showTooltip').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationCommonSettingsFormGroup.get('useTooltipFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.tripAnimationCommonSettingsFormGroup.disable({emitEvent: false}); + } else { + this.tripAnimationCommonSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TripAnimationCommonSettings): void { + this.modelValue = value; + this.tripAnimationCommonSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.tripAnimationCommonSettingsFormGroup.valid ? null : { + tripAnimationCommonSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: TripAnimationCommonSettings = this.tripAnimationCommonSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showTooltip: boolean = this.tripAnimationCommonSettingsFormGroup.get('showTooltip').value; + const useTooltipFunction: boolean = this.tripAnimationCommonSettingsFormGroup.get('useTooltipFunction').value; + if (showTooltip) { + this.tripAnimationCommonSettingsFormGroup.get('tooltipColor').enable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipFontColor').enable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipOpacity').enable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('autocloseTooltip').enable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('useTooltipFunction').enable({emitEvent: false}); + if (useTooltipFunction) { + this.tripAnimationCommonSettingsFormGroup.get('tooltipFunction').enable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipPattern').disable({emitEvent}); + } else { + this.tripAnimationCommonSettingsFormGroup.get('tooltipFunction').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipPattern').enable({emitEvent}); + } + } else { + this.tripAnimationCommonSettingsFormGroup.get('tooltipColor').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipFontColor').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipOpacity').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('autocloseTooltip').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('useTooltipFunction').disable({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipFunction').disable({emitEvent}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipPattern').disable({emitEvent}); + } + this.tripAnimationCommonSettingsFormGroup.get('tooltipColor').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipFontColor').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipOpacity').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('autocloseTooltip').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('useTooltipFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationCommonSettingsFormGroup.get('tooltipPattern').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.html new file mode 100644 index 0000000000..6cbeeb2b8b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.html @@ -0,0 +1,97 @@ + +
+
+ widgets.maps.markers-settings + + widgets.maps.rotation-angle + + +
+ widgets.maps.label + + + + + {{ 'widgets.maps.show-label' | translate }} + + + + widget-config.advanced-settings + + + + + {{ 'widgets.maps.use-label-function' | translate }} + + + + + + + +
+
+ widgets.maps.marker-image + + + + + {{ 'widgets.maps.use-marker-image-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + widgets.maps.custom-marker-image-size + + + + + + + + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.ts new file mode 100644 index 0000000000..5f959c4e5c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-marker-settings.component.ts @@ -0,0 +1,175 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, + Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { TripAnimationMarkerSettings } from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-trip-animation-marker-settings', + templateUrl: './trip-animation-marker-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TripAnimationMarkerSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TripAnimationMarkerSettingsComponent), + multi: true + } + ] +}) +export class TripAnimationMarkerSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: TripAnimationMarkerSettings; + + private propagateChange = null; + + public tripAnimationMarkerSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.tripAnimationMarkerSettingsFormGroup = this.fb.group({ + rotationAngle: [null, [Validators.min(0), Validators.max(360)]], + showLabel: [null, []], + useLabelFunction: [null, []], + label: [null, []], + labelFunction: [null, []], + useMarkerImageFunction: [null, []], + markerImage: [null, []], + markerImageSize: [null, [Validators.min(1)]], + markerImageFunction: [null, []], + markerImages: [null, []] + }); + this.tripAnimationMarkerSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.tripAnimationMarkerSettingsFormGroup.get('showLabel').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationMarkerSettingsFormGroup.get('useLabelFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationMarkerSettingsFormGroup.get('useMarkerImageFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.tripAnimationMarkerSettingsFormGroup.disable({emitEvent: false}); + } else { + this.tripAnimationMarkerSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: TripAnimationMarkerSettings): void { + this.modelValue = value; + this.tripAnimationMarkerSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.tripAnimationMarkerSettingsFormGroup.valid ? null : { + tripAnimationMarkerSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: TripAnimationMarkerSettings = this.tripAnimationMarkerSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showLabel: boolean = this.tripAnimationMarkerSettingsFormGroup.get('showLabel').value; + const useLabelFunction: boolean = this.tripAnimationMarkerSettingsFormGroup.get('useLabelFunction').value; + const useMarkerImageFunction: boolean = this.tripAnimationMarkerSettingsFormGroup.get('useMarkerImageFunction').value; + if (showLabel) { + this.tripAnimationMarkerSettingsFormGroup.get('useLabelFunction').enable({emitEvent: false}); + if (useLabelFunction) { + this.tripAnimationMarkerSettingsFormGroup.get('labelFunction').enable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('label').disable({emitEvent}); + } else { + this.tripAnimationMarkerSettingsFormGroup.get('labelFunction').disable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('label').enable({emitEvent}); + } + } else { + this.tripAnimationMarkerSettingsFormGroup.get('useLabelFunction').disable({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('labelFunction').disable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('label').disable({emitEvent}); + } + if (useMarkerImageFunction) { + this.tripAnimationMarkerSettingsFormGroup.get('markerImageFunction').enable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImages').enable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImage').disable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImageSize').disable({emitEvent}); + } else { + this.tripAnimationMarkerSettingsFormGroup.get('markerImageFunction').disable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImages').disable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImage').enable({emitEvent}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImageSize').enable({emitEvent}); + } + this.tripAnimationMarkerSettingsFormGroup.get('useLabelFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('labelFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('label').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImageFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImages').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImage').updateValueAndValidity({emitEvent: false}); + this.tripAnimationMarkerSettingsFormGroup.get('markerImageSize').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.html new file mode 100644 index 0000000000..c2bc5ed7ce --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.html @@ -0,0 +1,116 @@ + +
+
+ widgets.maps.path-settings +
+ + + + widgets.maps.stroke-weight + + + + widgets.maps.stroke-opacity + + +
+ + + + + {{ 'widgets.maps.use-path-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + +
+ widgets.maps.path-decorator + + + + + {{ 'widgets.maps.use-path-decorator' | translate }} + + + + widget-config.advanced-settings + + + +
+ + widgets.maps.decorator-symbol + + + {{polylineDecoratorSymbolTranslations.get(symbol) | translate}} + + + + + widgets.maps.decorator-symbol-size + + +
+
+ + {{ 'widgets.maps.use-path-decorator-custom-color' | translate }} + + + +
+
+ + widgets.maps.decorator-offset + + + + widgets.maps.end-decorator-offset + + + + widgets.maps.decorator-repeat + + +
+
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.ts new file mode 100644 index 0000000000..8dc90b0882 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-path-settings.component.ts @@ -0,0 +1,187 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + PolylineDecoratorSymbol, + polylineDecoratorSymbolTranslationMap, + PolylineSettings +} from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-trip-animation-path-settings', + templateUrl: './trip-animation-path-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TripAnimationPathSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TripAnimationPathSettingsComponent), + multi: true + } + ] +}) +export class TripAnimationPathSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: PolylineSettings; + + private propagateChange = null; + + public tripAnimationPathSettingsFormGroup: FormGroup; + + polylineDecoratorSymbols = Object.values(PolylineDecoratorSymbol); + + polylineDecoratorSymbolTranslations = polylineDecoratorSymbolTranslationMap; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.tripAnimationPathSettingsFormGroup = this.fb.group({ + color: [null, []], + strokeWeight: [null, [Validators.min(0)]], + strokeOpacity: [null, [Validators.min(0), Validators.max(1)]], + useColorFunction: [null, []], + colorFunction: [null, []], + usePolylineDecorator: [null, []], + decoratorSymbol: [null, []], + decoratorSymbolSize: [null, [Validators.min(1)]], + useDecoratorCustomColor: [null, []], + decoratorCustomColor: [null, []], + decoratorOffset: [null, []], + endDecoratorOffset: [null, []], + decoratorRepeat: [null, []], + }); + this.tripAnimationPathSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.tripAnimationPathSettingsFormGroup.get('useColorFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationPathSettingsFormGroup.get('usePolylineDecorator').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.tripAnimationPathSettingsFormGroup.disable({emitEvent: false}); + } else { + this.tripAnimationPathSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: PolylineSettings): void { + this.modelValue = value; + this.tripAnimationPathSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.tripAnimationPathSettingsFormGroup.valid ? null : { + tripAnimationPathSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: PolylineSettings = this.tripAnimationPathSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const useColorFunction: boolean = this.tripAnimationPathSettingsFormGroup.get('useColorFunction').value; + const usePolylineDecorator: boolean = this.tripAnimationPathSettingsFormGroup.get('usePolylineDecorator').value; + const useDecoratorCustomColor: boolean = this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').value; + if (useColorFunction) { + this.tripAnimationPathSettingsFormGroup.get('colorFunction').enable({emitEvent}); + } else { + this.tripAnimationPathSettingsFormGroup.get('colorFunction').disable({emitEvent}); + } + if (usePolylineDecorator) { + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').enable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').enable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').enable({emitEvent: false}); + if (useDecoratorCustomColor) { + this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').enable({emitEvent}); + } else { + this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').disable({emitEvent}); + } + this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').enable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').enable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').enable({emitEvent}); + } else { + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').disable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').disable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').disable({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').disable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').disable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').disable({emitEvent}); + this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').disable({emitEvent}); + } + this.tripAnimationPathSettingsFormGroup.get('colorFunction').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbol').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorSymbolSize').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('useDecoratorCustomColor').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorCustomColor').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorOffset').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('endDecoratorOffset').updateValueAndValidity({emitEvent: false}); + this.tripAnimationPathSettingsFormGroup.get('decoratorRepeat').updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.html new file mode 100644 index 0000000000..e48c690823 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.html @@ -0,0 +1,94 @@ + +
+
+ widgets.maps.points-settings + + + + + {{ 'widgets.maps.show-points' | translate }} + + + + widget-config.advanced-settings + + + +
+ + + + widgets.maps.point-size + + +
+ + + + + {{ 'widgets.maps.use-point-color-function' | translate }} + + + + widget-config.advanced-settings + + + + + + + + + + + + {{ 'widgets.maps.use-point-as-anchor' | translate }} + + + + widget-config.advanced-settings + + + + + + + + + {{ 'widgets.maps.independent-point-tooltip' | translate }} + +
+
+
+
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.ts new file mode 100644 index 0000000000..571c20cfca --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-point-settings.component.ts @@ -0,0 +1,163 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + Validator, Validators +} from '@angular/forms'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { + PointsSettings, + PolylineDecoratorSymbol, + polylineDecoratorSymbolTranslationMap, + PolylineSettings +} from '@home/components/widget/lib/maps/map-models'; +import { WidgetService } from '@core/http/widget.service'; + +@Component({ + selector: 'tb-trip-animation-point-settings', + templateUrl: './trip-animation-point-settings.component.html', + styleUrls: ['./../widget-settings.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => TripAnimationPointSettingsComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => TripAnimationPointSettingsComponent), + multi: true + } + ] +}) +export class TripAnimationPointSettingsComponent extends PageComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + + private modelValue: PointsSettings; + + private propagateChange = null; + + public tripAnimationPointSettingsFormGroup: FormGroup; + + constructor(protected store: Store, + private translate: TranslateService, + private widgetService: WidgetService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit(): void { + this.tripAnimationPointSettingsFormGroup = this.fb.group({ + showPoints: [null, []], + pointColor: [null, []], + pointSize: [null, [Validators.min(1)]], + useColorPointFunction: [null, []], + colorPointFunction: [null, []], + usePointAsAnchor: [null, []], + pointAsAnchorFunction: [null, []], + pointTooltipOnRightPanel: [null, []] + }); + this.tripAnimationPointSettingsFormGroup.valueChanges.subscribe(() => { + this.updateModel(); + }); + this.tripAnimationPointSettingsFormGroup.get('showPoints').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationPointSettingsFormGroup.get('useColorPointFunction').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.tripAnimationPointSettingsFormGroup.get('usePointAsAnchor').valueChanges.subscribe(() => { + this.updateValidators(true); + }); + this.updateValidators(false); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.tripAnimationPointSettingsFormGroup.disable({emitEvent: false}); + } else { + this.tripAnimationPointSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: PointsSettings): void { + this.modelValue = value; + this.tripAnimationPointSettingsFormGroup.patchValue( + value, {emitEvent: false} + ); + this.updateValidators(false); + } + + public validate(c: FormControl) { + return this.tripAnimationPointSettingsFormGroup.valid ? null : { + tripAnimationPointSettings: { + valid: false, + }, + }; + } + + private updateModel() { + const value: PointsSettings = this.tripAnimationPointSettingsFormGroup.value; + this.modelValue = value; + this.propagateChange(this.modelValue); + } + + private updateValidators(emitEvent?: boolean): void { + const showPoints: boolean = this.tripAnimationPointSettingsFormGroup.get('showPoints').value; + const useColorPointFunction: boolean = this.tripAnimationPointSettingsFormGroup.get('useColorPointFunction').value; + const usePointAsAnchor: boolean = this.tripAnimationPointSettingsFormGroup.get('usePointAsAnchor').value; + + this.tripAnimationPointSettingsFormGroup.disable({emitEvent: false}); + this.tripAnimationPointSettingsFormGroup.get('showPoints').enable({emitEvent: false}); + + if (showPoints) { + this.tripAnimationPointSettingsFormGroup.get('pointColor').enable({emitEvent: false}); + this.tripAnimationPointSettingsFormGroup.get('pointSize').enable({emitEvent: false}); + this.tripAnimationPointSettingsFormGroup.get('useColorPointFunction').enable({emitEvent: false}); + if (useColorPointFunction) { + this.tripAnimationPointSettingsFormGroup.get('colorPointFunction').enable({emitEvent: false}); + } + this.tripAnimationPointSettingsFormGroup.get('usePointAsAnchor').enable({emitEvent: false}); + if (usePointAsAnchor) { + this.tripAnimationPointSettingsFormGroup.get('pointAsAnchorFunction').enable({emitEvent: false}); + } + this.tripAnimationPointSettingsFormGroup.get('pointTooltipOnRightPanel').enable({emitEvent: false}); + } + this.tripAnimationPointSettingsFormGroup.updateValueAndValidity({emitEvent: false}); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.html new file mode 100644 index 0000000000..6a5e0d66e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.html @@ -0,0 +1,45 @@ + +
+ + + + + + + + + + + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.ts new file mode 100644 index 0000000000..5e28fcd1ca --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/map/trip-animation-widget-settings.component.ts @@ -0,0 +1,101 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { + CircleSettings, + defaultTripAnimationSettings, + MapProviderSettings, + PointsSettings, + PolygonSettings, + PolylineSettings, + TripAnimationCommonSettings, + TripAnimationMarkerSettings +} from 'src/app/modules/home/components/widget/lib/maps/map-models'; +import { extractType } from '@core/utils'; +import { keys } from 'ts-transformer-keys'; + +@Component({ + selector: 'tb-trip-animation-widget-settings', + templateUrl: './trip-animation-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class TripAnimationWidgetSettingsComponent extends WidgetSettingsComponent { + + tripAnimationWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.tripAnimationWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + ...defaultTripAnimationSettings + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.tripAnimationWidgetSettingsForm = this.fb.group({ + mapProviderSettings: [settings.mapProviderSettings, []], + commonMapSettings: [settings.commonMapSettings, []], + markersSettings: [settings.markersSettings, []], + pathSettings: [settings.pathSettings, []], + pointSettings: [settings.pointSettings, []], + polygonSettings: [settings.polygonSettings, []], + circleSettings: [settings.circleSettings, []] + }); + } + + protected prepareInputSettings(settings: WidgetSettings): WidgetSettings { + const mapProviderSettings = extractType(settings, keys()); + const commonMapSettings = extractType(settings, keys()); + const markersSettings = extractType(settings, keys()); + const pathSettings = extractType(settings, keys()); + const pointSettings = extractType(settings, keys()); + const polygonSettings = extractType(settings, keys()); + const circleSettings = extractType(settings, keys()); + return { + mapProviderSettings, + commonMapSettings, + markersSettings, + pathSettings, + pointSettings, + polygonSettings, + circleSettings + }; + } + + protected prepareOutputSettings(settings: any): WidgetSettings { + return { + ...settings.mapProviderSettings, + ...settings.commonMapSettings, + ...settings.markersSettings, + ...settings.pathSettings, + ...settings.pointSettings, + ...settings.polygonSettings, + ...settings.circleSettings, + }; + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.html new file mode 100644 index 0000000000..4bb4ea7824 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.html @@ -0,0 +1,32 @@ + +
+ + widgets.navigation.title + + + + + + widgets.navigation.navigation-path + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.ts new file mode 100644 index 0000000000..28ff53599b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component.ts @@ -0,0 +1,56 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; + +@Component({ + selector: 'tb-navigation-card-widget-settings', + templateUrl: './navigation-card-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class NavigationCardWidgetSettingsComponent extends WidgetSettingsComponent { + + navigationCardWidgetSettingsForm: FormGroup; + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + } + + protected settingsForm(): FormGroup { + return this.navigationCardWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + name: '{i18n:device.devices}', + icon: 'devices_other', + path: '/devices' + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.navigationCardWidgetSettingsForm = this.fb.group({ + name: [settings.name, [Validators.required]], + icon: [settings.icon, [Validators.required]], + path: [settings.path, [Validators.required]] + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.html new file mode 100644 index 0000000000..18aca3645f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.html @@ -0,0 +1,56 @@ + +
+
+
widgets.navigation.filter-type
+ + {{ 'widgets.navigation.filter-type-all' | translate }} + {{ 'widgets.navigation.filter-type-include' | translate }} + {{ 'widgets.navigation.filter-type-exclude' | translate }} + +
+ + widgets.navigation.items + + + {{ filterItem }} + cancel + + + + + + + + + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.ts new file mode 100644 index 0000000000..4bf7d36f14 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component.ts @@ -0,0 +1,156 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, ViewChild } from '@angular/core'; +import { WidgetSettings, WidgetSettingsComponent } from '@shared/models/widget.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { MatChipInputEvent, MatChipList } from '@angular/material/chips'; +import { MatAutocomplete, MatAutocompleteSelectedEvent } from '@angular/material/autocomplete'; +import { COMMA, ENTER, SEMICOLON } from '@angular/cdk/keycodes'; +import { Observable, of, Subject } from 'rxjs'; +import { map, mergeMap, share, startWith } from 'rxjs/operators'; + +@Component({ + selector: 'tb-navigation-cards-widget-settings', + templateUrl: './navigation-cards-widget-settings.component.html', + styleUrls: ['./../widget-settings.scss'] +}) +export class NavigationCardsWidgetSettingsComponent extends WidgetSettingsComponent { + + @ViewChild('filterItemsChipList') filterItemsChipList: MatChipList; + @ViewChild('filterItemAutocomplete') filterItemAutocomplete: MatAutocomplete; + @ViewChild('filterItemInput') filterItemInput: ElementRef; + + filterItems: Array = ['/devices', '/assets', '/deviceProfiles']; + + separatorKeysCodes = [ENTER, COMMA, SEMICOLON]; + + navigationCardsWidgetSettingsForm: FormGroup; + + filteredFilterItems: Observable>; + + filterItemSearchText = ''; + + filterItemInputChange = new Subject(); + + constructor(protected store: Store, + private fb: FormBuilder) { + super(store); + this.filteredFilterItems = this.filterItemInputChange + .pipe( + startWith(''), + map((value) => value ? value : ''), + mergeMap(name => this.fetchFilterItems(name) ), + share() + ); + } + + protected settingsForm(): FormGroup { + return this.navigationCardsWidgetSettingsForm; + } + + protected defaultSettings(): WidgetSettings { + return { + filterType: 'all', + filter: [] + }; + } + + protected onSettingsSet(settings: WidgetSettings) { + this.navigationCardsWidgetSettingsForm = this.fb.group({ + filterType: [settings.filterType, []], + filter: [settings.filter, []] + }); + } + + protected validatorTriggers(): string[] { + return ['filterType']; + } + + protected updateValidators(emitEvent: boolean) { + const filterType: string = this.navigationCardsWidgetSettingsForm.get('filterType').value; + if (filterType === 'all') { + this.navigationCardsWidgetSettingsForm.get('filter').disable(); + } else { + this.navigationCardsWidgetSettingsForm.get('filter').enable(); + } + this.navigationCardsWidgetSettingsForm.get('filter').updateValueAndValidity({emitEvent}); + } + + private fetchFilterItems(searchText?: string): Observable> { + this.filterItemSearchText = searchText; + let result = [...this.filterItems]; + if (this.filterItemSearchText && this.filterItemSearchText.length) { + result.unshift(this.filterItemSearchText); + result = result.filter(item => item.includes(this.filterItemSearchText)); + } + return of(result); + } + + private addFilterItem(filterItem: string): boolean { + if (filterItem) { + const filterItems: string[] = this.navigationCardsWidgetSettingsForm.get('filter').value; + const index = filterItems.indexOf(filterItem); + if (index === -1) { + filterItems.push(filterItem); + this.navigationCardsWidgetSettingsForm.get('filter').setValue(filterItems); + this.navigationCardsWidgetSettingsForm.get('filter').markAsDirty(); + return true; + } + } + return false; + } + + onFilterItemRemoved(filterItem: string): void { + const filterItems: string[] = this.navigationCardsWidgetSettingsForm.get('filter').value; + const index = filterItems.indexOf(filterItem); + if (index > -1) { + filterItems.splice(index, 1); + this.navigationCardsWidgetSettingsForm.get('filter').setValue(filterItems); + this.navigationCardsWidgetSettingsForm.get('filter').markAsDirty(); + } + } + + onFilterItemInputFocus() { + this.filterItemInputChange.next(this.filterItemInput.nativeElement.value); + } + + addFilterItemFromChipInput(event: MatChipInputEvent): void { + const value = event.value; + if ((value || '').trim()) { + const filterItem = value.trim(); + if (this.addFilterItem(filterItem)) { + this.clearFilterItemInput(''); + } + } + } + + filterItemSelected(event: MatAutocompleteSelectedEvent): void { + this.addFilterItem(event.option.value); + this.clearFilterItemInput(''); + } + + clearFilterItemInput(value: string = '') { + this.filterItemInput.nativeElement.value = value; + this.filterItemInputChange.next(null); + setTimeout(() => { + this.filterItemInput.nativeElement.blur(); + this.filterItemInput.nativeElement.focus(); + }, 0); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.module.ts new file mode 100644 index 0000000000..17875262c0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.module.ts @@ -0,0 +1,531 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { NgModule, Type } from '@angular/core'; +import { QrCodeWidgetSettingsComponent } from '@home/components/widget/lib/settings/cards/qrcode-widget-settings.component'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { SharedHomeComponentsModule } from '@home/components/shared-home-components.module'; +import { IWidgetSettingsComponent } from '@shared/models/widget.models'; +import { + TimeseriesTableWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component'; +import { + TimeseriesTableKeySettingsComponent +} from '@home/components/widget/lib/settings/cards/timeseries-table-key-settings.component'; +import { + TimeseriesTableLatestKeySettingsComponent +} from '@home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component'; +import { + MarkdownWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/markdown-widget-settings.component'; +import { WidgetFontComponent } from '@home/components/widget/lib/settings/common/widget-font.component'; +import { LabelWidgetLabelComponent } from '@home/components/widget/lib/settings/cards/label-widget-label.component'; +import { LabelWidgetSettingsComponent } from '@home/components/widget/lib/settings/cards/label-widget-settings.component'; +import { + SimpleCardWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/simple-card-widget-settings.component'; +import { + DashboardStateWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component'; +import { + EntitiesHierarchyWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/entities-hierarchy-widget-settings.component'; +import { + HtmlCardWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/html-card-widget-settings.component'; +import { + EntitiesTableWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/entities-table-widget-settings.component'; +import { + EntitiesTableKeySettingsComponent +} from '@home/components/widget/lib/settings/cards/entities-table-key-settings.component'; +import { + AlarmsTableWidgetSettingsComponent +} from '@home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component'; +import { + AlarmsTableKeySettingsComponent +} from '@home/components/widget/lib/settings/alarm/alarms-table-key-settings.component'; +import { GaugeHighlightComponent } from '@home/components/widget/lib/settings/gauge/gauge-highlight.component'; +import { + AnalogueRadialGaugeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/analogue-radial-gauge-widget-settings.component'; +import { + AnalogueLinearGaugeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/analogue-linear-gauge-widget-settings.component'; +import { + AnalogueCompassWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component'; +import { + DigitalGaugeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component'; +import { ValueSourceComponent } from '@home/components/widget/lib/settings/common/value-source.component'; +import { FixedColorLevelComponent } from '@home/components/widget/lib/settings/gauge/fixed-color-level.component'; +import { TickValueComponent } from '@home/components/widget/lib/settings/gauge/tick-value.component'; +import { FlotWidgetSettingsComponent } from '@home/components/widget/lib/settings/chart/flot-widget-settings.component'; +import { + FlotLineWidgetSettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-line-widget-settings.component'; +import { LabelDataKeyComponent } from '@home/components/widget/lib/settings/chart/label-data-key.component'; +import { + FlotBarWidgetSettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-bar-widget-settings.component'; +import { FlotThresholdComponent } from '@home/components/widget/lib/settings/chart/flot-threshold.component'; +import { FlotKeySettingsComponent } from '@home/components/widget/lib/settings/chart/flot-key-settings.component'; +import { + FlotLineKeySettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-line-key-settings.component'; +import { + FlotBarKeySettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-bar-key-settings.component'; +import { + FlotLatestKeySettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-latest-key-settings.component'; +import { + FlotPieWidgetSettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-pie-widget-settings.component'; +import { + FlotPieKeySettingsComponent +} from '@home/components/widget/lib/settings/chart/flot-pie-key-settings.component'; +import { + ChartWidgetSettingsComponent +} from '@home/components/widget/lib/settings/chart/chart-widget-settings.component'; +import { + DoughnutChartWidgetSettingsComponent +} from '@home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component'; +import { SwitchRpcSettingsComponent } from '@home/components/widget/lib/settings/control/switch-rpc-settings.component'; +import { + RoundSwitchWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/round-switch-widget-settings.component'; +import { + SwitchControlWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/switch-control-widget-settings.component'; +import { + SlideToggleWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/slide-toggle-widget-settings.component'; +import { + PersistentTableWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/persistent-table-widget-settings.component'; +import { RpcButtonStyleComponent } from '@home/components/widget/lib/settings/control/rpc-button-style.component'; +import { + UpdateDeviceAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component'; +import { + SendRpcWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/send-rpc-widget-settings.component'; +import { + DeviceKeyAutocompleteComponent +} from '@home/components/widget/lib/settings/control/device-key-autocomplete.component'; +import { + LedIndicatorWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/led-indicator-widget-settings.component'; +import { + KnobControlWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/knob-control-widget-settings.component'; +import { + RpcTerminalWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component'; +import { + RpcShellWidgetSettingsComponent +} from '@home/components/widget/lib/settings/control/rpc-shell-widget-settings.component'; +import { + DateRangeNavigatorWidgetSettingsComponent +} from '@home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component'; +import { + EdgeQuickOverviewWidgetSettingsComponent +} from '@home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component'; +import { + GatewayConfigWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component'; +import { + GatewayConfigSingleDeviceWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component'; +import { + GatewayEventsWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component'; +import { GpioItemComponent } from '@home/components/widget/lib/settings/gpio/gpio-item.component'; +import { + GpioControlWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component'; +import { + GpioPanelWidgetSettingsComponent +} from '@home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component'; +import { + NavigationCardWidgetSettingsComponent +} from '@home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component'; +import { + NavigationCardsWidgetSettingsComponent +} from '@home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component'; +import { + DeviceClaimingWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/device-claiming-widget-settings.component'; +import { + UpdateAttributeGeneralSettingsComponent +} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component'; +import { + UpdateIntegerAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component'; +import { + UpdateDoubleAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component'; +import { + UpdateStringAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component'; +import { + UpdateBooleanAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component'; +import { + UpdateImageAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component'; +import { + UpdateDateAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component'; +import { + UpdateLocationAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component'; +import { + UpdateJsonAttributeWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component'; +import { + PhotoCameraInputWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component'; +import { + UpdateMultipleAttributesWidgetSettingsComponent +} from '@home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component'; +import { + DataKeySelectOptionComponent +} from '@home/components/widget/lib/settings/input/datakey-select-option.component'; +import { + UpdateMultipleAttributesKeySettingsComponent +} from '@home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component'; +import { + OpenStreetMapProviderSettingsComponent +} from '@home/components/widget/lib/settings/map/openstreet-map-provider-settings.component'; +import { MapProviderSettingsComponent } from '@home/components/widget/lib/settings/map/map-provider-settings.component'; +import { MapSettingsComponent } from '@home/components/widget/lib/settings/map/map-settings.component'; +import { MapWidgetSettingsComponent } from '@home/components/widget/lib/settings/map/map-widget-settings.component'; +import { + GoogleMapProviderSettingsComponent +} from '@home/components/widget/lib/settings/map/google-map-provider-settings.component'; +import { + HereMapProviderSettingsComponent +} from '@home/components/widget/lib/settings/map/here-map-provider-settings.component'; +import { + TencentMapProviderSettingsComponent +} from '@home/components/widget/lib/settings/map/tencent-map-provider-settings.component'; +import { + ImageMapProviderSettingsComponent +} from '@home/components/widget/lib/settings/map/image-map-provider-settings.component'; +import { + DatasourcesKeyAutocompleteComponent +} from '@home/components/widget/lib/settings/map/datasources-key-autocomplete.component'; +import { CommonMapSettingsComponent } from '@home/components/widget/lib/settings/map/common-map-settings.component'; +import { MarkersSettingsComponent } from '@home/components/widget/lib/settings/map/markers-settings.component'; +import { PolygonSettingsComponent } from '@home/components/widget/lib/settings/map/polygon-settings.component'; +import { CircleSettingsComponent } from '@home/components/widget/lib/settings/map/circle-settings.component'; +import { + MarkerClusteringSettingsComponent +} from '@home/components/widget/lib/settings/map/marker-clustering-settings.component'; +import { MapEditorSettingsComponent } from '@home/components/widget/lib/settings/map/map-editor-settings.component'; +import { RouteMapSettingsComponent } from '@home/components/widget/lib/settings/map/route-map-settings.component'; +import { + RouteMapWidgetSettingsComponent +} from '@home/components/widget/lib/settings/map/route-map-widget-settings.component'; +import { + TripAnimationWidgetSettingsComponent +} from '@home/components/widget/lib/settings/map/trip-animation-widget-settings.component'; +import { + TripAnimationCommonSettingsComponent +} from '@home/components/widget/lib/settings/map/trip-animation-common-settings.component'; +import { + TripAnimationMarkerSettingsComponent +} from '@home/components/widget/lib/settings/map/trip-animation-marker-settings.component'; +import { + TripAnimationPathSettingsComponent +} from '@home/components/widget/lib/settings/map/trip-animation-path-settings.component'; +import { + TripAnimationPointSettingsComponent +} from '@home/components/widget/lib/settings/map/trip-animation-point-settings.component'; + +@NgModule({ + declarations: [ + QrCodeWidgetSettingsComponent, + TimeseriesTableWidgetSettingsComponent, + TimeseriesTableKeySettingsComponent, + TimeseriesTableLatestKeySettingsComponent, + MarkdownWidgetSettingsComponent, + WidgetFontComponent, + LabelWidgetLabelComponent, + LabelWidgetSettingsComponent, + SimpleCardWidgetSettingsComponent, + DashboardStateWidgetSettingsComponent, + EntitiesHierarchyWidgetSettingsComponent, + HtmlCardWidgetSettingsComponent, + EntitiesTableWidgetSettingsComponent, + EntitiesTableKeySettingsComponent, + AlarmsTableWidgetSettingsComponent, + AlarmsTableKeySettingsComponent, + GaugeHighlightComponent, + AnalogueRadialGaugeWidgetSettingsComponent, + AnalogueLinearGaugeWidgetSettingsComponent, + AnalogueCompassWidgetSettingsComponent, + DigitalGaugeWidgetSettingsComponent, + ValueSourceComponent, + FixedColorLevelComponent, + TickValueComponent, + FlotWidgetSettingsComponent, + LabelDataKeyComponent, + FlotLineWidgetSettingsComponent, + FlotBarWidgetSettingsComponent, + FlotThresholdComponent, + FlotKeySettingsComponent, + FlotLineKeySettingsComponent, + FlotBarKeySettingsComponent, + FlotLatestKeySettingsComponent, + FlotPieWidgetSettingsComponent, + FlotPieKeySettingsComponent, + ChartWidgetSettingsComponent, + DoughnutChartWidgetSettingsComponent, + DeviceKeyAutocompleteComponent, + SwitchRpcSettingsComponent, + RoundSwitchWidgetSettingsComponent, + SwitchControlWidgetSettingsComponent, + SlideToggleWidgetSettingsComponent, + PersistentTableWidgetSettingsComponent, + RpcButtonStyleComponent, + UpdateDeviceAttributeWidgetSettingsComponent, + SendRpcWidgetSettingsComponent, + LedIndicatorWidgetSettingsComponent, + KnobControlWidgetSettingsComponent, + RpcTerminalWidgetSettingsComponent, + RpcShellWidgetSettingsComponent, + DateRangeNavigatorWidgetSettingsComponent, + EdgeQuickOverviewWidgetSettingsComponent, + GatewayConfigWidgetSettingsComponent, + GatewayConfigSingleDeviceWidgetSettingsComponent, + GatewayEventsWidgetSettingsComponent, + GpioItemComponent, + GpioControlWidgetSettingsComponent, + GpioPanelWidgetSettingsComponent, + NavigationCardWidgetSettingsComponent, + NavigationCardsWidgetSettingsComponent, + DeviceClaimingWidgetSettingsComponent, + UpdateAttributeGeneralSettingsComponent, + UpdateIntegerAttributeWidgetSettingsComponent, + UpdateDoubleAttributeWidgetSettingsComponent, + UpdateStringAttributeWidgetSettingsComponent, + UpdateBooleanAttributeWidgetSettingsComponent, + UpdateImageAttributeWidgetSettingsComponent, + UpdateDateAttributeWidgetSettingsComponent, + UpdateLocationAttributeWidgetSettingsComponent, + UpdateJsonAttributeWidgetSettingsComponent, + PhotoCameraInputWidgetSettingsComponent, + UpdateMultipleAttributesWidgetSettingsComponent, + DataKeySelectOptionComponent, + UpdateMultipleAttributesKeySettingsComponent, + GoogleMapProviderSettingsComponent, + OpenStreetMapProviderSettingsComponent, + HereMapProviderSettingsComponent, + ImageMapProviderSettingsComponent, + TencentMapProviderSettingsComponent, + MapProviderSettingsComponent, + DatasourcesKeyAutocompleteComponent, + CommonMapSettingsComponent, + MarkersSettingsComponent, + PolygonSettingsComponent, + CircleSettingsComponent, + MarkerClusteringSettingsComponent, + MapEditorSettingsComponent, + RouteMapSettingsComponent, + MapSettingsComponent, + TripAnimationCommonSettingsComponent, + TripAnimationMarkerSettingsComponent, + TripAnimationPathSettingsComponent, + TripAnimationPointSettingsComponent, + MapWidgetSettingsComponent, + RouteMapWidgetSettingsComponent, + TripAnimationWidgetSettingsComponent + ], + imports: [ + CommonModule, + SharedModule, + SharedHomeComponentsModule + ], + exports: [ + QrCodeWidgetSettingsComponent, + TimeseriesTableWidgetSettingsComponent, + TimeseriesTableKeySettingsComponent, + TimeseriesTableLatestKeySettingsComponent, + MarkdownWidgetSettingsComponent, + WidgetFontComponent, + LabelWidgetLabelComponent, + LabelWidgetSettingsComponent, + SimpleCardWidgetSettingsComponent, + DashboardStateWidgetSettingsComponent, + EntitiesHierarchyWidgetSettingsComponent, + HtmlCardWidgetSettingsComponent, + EntitiesTableWidgetSettingsComponent, + EntitiesTableKeySettingsComponent, + AlarmsTableWidgetSettingsComponent, + AlarmsTableKeySettingsComponent, + GaugeHighlightComponent, + AnalogueRadialGaugeWidgetSettingsComponent, + AnalogueLinearGaugeWidgetSettingsComponent, + AnalogueCompassWidgetSettingsComponent, + DigitalGaugeWidgetSettingsComponent, + ValueSourceComponent, + FixedColorLevelComponent, + TickValueComponent, + FlotWidgetSettingsComponent, + LabelDataKeyComponent, + FlotLineWidgetSettingsComponent, + FlotBarWidgetSettingsComponent, + FlotThresholdComponent, + FlotKeySettingsComponent, + FlotLineKeySettingsComponent, + FlotBarKeySettingsComponent, + FlotLatestKeySettingsComponent, + FlotPieWidgetSettingsComponent, + FlotPieKeySettingsComponent, + ChartWidgetSettingsComponent, + DoughnutChartWidgetSettingsComponent, + DeviceKeyAutocompleteComponent, + SwitchRpcSettingsComponent, + RoundSwitchWidgetSettingsComponent, + SwitchControlWidgetSettingsComponent, + SlideToggleWidgetSettingsComponent, + PersistentTableWidgetSettingsComponent, + RpcButtonStyleComponent, + UpdateDeviceAttributeWidgetSettingsComponent, + SendRpcWidgetSettingsComponent, + LedIndicatorWidgetSettingsComponent, + KnobControlWidgetSettingsComponent, + RpcTerminalWidgetSettingsComponent, + RpcShellWidgetSettingsComponent, + DateRangeNavigatorWidgetSettingsComponent, + EdgeQuickOverviewWidgetSettingsComponent, + GatewayConfigWidgetSettingsComponent, + GatewayConfigSingleDeviceWidgetSettingsComponent, + GatewayEventsWidgetSettingsComponent, + GpioItemComponent, + GpioControlWidgetSettingsComponent, + GpioPanelWidgetSettingsComponent, + NavigationCardWidgetSettingsComponent, + NavigationCardsWidgetSettingsComponent, + DeviceClaimingWidgetSettingsComponent, + UpdateAttributeGeneralSettingsComponent, + UpdateIntegerAttributeWidgetSettingsComponent, + UpdateDoubleAttributeWidgetSettingsComponent, + UpdateStringAttributeWidgetSettingsComponent, + UpdateBooleanAttributeWidgetSettingsComponent, + UpdateImageAttributeWidgetSettingsComponent, + UpdateDateAttributeWidgetSettingsComponent, + UpdateLocationAttributeWidgetSettingsComponent, + UpdateJsonAttributeWidgetSettingsComponent, + PhotoCameraInputWidgetSettingsComponent, + UpdateMultipleAttributesWidgetSettingsComponent, + DataKeySelectOptionComponent, + UpdateMultipleAttributesKeySettingsComponent, + GoogleMapProviderSettingsComponent, + OpenStreetMapProviderSettingsComponent, + HereMapProviderSettingsComponent, + ImageMapProviderSettingsComponent, + TencentMapProviderSettingsComponent, + MapProviderSettingsComponent, + DatasourcesKeyAutocompleteComponent, + CommonMapSettingsComponent, + MarkersSettingsComponent, + PolygonSettingsComponent, + CircleSettingsComponent, + MarkerClusteringSettingsComponent, + MapEditorSettingsComponent, + RouteMapSettingsComponent, + MapSettingsComponent, + TripAnimationCommonSettingsComponent, + TripAnimationMarkerSettingsComponent, + TripAnimationPathSettingsComponent, + TripAnimationPointSettingsComponent, + MapWidgetSettingsComponent, + RouteMapWidgetSettingsComponent, + TripAnimationWidgetSettingsComponent + ] +}) +export class WidgetSettingsModule { +} + +export const widgetSettingsComponentsMap: {[key: string]: Type} = { + 'tb-qrcode-widget-settings': QrCodeWidgetSettingsComponent, + 'tb-timeseries-table-widget-settings': TimeseriesTableWidgetSettingsComponent, + 'tb-timeseries-table-key-settings': TimeseriesTableKeySettingsComponent, + 'tb-timeseries-table-latest-key-settings': TimeseriesTableLatestKeySettingsComponent, + 'tb-markdown-widget-settings': MarkdownWidgetSettingsComponent, + 'tb-label-widget-settings': LabelWidgetSettingsComponent, + 'tb-simple-card-widget-settings': SimpleCardWidgetSettingsComponent, + 'tb-dashboard-state-widget-settings': DashboardStateWidgetSettingsComponent, + 'tb-entities-hierarchy-widget-settings': EntitiesHierarchyWidgetSettingsComponent, + 'tb-html-card-widget-settings': HtmlCardWidgetSettingsComponent, + 'tb-entities-table-widget-settings': EntitiesTableWidgetSettingsComponent, + 'tb-entities-table-key-settings': EntitiesTableKeySettingsComponent, + 'tb-alarms-table-widget-settings': AlarmsTableWidgetSettingsComponent, + 'tb-alarms-table-key-settings': AlarmsTableKeySettingsComponent, + 'tb-analogue-radial-gauge-widget-settings': AnalogueRadialGaugeWidgetSettingsComponent, + 'tb-analogue-linear-gauge-widget-settings': AnalogueLinearGaugeWidgetSettingsComponent, + 'tb-analogue-compass-widget-settings': AnalogueCompassWidgetSettingsComponent, + 'tb-digital-gauge-widget-settings': DigitalGaugeWidgetSettingsComponent, + 'tb-flot-line-widget-settings': FlotLineWidgetSettingsComponent, + 'tb-flot-bar-widget-settings': FlotBarWidgetSettingsComponent, + 'tb-flot-line-key-settings': FlotLineKeySettingsComponent, + 'tb-flot-bar-key-settings': FlotBarKeySettingsComponent, + 'tb-flot-latest-key-settings': FlotLatestKeySettingsComponent, + 'tb-flot-pie-widget-settings': FlotPieWidgetSettingsComponent, + 'tb-flot-pie-key-settings': FlotPieKeySettingsComponent, + 'tb-chart-widget-settings': ChartWidgetSettingsComponent, + 'tb-doughnut-chart-widget-settings': DoughnutChartWidgetSettingsComponent, + 'tb-round-switch-widget-settings': RoundSwitchWidgetSettingsComponent, + 'tb-switch-control-widget-settings': SwitchControlWidgetSettingsComponent, + 'tb-slide-toggle-widget-settings': SlideToggleWidgetSettingsComponent, + 'tb-persistent-table-widget-settings': PersistentTableWidgetSettingsComponent, + 'tb-update-device-attribute-widget-settings': UpdateDeviceAttributeWidgetSettingsComponent, + 'tb-send-rpc-widget-settings': SendRpcWidgetSettingsComponent, + 'tb-led-indicator-widget-settings': LedIndicatorWidgetSettingsComponent, + 'tb-knob-control-widget-settings': KnobControlWidgetSettingsComponent, + 'tb-rpc-terminal-widget-settings': RpcTerminalWidgetSettingsComponent, + 'tb-rpc-shell-widget-settings': RpcShellWidgetSettingsComponent, + 'tb-date-range-navigator-widget-settings': DateRangeNavigatorWidgetSettingsComponent, + 'tb-edge-quick-overview-widget-settings': EdgeQuickOverviewWidgetSettingsComponent, + 'tb-gateway-config-widget-settings': GatewayConfigWidgetSettingsComponent, + 'tb-gateway-config-single-device-widget-settings': GatewayConfigSingleDeviceWidgetSettingsComponent, + 'tb-gateway-events-widget-settings': GatewayEventsWidgetSettingsComponent, + 'tb-gpio-control-widget-settings': GpioControlWidgetSettingsComponent, + 'tb-gpio-panel-widget-settings': GpioPanelWidgetSettingsComponent, + 'tb-navigation-card-widget-settings': NavigationCardWidgetSettingsComponent, + 'tb-navigation-cards-widget-settings': NavigationCardsWidgetSettingsComponent, + 'tb-device-claiming-widget-settings': DeviceClaimingWidgetSettingsComponent, + 'tb-update-integer-attribute-widget-settings': UpdateIntegerAttributeWidgetSettingsComponent, + 'tb-update-double-attribute-widget-settings': UpdateDoubleAttributeWidgetSettingsComponent, + 'tb-update-string-attribute-widget-settings': UpdateStringAttributeWidgetSettingsComponent, + 'tb-update-boolean-attribute-widget-settings': UpdateBooleanAttributeWidgetSettingsComponent, + 'tb-update-image-attribute-widget-settings': UpdateImageAttributeWidgetSettingsComponent, + 'tb-update-date-attribute-widget-settings': UpdateDateAttributeWidgetSettingsComponent, + 'tb-update-location-attribute-widget-settings': UpdateLocationAttributeWidgetSettingsComponent, + 'tb-update-json-attribute-widget-settings': UpdateJsonAttributeWidgetSettingsComponent, + 'tb-photo-camera-input-widget-settings': PhotoCameraInputWidgetSettingsComponent, + 'tb-update-multiple-attributes-widget-settings': UpdateMultipleAttributesWidgetSettingsComponent, + 'tb-update-multiple-attributes-key-settings': UpdateMultipleAttributesKeySettingsComponent, + 'tb-map-widget-settings': MapWidgetSettingsComponent, + 'tb-route-map-widget-settings': RouteMapWidgetSettingsComponent, + 'tb-trip-animation-widget-settings': TripAnimationWidgetSettingsComponent +}; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.scss b/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.scss new file mode 100644 index 0000000000..22d5732d41 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.scss @@ -0,0 +1,134 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@import '../../../../../../../scss/constants'; + +:host { + .tb-widget-settings { + .fields-group { + padding: 0 16px 8px; + margin-bottom: 10px; + border: 1px groove rgba(0, 0, 0, .25); + border-radius: 4px; + + legend { + color: rgba(0, 0, 0, .7); + width: fit-content; + } + + legend + * { + display: block; + margin-top: 16px; + } + + &.fields-group-slider { + padding: 0; + + legend { + margin-left: 16px; + } + + > .tb-settings { + margin-top: 0; + padding: 0 16px 8px; + } + } + } + + .tb-control-list { + overflow-y: auto; + &.mat-padding { + padding: 8px; + @media #{$mat-gt-sm} { + padding: 16px; + } + } + } + + .tb-prompt{ + margin: 30px 0; + } + } +} + +:host ::ng-deep { + .tb-widget-settings { + .mat-checkbox-label { + white-space: normal; + } + + .mat-expansion-panel { + &.tb-settings { + box-shadow: none; + + .mat-content { + overflow: visible; + } + + .mat-expansion-panel-header { + padding: 0; + + &:hover { + background: none; + } + + .mat-expansion-indicator { + padding: 2px; + } + } + + .mat-expansion-panel-header-description { + align-items: center; + } + + > .mat-expansion-panel-content { + > .mat-expansion-panel-body { + padding: 0; + } + } + + .mat-checkbox-layout { + margin: 5px 0; + } + + .mat-checkbox-inner-container { + margin-right: 12px; + } + } + + .mat-expansion-panel-content { + font: inherit; + } + } + + .mat-slide { + margin: 8px 0; + } + + .slide-block { + display: block; + + &:not(:last-child) { + margin-bottom: 8px; + } + } + + .mat-slide-toggle-content { + white-space: normal; + } + + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.models.ts index f90c287111..0747ddffc1 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.models.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -15,14 +15,13 @@ /// import { EntityId } from '@shared/models/id/entity-id'; -import { DataKey, WidgetActionDescriptor, WidgetConfig } from '@shared/models/widget.models'; +import { DataKey, FormattedData, WidgetActionDescriptor, WidgetConfig } from '@shared/models/widget.models'; import { getDescendantProp, isDefined, isNotEmptyStr } from '@core/utils'; import { AlarmDataInfo, alarmFields } from '@shared/models/alarm.models'; import * as tinycolor_ from 'tinycolor2'; import { Direction, EntityDataSortOrder, EntityKey } from '@shared/models/query/query.models'; import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import { WidgetContext } from '@home/models/widget-component.models'; -import { FormattedData } from '@home/components/widget/lib/maps/map-models'; import { UtilsService } from '@core/services/utils.service'; import { TranslateService } from '@ngx-translate/core'; @@ -73,6 +72,7 @@ export interface EntityData { export interface EntityColumn extends DataKey { def: string; title: string; + sortable: boolean; entityKey?: EntityKey; } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.scss b/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.scss index 98c3dd67a2..0ef9fa5d12 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.scss +++ b/ui-ngx/src/app/modules/home/components/widget/lib/table-widget.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/timeseries-table-widget.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/timeseries-table-widget.component.html index 8c3b9084b0..02ab76d829 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/timeseries-table-widget.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/timeseries-table-widget.component.html @@ -1,6 +1,6 @@ +
+ +
{{definedDirectiveError}}
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.scss b/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.scss new file mode 100644 index 0000000000..2afac0944b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.scss @@ -0,0 +1,22 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host { + .tb-settings-directive-error { + font-size: 13px; + font-weight: 400; + color: rgb(221, 44, 0); + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.ts b/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.ts new file mode 100644 index 0000000000..4337a5e07b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/widget/widget-settings.component.ts @@ -0,0 +1,231 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { + AfterViewInit, + Component, ComponentFactoryResolver, + ComponentRef, + forwardRef, + Input, OnChanges, + OnDestroy, + OnInit, SimpleChanges, + ViewChild, + ViewContainerRef +} from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; +import { + IRuleNodeConfigurationComponent, + RuleNodeConfiguration, + RuleNodeDefinition +} from '@shared/models/rule-node.models'; +import { Subscription } from 'rxjs'; +import { RuleChainService } from '@core/http/rule-chain.service'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { TranslateService } from '@ngx-translate/core'; +import { JsonObjectEditComponent } from '@shared/components/json-object-edit.component'; +import { deepClone } from '@core/utils'; +import { RuleChainType } from '@shared/models/rule-chain.models'; +import { JsonFormComponent } from '@shared/components/json-form/json-form.component'; +import { JsonFormComponentData } from '@shared/components/json-form/json-form-component.models'; +import { IWidgetSettingsComponent, Widget, WidgetSettings } from '@shared/models/widget.models'; +import { widgetSettingsComponentsMap } from '@home/components/widget/lib/settings/widget-settings.module'; +import { Dashboard } from '@shared/models/dashboard.models'; +import { WidgetService } from '@core/http/widget.service'; +import { IAliasController } from '@core/api/widget-api.models'; + +@Component({ + selector: 'tb-widget-settings', + templateUrl: './widget-settings.component.html', + styleUrls: ['./widget-settings.component.scss'], + providers: [{ + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => WidgetSettingsComponent), + multi: true + }] +}) +export class WidgetSettingsComponent implements ControlValueAccessor, OnInit, OnDestroy, AfterViewInit, OnChanges { + + @ViewChild('definedSettingsContent', {read: ViewContainerRef, static: true}) definedSettingsContainer: ViewContainerRef; + + @ViewChild('jsonFormComponent') jsonFormComponent: JsonFormComponent; + + @Input() + disabled: boolean; + + @Input() + aliasController: IAliasController; + + @Input() + dashboard: Dashboard; + + @Input() + widget: Widget; + + private settingsDirective: string; + + definedDirectiveError: string; + + widgetSettingsFormGroup: FormGroup; + + changeSubscription: Subscription; + + private definedSettingsComponentRef: ComponentRef; + private definedSettingsComponent: IWidgetSettingsComponent; + + private widgetSettingsFormData: JsonFormComponentData; + + private propagateChange = (v: any) => { }; + + constructor(private translate: TranslateService, + private cfr: ComponentFactoryResolver, + private widgetService: WidgetService, + private fb: FormBuilder) { + this.widgetSettingsFormGroup = this.fb.group({ + settings: [null, Validators.required] + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + ngOnInit(): void { + } + + ngOnChanges(changes: SimpleChanges): void { + for (const propName of Object.keys(changes)) { + const change = changes[propName]; + if (!change.firstChange && change.currentValue !== change.previousValue) { + if (propName === 'widget') { + if (this.definedSettingsComponent) { + this.definedSettingsComponent.widget = this.widget; + } + } + if (propName === 'dashboard') { + if (this.definedSettingsComponent) { + this.definedSettingsComponent.dashboard = this.dashboard; + } + } + if (propName === 'aliasController') { + if (this.definedSettingsComponent) { + this.definedSettingsComponent.aliasController = this.aliasController; + } + } + } + } + } + + ngOnDestroy(): void { + if (this.definedSettingsComponentRef) { + this.definedSettingsComponentRef.destroy(); + } + } + + ngAfterViewInit(): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.widgetSettingsFormGroup.disable({emitEvent: false}); + } else { + this.widgetSettingsFormGroup.enable({emitEvent: false}); + } + } + + writeValue(value: JsonFormComponentData): void { + this.widgetSettingsFormData = value; + if (this.changeSubscription) { + this.changeSubscription.unsubscribe(); + this.changeSubscription = null; + } + if (this.settingsDirective !== this.widgetSettingsFormData.settingsDirective) { + this.settingsDirective = this.widgetSettingsFormData.settingsDirective; + this.validateDefinedDirective(); + } + if (this.definedSettingsComponent) { + this.definedSettingsComponent.settings = this.widgetSettingsFormData.model; + this.changeSubscription = this.definedSettingsComponent.settingsChanged.subscribe((settings) => { + this.updateModel(settings); + }); + } else { + this.widgetSettingsFormGroup.get('settings').patchValue(this.widgetSettingsFormData, {emitEvent: false}); + this.changeSubscription = this.widgetSettingsFormGroup.get('settings').valueChanges.subscribe( + (widgetSettingsFormData: JsonFormComponentData) => { + this.updateModel(widgetSettingsFormData.model); + } + ); + } + } + + useDefinedDirective(): boolean { + return this.settingsDirective && + this.settingsDirective.length && !this.definedDirectiveError; + } + + useJsonForm(): boolean { + return !this.settingsDirective || !this.settingsDirective.length; + } + + private updateModel(settings: WidgetSettings) { + this.widgetSettingsFormData.model = settings; + if (this.definedSettingsComponent || this.widgetSettingsFormGroup.valid) { + this.propagateChange(this.widgetSettingsFormData); + } else { + this.propagateChange(null); + } + } + + private validateDefinedDirective() { + if (this.definedSettingsComponentRef) { + this.definedSettingsComponentRef.destroy(); + this.definedSettingsComponentRef = null; + this.definedSettingsComponent = null; + } + if (this.settingsDirective && this.settingsDirective.length) { + const componentType = widgetSettingsComponentsMap[this.settingsDirective]; + if (!componentType) { + this.definedDirectiveError = this.translate.instant('widget-config.settings-component-not-found', + {selector: this.settingsDirective}); + } else { + if (this.changeSubscription) { + this.changeSubscription.unsubscribe(); + this.changeSubscription = null; + } + this.definedSettingsContainer.clear(); + const factory = this.cfr.resolveComponentFactory(componentType); + this.definedSettingsComponentRef = this.definedSettingsContainer.createComponent(factory); + this.definedSettingsComponent = this.definedSettingsComponentRef.instance; + this.definedSettingsComponent.aliasController = this.aliasController; + this.definedSettingsComponent.dashboard = this.dashboard; + this.definedSettingsComponent.widget = this.widget; + this.definedSettingsComponent.functionScopeVariables = this.widgetService.getWidgetScopeVariables(); + this.changeSubscription = this.definedSettingsComponent.settingsChanged.subscribe((settings) => { + this.updateModel(settings); + }); + } + } + } + + validate() { + if (this.useDefinedDirective()) { + this.definedSettingsComponent.validate(); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/widget/widget.component.html b/ui-ngx/src/app/modules/home/components/widget/widget.component.html index fcaede8fc9..0d20c1de2b 100644 --- a/ui-ngx/src/app/modules/home/components/widget/widget.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/widget.component.html @@ -1,6 +1,6 @@ - + {{section.icon}} {{section.name | translate}} diff --git a/ui-ngx/src/app/modules/home/menu/menu-link.component.scss b/ui-ngx/src/app/modules/home/menu/menu-link.component.scss index 3abcc4c738..da8df4b469 100644 --- a/ui-ngx/src/app/modules/home/menu/menu-link.component.scss +++ b/ui-ngx/src/app/modules/home/menu/menu-link.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/menu/menu-link.component.ts b/ui-ngx/src/app/modules/home/menu/menu-link.component.ts index 58724b89f9..cae14d32b6 100644 --- a/ui-ngx/src/app/modules/home/menu/menu-link.component.ts +++ b/ui-ngx/src/app/modules/home/menu/menu-link.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html index 0a41e75657..0635205581 100644 --- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html +++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.html @@ -1,6 +1,6 @@ + routerLinkActive="tb-active" [routerLinkActiveOptions]="{paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored'}" routerLink="{{section.path}}"> {{section.icon}} {{section.name | translate}} diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss index 87899b02b5..a076fa77d6 100644 --- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss +++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts index 6bbc5414fe..76a818c16b 100644 --- a/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts +++ b/ui-ngx/src/app/modules/home/menu/menu-toggle.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/menu/side-menu.component.html b/ui-ngx/src/app/modules/home/menu/side-menu.component.html index 91275719e9..8a9f07f3c9 100644 --- a/ui-ngx/src/app/modules/home/menu/side-menu.component.html +++ b/ui-ngx/src/app/modules/home/menu/side-menu.component.html @@ -1,6 +1,6 @@ +
+ + +
+ +
+
+
+ + +
diff --git a/ui-ngx/src/app/modules/home/pages/admin/queue/queue.component.ts b/ui-ngx/src/app/modules/home/pages/admin/queue/queue.component.ts new file mode 100644 index 0000000000..d2fbaa1b77 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/admin/queue/queue.component.ts @@ -0,0 +1,87 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { ChangeDetectorRef, Component, Inject } from '@angular/core'; +import { EntityType } from '@shared/models/entity-type.models'; +import { FormBuilder, FormGroup } from '@angular/forms'; +import { EntityComponent } from '@home/components/entity/entity.component'; +import { QueueInfo } from '@shared/models/queue.models'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { EntityTableConfig } from '@home/models/entity/entities-table-config.models'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; + +@Component({ + selector: 'tb-queue', + templateUrl: './queue.component.html', + styleUrls: [] +}) +export class QueueComponent extends EntityComponent { + entityForm: FormGroup; + + entityType = EntityType; + submitStrategies: string[] = []; + processingStrategies: string[] = []; + + constructor(protected store: Store, + protected translate: TranslateService, + @Inject('entity') protected entityValue: QueueInfo, + @Inject('entitiesTableConfig') protected entitiesTableConfigValue: EntityTableConfig, + protected cd: ChangeDetectorRef, + public fb: FormBuilder) { + super(store, fb, entityValue, entitiesTableConfigValue, cd); + } + + ngOnInit() { + super.ngOnInit(); + } + + buildForm(entity: QueueInfo): FormGroup { + return this.fb.group({ + queue: [entity] + }); + } + + hideDelete() { + if (this.entitiesTableConfig) { + return !this.entitiesTableConfig.deleteEnabled(this.entity); + } else { + return false; + } + } + + updateForm(entity: QueueInfo) { + this.entityForm.patchValue({ + queue: entity + }, {emitEvent: false}); + } + + prepareFormValue(formValue: any) { + return super.prepareFormValue(formValue.queue); + } + + onQueueIdCopied($event) { + this.store.dispatch(new ActionNotificationShow( + { + message: this.translate.instant('queue.idCopiedMessage'), + type: 'success', + duration: 750, + verticalPosition: 'bottom', + horizontalPosition: 'right' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/admin/queue/queues-table-config.resolver.ts b/ui-ngx/src/app/modules/home/pages/admin/queue/queues-table-config.resolver.ts new file mode 100644 index 0000000000..24f33a8a03 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/admin/queue/queues-table-config.resolver.ts @@ -0,0 +1,133 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, Resolve, Router } from '@angular/router'; +import { EntityTableColumn, EntityTableConfig } from '@home/models/entity/entities-table-config.models'; +import { + QueueInfo, + QueueProcessingStrategyTypesMap, + QueueSubmitStrategyTypesMap, + ServiceType +} from '@shared/models/queue.models'; +import { select, Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { BroadcastService } from '@core/services/broadcast.service'; +import { CustomerService } from '@core/http/customer.service'; +import { DialogService } from '@core/services/dialog.service'; +import { HomeDialogsService } from '@home/dialogs/home-dialogs.service'; +import { map, mergeMap, take } from 'rxjs/operators'; +import { Observable } from 'rxjs'; +import { EntityType, entityTypeResources, entityTypeTranslations } from '@app/shared/models/entity-type.models'; +import { TranslateService } from '@ngx-translate/core'; +import { QueueComponent } from './queue.component'; +import { QueueService } from '@core/http/queue.service'; +import { selectAuthUser } from '@core/auth/auth.selectors'; +import { EntityAction } from '@home/models/entity/entity-component.models'; + +@Injectable() +export class QueuesTableConfigResolver implements Resolve> { + + readonly queueType = ServiceType.TB_RULE_ENGINE; + + private readonly config: EntityTableConfig = new EntityTableConfig(); + + constructor(private store: Store, + private broadcast: BroadcastService, + private queueService: QueueService, + private customerService: CustomerService, + private dialogService: DialogService, + private homeDialogs: HomeDialogsService, + private router: Router, + private translate: TranslateService) { + + this.config.entityType = EntityType.QUEUE; + this.config.entityComponent = QueueComponent; + this.config.entityTranslations = entityTypeTranslations.get(EntityType.QUEUE); + this.config.entityResources = entityTypeResources.get(EntityType.QUEUE); + + this.config.deleteEntityTitle = queue => this.translate.instant('queue.delete-queue-title', {queueName: queue.name}); + this.config.deleteEntityContent = () => this.translate.instant('queue.delete-queue-text'); + this.config.deleteEntitiesTitle = count => this.translate.instant('queue.delete-queues-title', {count}); + this.config.deleteEntitiesContent = () => this.translate.instant('queue.delete-queues-text'); + + this.config.onEntityAction = action => this.onQueueAction(action); + } + + resolve(route: ActivatedRouteSnapshot): Observable> { + this.config.componentsData = { + queueType: this.queueType + }; + + return this.store.pipe(select(selectAuthUser), take(1)).pipe( + map(() => { + this.config.tableTitle = this.translate.instant('admin.queues'); + this.config.columns = this.configureColumns(); + this.configureEntityFunctions(); + return this.config; + }) + ); + } + + configureColumns(): Array> { + return [ + new EntityTableColumn('name', 'admin.queue-name', '25%'), + new EntityTableColumn('partitions', 'admin.queue-partitions', '25%'), + new EntityTableColumn('submitStrategy', 'admin.queue-submit-strategy', '25%', + (entity: QueueInfo) => { + return this.translate.instant(QueueSubmitStrategyTypesMap.get(entity.submitStrategy.type).label); + }, + () => ({}), + false + ), + new EntityTableColumn('processingStrategy', 'admin.queue-processing-strategy', '25%', + (entity: QueueInfo) => { + return this.translate.instant(QueueProcessingStrategyTypesMap.get(entity.processingStrategy.type).label); + }, + () => ({}), + false + ) + ]; + } + + configureEntityFunctions(): void { + this.config.entitiesFetchFunction = pageLink => this.queueService.getTenantQueuesByServiceType(pageLink, this.queueType); + this.config.loadEntity = id => this.queueService.getQueueById(id.id); + this.config.saveEntity = queue => this.queueService.saveQueue(queue, this.queueType).pipe( + mergeMap((savedQueue) => this.queueService.getQueueById(savedQueue.id.id) + )); + this.config.deleteEntity = id => this.queueService.deleteQueue(id.id); + this.config.deleteEnabled = (queue) => queue && queue.name !== 'Main'; + this.config.entitySelectionEnabled = (queue) => queue && queue.name !== 'Main'; + } + + onQueueAction(action: EntityAction): boolean { + switch (action.action) { + case 'open': + this.openQueue(action.event, action.entity); + return true; + } + return false; + } + + private openQueue($event: Event, queue) { + if ($event) { + $event.stopPropagation(); + } + const url = this.router.createUrlTree(['settings', 'queues', queue.id.id]); + this.router.navigateByUrl(url); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library-table-config.resolve.ts b/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library-table-config.resolve.ts index 96745fa47a..ef50352a53 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library-table-config.resolve.ts +++ b/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library-table-config.resolve.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import { EntityTableColumn, EntityTableConfig } from '@home/models/entity/entities-table-config.models'; -import { Resolve } from '@angular/router'; +import { Resolve, Router } from '@angular/router'; import { Resource, ResourceInfo, ResourceTypeTranslationMap } from '@shared/models/resource.models'; import { EntityType, entityTypeResources, entityTypeTranslations } from '@shared/models/entity-type.models'; import { NULL_UUID } from '@shared/models/id/has-uuid'; @@ -46,6 +46,7 @@ export class ResourcesLibraryTableConfigResolver implements Resolve, private resourceService: ResourceService, private translate: TranslateService, + private router: Router, private datePipe: DatePipe) { this.config.entityType = EntityType.TB_RESOURCE; @@ -118,6 +119,14 @@ export class ResourcesLibraryTableConfigResolver implements Resolve): boolean { switch (action.action) { + case 'open': + this.openResource(action.event, action.entity); + return true; case 'downloadResource': this.downloadResource(action.event, action.entity); return true; diff --git a/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library.component.html b/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library.component.html index ff2f8a1085..ca75fa996c 100644 --- a/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library.component.html +++ b/ui-ngx/src/app/modules/home/pages/admin/resource/resources-library.component.html @@ -1,6 +1,6 @@
+ +
+ + + + +
diff --git a/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.scss b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.scss new file mode 100644 index 0000000000..254cc51c22 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.scss @@ -0,0 +1,90 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@import "../../../../../scss/constants"; + +:host { + mat-card.settings-card { + @media #{$mat-md} { + width: 90%; + } + + .fields-group { + margin: 8px 0; + border: 1px groove rgba(0, 0, 0, .25); + border-radius: 4px; + position: relative; + padding-bottom: 8px; + + legend { + color: rgba(0, 0, 0, .7); + width: fit-content; + margin: 0 8px; + } + + .input-row { + padding: 8px 8px 0; + } + + &:last-of-type { + margin-bottom: 24px; + } + } + + .mat-expansion-panel { + box-shadow: none; + margin: 1px 0 0; + + &.provider { + overflow: inherit; + + .mat-expansion-panel-header { + padding: 0 24px 0 8px; + + &.mat-expanded { + height: 48px; + } + + .mat-slide-toggle { + margin-right: 8px; + } + } + + .mat-expansion-panel-header-title { + height: 40px; + } + } + } + } +} + +:host ::ng-deep { + .mat-expansion-panel { + .mat-expansion-panel-content { + font-size: 16px; + } + + &.provider { + .mat-expansion-panel-header > .mat-content { + overflow: inherit; + } + + .mat-expansion-panel-body { + padding: 0 16px 8px 8px; + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts new file mode 100644 index 0000000000..f4c7c2f1c9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/admin/two-factor-auth-settings.component.ts @@ -0,0 +1,246 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'; +import { PageComponent } from '@shared/components/page.component'; +import { HasConfirmForm } from '@core/guards/confirm-on-exit.guard'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + TwoFactorAuthProviderConfigForm, + twoFactorAuthProvidersData, + TwoFactorAuthProviderType, + TwoFactorAuthSettings, + TwoFactorAuthSettingsForm +} from '@shared/models/two-factor-auth.models'; +import { isNotEmptyStr } from '@core/utils'; +import { Subject } from 'rxjs'; +import { takeUntil } from 'rxjs/operators'; +import { MatExpansionPanel } from '@angular/material/expansion'; + +@Component({ + selector: 'tb-2fa-settings', + templateUrl: './two-factor-auth-settings.component.html', + styleUrls: [ './settings-card.scss', './two-factor-auth-settings.component.scss'] +}) +export class TwoFactorAuthSettingsComponent extends PageComponent implements OnInit, HasConfirmForm, OnDestroy { + + private readonly destroy$ = new Subject(); + private readonly posIntValidation = [Validators.required, Validators.min(1), Validators.pattern(/^\d*$/)]; + + twoFaFormGroup: FormGroup; + twoFactorAuthProviderType = TwoFactorAuthProviderType; + twoFactorAuthProvidersData = twoFactorAuthProvidersData; + + @ViewChildren(MatExpansionPanel) expansionPanel: QueryList; + + constructor(protected store: Store, + private twoFaService: TwoFactorAuthenticationService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit() { + this.build2faSettingsForm(); + this.twoFaService.getTwoFaSettings().subscribe((setting) => { + this.setAuthConfigFormValue(setting); + }); + } + + ngOnDestroy() { + super.ngOnDestroy(); + this.destroy$.next(); + this.destroy$.complete(); + } + + confirmForm(): FormGroup { + return this.twoFaFormGroup; + } + + save() { + if (this.twoFaFormGroup.valid) { + const setting = this.twoFaFormGroup.getRawValue() as TwoFactorAuthSettingsForm; + this.joinRateLimit(setting, 'verificationCodeCheckRateLimit'); + const providers = setting.providers.filter(provider => provider.enable); + providers.forEach(provider => delete provider.enable); + const config = Object.assign(setting, {providers}); + this.twoFaService.saveTwoFaSettings(config).subscribe( + (settings) => { + this.setAuthConfigFormValue(settings); + this.twoFaFormGroup.markAsUntouched(); + this.twoFaFormGroup.markAsPristine(); + } + ); + } else { + Object.keys(this.twoFaFormGroup.controls).forEach(field => { + const control = this.twoFaFormGroup.get(field); + control.markAsTouched({onlySelf: true}); + }); + } + } + + toggleExtensionPanel($event: Event, index: number, currentState: boolean) { + if ($event) { + $event.stopPropagation(); + } + if (currentState) { + this.getByIndexPanel(index).close(); + } else { + this.getByIndexPanel(index).open(); + } + } + + trackByElement(i: number, item: any) { + return item; + } + + get providersForm(): FormArray { + return this.twoFaFormGroup.get('providers') as FormArray; + } + + private build2faSettingsForm(): void { + this.twoFaFormGroup = this.fb.group({ + maxVerificationFailuresBeforeUserLockout: [30, [ + Validators.pattern(/^\d*$/), + Validators.min(0), + Validators.max(65535) + ]], + totalAllowedTimeForVerification: [3600, [ + Validators.required, + Validators.min(60), + Validators.pattern(/^\d*$/) + ]], + verificationCodeCheckRateLimitEnable: [false], + verificationCodeCheckRateLimitNumber: [{value: 3, disabled: true}, this.posIntValidation], + verificationCodeCheckRateLimitTime: [{value: 900, disabled: true}, this.posIntValidation], + minVerificationCodeSendPeriod: ['30', [Validators.required, Validators.min(5), Validators.pattern(/^\d*$/)]], + providers: this.fb.array([]) + }); + Object.values(TwoFactorAuthProviderType).forEach(provider => { + this.buildProvidersSettingsForm(provider); + }); + this.twoFaFormGroup.get('verificationCodeCheckRateLimitEnable').valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe(value => { + if (value) { + this.twoFaFormGroup.get('verificationCodeCheckRateLimitNumber').enable({emitEvent: false}); + this.twoFaFormGroup.get('verificationCodeCheckRateLimitTime').enable({emitEvent: false}); + } else { + this.twoFaFormGroup.get('verificationCodeCheckRateLimitNumber').disable({emitEvent: false}); + this.twoFaFormGroup.get('verificationCodeCheckRateLimitTime').disable({emitEvent: false}); + } + }); + this.providersForm.valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe((value: TwoFactorAuthProviderConfigForm[]) => { + const activeProvider = value.filter(provider => provider.enable); + const indexBackupCode = Object.values(TwoFactorAuthProviderType).indexOf(TwoFactorAuthProviderType.BACKUP_CODE); + if (!activeProvider.length || + activeProvider.length === 1 && activeProvider[0].providerType === TwoFactorAuthProviderType.BACKUP_CODE) { + this.providersForm.at(indexBackupCode).get('enable').setValue(false, {emitEvent: false}); + this.providersForm.at(indexBackupCode).disable( {emitEvent: false}); + this.providersForm.at(indexBackupCode).get('providerType').enable({emitEvent: false}); + } else { + this.providersForm.at(indexBackupCode).get('enable').enable( {emitEvent: false}); + } + }); + } + + private setAuthConfigFormValue(settings: TwoFactorAuthSettings) { + const [checkRateLimitNumber, checkRateLimitTime] = this.splitRateLimit(settings?.verificationCodeCheckRateLimit); + const allowProvidersConfig = settings?.providers.map(provider => provider.providerType) || []; + const processFormValue: TwoFactorAuthSettingsForm = Object.assign({}, settings, { + verificationCodeCheckRateLimitEnable: checkRateLimitNumber > 0, + verificationCodeCheckRateLimitNumber: checkRateLimitNumber || 3, + verificationCodeCheckRateLimitTime: checkRateLimitTime || 900, + providers: [] + }); + if (checkRateLimitNumber > 0) { + this.getByIndexPanel(this.providersForm.length).open(); + } + Object.values(TwoFactorAuthProviderType).forEach((provider, index) => { + const findIndex = allowProvidersConfig.indexOf(provider); + if (findIndex > -1) { + processFormValue.providers.push(Object.assign(settings.providers[findIndex], {enable: true})); + this.getByIndexPanel(index).open(); + } else { + processFormValue.providers.push({enable: false}); + } + }); + this.twoFaFormGroup.patchValue(processFormValue); + } + + private buildProvidersSettingsForm(provider: TwoFactorAuthProviderType) { + const formControlConfig: {[key: string]: any} = { + providerType: [provider], + enable: [false] + }; + switch (provider) { + case TwoFactorAuthProviderType.TOTP: + formControlConfig.issuerName = [{value: 'ThingsBoard', disabled: true}, [Validators.required, Validators.pattern(/^\S+$/)]]; + break; + case TwoFactorAuthProviderType.SMS: + formControlConfig.smsVerificationMessageTemplate = [{value: 'Verification code: ${code}', disabled: true}, [ + Validators.required, + Validators.pattern(/\${code}/) + ]]; + formControlConfig.verificationCodeLifetime = [{value: 120, disabled: true}, this.posIntValidation]; + break; + case TwoFactorAuthProviderType.EMAIL: + formControlConfig.verificationCodeLifetime = [{value: 120, disabled: true}, this.posIntValidation]; + break; + case TwoFactorAuthProviderType.BACKUP_CODE: + formControlConfig.codesQuantity = [{value: 10, disabled: true}, this.posIntValidation]; + break; + } + const newProviders = this.fb.group(formControlConfig); + newProviders.get('enable').valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe(value => { + if (value) { + newProviders.enable({emitEvent: false}); + } else { + newProviders.disable({emitEvent: false}); + newProviders.get('enable').enable({emitEvent: false}); + newProviders.get('providerType').enable({emitEvent: false}); + } + }); + this.providersForm.push(newProviders, {emitEvent: false}); + } + + private getByIndexPanel(index: number) { + return this.expansionPanel.find((_, i) => i === index); + } + + private splitRateLimit(setting: string): [number, number] { + if (isNotEmptyStr(setting)) { + const [attemptNumber, time] = setting.split(':'); + return [parseInt(attemptNumber, 10), parseInt(time, 10)]; + } + return [0, 0]; + } + + private joinRateLimit(processFormValue: TwoFactorAuthSettingsForm, property: string) { + if (processFormValue[`${property}Enable`]) { + processFormValue[property] = [processFormValue[`${property}Number`], processFormValue[`${property}Time`]].join(':'); + } + delete processFormValue[`${property}Enable`]; + delete processFormValue[`${property}Number`]; + delete processFormValue[`${property}Time`]; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/api-usage/api-usage-routing.module.ts b/ui-ngx/src/app/modules/home/pages/api-usage/api-usage-routing.module.ts index 9566ff4d78..f1db71d466 100644 --- a/ui-ngx/src/app/modules/home/pages/api-usage/api-usage-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/api-usage/api-usage-routing.module.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/pages/api-usage/api-usage.component.html b/ui-ngx/src/app/modules/home/pages/api-usage/api-usage.component.html index fdee0db508..6563b6d941 100644 --- a/ui-ngx/src/app/modules/home/pages/api-usage/api-usage.component.html +++ b/ui-ngx/src/app/modules/home/pages/api-usage/api-usage.component.html @@ -1,6 +1,6 @@
+ - - - -
-
- - profile.current-password - - lock - - - - login.new-password - - lock - - - - login.new-password-again - - lock - - -
-
- - -
- diff --git a/ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.ts deleted file mode 100644 index 4c28b8eaa8..0000000000 --- a/ui-ngx/src/app/modules/home/pages/profile/change-password-dialog.component.ts +++ /dev/null @@ -1,70 +0,0 @@ -/// -/// Copyright © 2016-2021 The Thingsboard Authors -/// -/// Licensed under the Apache License, Version 2.0 (the "License"); -/// you may not use this file except in compliance with the License. -/// You may obtain a copy of the License at -/// -/// http://www.apache.org/licenses/LICENSE-2.0 -/// -/// Unless required by applicable law or agreed to in writing, software -/// distributed under the License is distributed on an "AS IS" BASIS, -/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -/// See the License for the specific language governing permissions and -/// limitations under the License. -/// - -import { Component, OnInit } from '@angular/core'; -import { MatDialogRef } from '@angular/material/dialog'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { FormBuilder, FormGroup } from '@angular/forms'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { TranslateService } from '@ngx-translate/core'; -import { AuthService } from '@core/auth/auth.service'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { Router } from '@angular/router'; - -@Component({ - selector: 'tb-change-password-dialog', - templateUrl: './change-password-dialog.component.html', - styleUrls: ['./change-password-dialog.component.scss'] -}) -export class ChangePasswordDialogComponent extends DialogComponent implements OnInit { - - changePassword: FormGroup; - - constructor(protected store: Store, - protected router: Router, - private translate: TranslateService, - private authService: AuthService, - public dialogRef: MatDialogRef, - public fb: FormBuilder) { - super(store, router, dialogRef); - } - - ngOnInit(): void { - this.buildChangePasswordForm(); - } - - buildChangePasswordForm() { - this.changePassword = this.fb.group({ - currentPassword: [''], - newPassword: [''], - newPassword2: [''] - }); - } - - onChangePassword(): void { - if (this.changePassword.get('newPassword').value !== this.changePassword.get('newPassword2').value) { - this.store.dispatch(new ActionNotificationShow({ message: this.translate.instant('login.passwords-mismatch-error'), - type: 'error' })); - } else { - this.authService.changePassword( - this.changePassword.get('currentPassword').value, - this.changePassword.get('newPassword').value).subscribe(() => { - this.dialogRef.close(true); - }); - } - } -} diff --git a/ui-ngx/src/app/modules/home/pages/profile/profile-routing.module.ts b/ui-ngx/src/app/modules/home/pages/profile/profile-routing.module.ts index f3fb0512e2..440db606fd 100644 --- a/ui-ngx/src/app/modules/home/pages/profile/profile-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/profile/profile-routing.module.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/modules/home/pages/profile/profile.component.html b/ui-ngx/src/app/modules/home/pages/profile/profile.component.html index 6d1eeaf3ac..3a15616055 100644 --- a/ui-ngx/src/app/modules/home/pages/profile/profile.component.html +++ b/ui-ngx/src/app/modules/home/pages/profile/profile.component.html @@ -1,6 +1,6 @@ + +

security.2fa.dialog.get-backup-code-title

+ + +
+ + +
+
+

security.2fa.dialog.backup-code-description

+
+
+ {{ code }} +
+
+
+ + +
+

security.2fa.dialog.backup-code-warn

+
+ +
+
diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-auth-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-auth-dialog.component.ts new file mode 100644 index 0000000000..5d3a26b13d --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-auth-dialog.component.ts @@ -0,0 +1,88 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder } from '@angular/forms'; +import { + AccountTwoFaSettings, + BackupCodeTwoFactorAuthAccountConfig, + TwoFactorAuthProviderType +} from '@shared/models/two-factor-auth.models'; +import { mergeMap, tap } from 'rxjs/operators'; +import { ImportExportService } from '@home/components/import-export/import-export.service'; +import { deepClone } from '@core/utils'; + +import printTemplate from '!raw-loader!./backup-code-print-template.raw'; + +@Component({ + selector: 'tb-backup-code-auth-dialog', + templateUrl: './backup-code-auth-dialog.component.html', + styleUrls: ['./authentication-dialog.component.scss'] +}) +export class BackupCodeAuthDialogComponent extends DialogComponent { + + private config: AccountTwoFaSettings; + backupCode: BackupCodeTwoFactorAuthAccountConfig; + + constructor(protected store: Store, + protected router: Router, + private twoFaService: TwoFactorAuthenticationService, + private importExportService: ImportExportService, + public dialogRef: MatDialogRef, + public fb: FormBuilder) { + super(store, router, dialogRef); + this.twoFaService.generateTwoFaAccountConfig(TwoFactorAuthProviderType.BACKUP_CODE).pipe( + tap((data: BackupCodeTwoFactorAuthAccountConfig) => this.backupCode = data), + mergeMap(data => this.twoFaService.verifyAndSaveTwoFaAccountConfig(data, null, {ignoreLoading: true})) + ).subscribe((config) => { + this.config = config; + }); + } + + closeDialog() { + this.dialogRef.close(this.config); + } + + downloadFile() { + this.importExportService.exportText(this.backupCode.codes, 'backup-codes'); + } + + printCode() { + const codeTemplate = deepClone(this.backupCode.codes) + .map(code => `
${code}
`).join(''); + const printPage = printTemplate.replace('${codesBlock}', codeTemplate); + const newWindow = window.open('', 'Print backup code'); + + newWindow.document.open(); + newWindow.document.write(printPage); + + setTimeout(() => { + newWindow.print(); + + newWindow.document.close(); + + setTimeout(() => { + newWindow.close(); + }, 10); + }, 0); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-print-template.raw b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-print-template.raw new file mode 100644 index 0000000000..1ab7efc79f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/backup-code-print-template.raw @@ -0,0 +1,50 @@ + + + + + Backup code + + + + + +
+
+

+ Backup codes +

+
+ ${codesBlock} +
+
+
+ + diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.html b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.html new file mode 100644 index 0000000000..45663845be --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.html @@ -0,0 +1,111 @@ + + +

security.2fa.dialog.enable-email-title

+ + +
+ + +
+
+ + + done + + + {{ 'security.2fa.dialog.email-step-label' | translate }} +
+

security.2fa.dialog.email-step-description

+
+ + + + + {{ 'user.email-required' | translate }} + + + {{ 'user.invalid-email-format' | translate }} + + + +
+
+
+ + {{ 'security.2fa.dialog.verification-step-label' | translate }} +
+

+ {{ 'security.2fa.dialog.verification-step-description' | translate : {address: emailConfigForm.get('email').value} }} +

+
+ + + + + {{ 'security.2fa.dialog.verification-code-invalid' | translate }} + + +
+ + +
+
+
+
+ + {{ 'security.2fa.dialog.activation-step-label' | translate }} +
+

security.2fa.dialog.success

+

security.2fa.dialog.activation-step-description-email

+
+ +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.ts new file mode 100644 index 0000000000..385ea0e818 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/email-auth-dialog.component.ts @@ -0,0 +1,113 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, Inject, ViewChild } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + AccountTwoFaSettings, + TwoFactorAuthAccountConfig, + TwoFactorAuthProviderType +} from '@shared/models/two-factor-auth.models'; +import { MatStepper } from '@angular/material/stepper'; + +export interface EmailAuthDialogData { + email: string; +} + +@Component({ + selector: 'tb-email-auth-dialog', + templateUrl: './email-auth-dialog.component.html', + styleUrls: ['./authentication-dialog.component.scss'] +}) +export class EmailAuthDialogComponent extends DialogComponent { + + private authAccountConfig: TwoFactorAuthAccountConfig; + private config: AccountTwoFaSettings; + + emailConfigForm: FormGroup; + emailVerificationForm: FormGroup; + + @ViewChild('stepper', {static: false}) stepper: MatStepper; + + constructor(protected store: Store, + protected router: Router, + private twoFaService: TwoFactorAuthenticationService, + @Inject(MAT_DIALOG_DATA) public data: EmailAuthDialogData, + public dialogRef: MatDialogRef, + public fb: FormBuilder) { + super(store, router, dialogRef); + + this.emailConfigForm = this.fb.group({ + email: [this.data.email, [Validators.required, Validators.email]] + }); + + this.emailVerificationForm = this.fb.group({ + verificationCode: ['', [ + Validators.required, + Validators.minLength(6), + Validators.maxLength(6), + Validators.pattern(/^\d*$/) + ]] + }); + } + + nextStep() { + switch (this.stepper.selectedIndex) { + case 0: + if (this.emailConfigForm.valid) { + this.authAccountConfig = { + providerType: TwoFactorAuthProviderType.EMAIL, + useByDefault: true, + email: this.emailConfigForm.get('email').value as string + }; + this.twoFaService.submitTwoFaAccountConfig(this.authAccountConfig).subscribe(() => { + this.stepper.next(); + }); + } else { + this.showFormErrors(this.emailConfigForm); + } + break; + case 1: + if (this.emailVerificationForm.valid) { + this.twoFaService.verifyAndSaveTwoFaAccountConfig(this.authAccountConfig, + this.emailVerificationForm.get('verificationCode').value).subscribe((config) => { + this.config = config; + this.stepper.next(); + }); + } else { + this.showFormErrors(this.emailVerificationForm); + } + break; + } + } + + closeDialog() { + return this.dialogRef.close(this.config); + } + + private showFormErrors(form: FormGroup) { + Object.keys(form.controls).forEach(field => { + const control = form.get(field); + control.markAsTouched({onlySelf: true}); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.html b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.html new file mode 100644 index 0000000000..aace1d7152 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.html @@ -0,0 +1,104 @@ + + +

security.2fa.dialog.enable-sms-title

+ + +
+ + +
+
+ + + done + + + {{ 'security.2fa.dialog.sms-step-label' | translate }} +
+

security.2fa.dialog.sms-step-description

+
+ + + +
+
+
+ + {{ 'security.2fa.dialog.verification-step-label' | translate }} +
+

+ {{ 'security.2fa.dialog.verification-step-description' | translate : {address: smsConfigForm.get('phone').value} }} +

+
+ + + + + {{ 'security.2fa.dialog.verification-code-invalid' | translate }} + + +
+ + +
+
+
+
+ + {{ 'security.2fa.dialog.activation-step-label' | translate }} +
+

security.2fa.dialog.success

+

security.2fa.dialog.activation-step-description-sms

+
+ +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.ts new file mode 100644 index 0000000000..7ab946b86f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/sms-auth-dialog.component.ts @@ -0,0 +1,111 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ViewChild } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + AccountTwoFaSettings, + TwoFactorAuthAccountConfig, + TwoFactorAuthProviderType +} from '@shared/models/two-factor-auth.models'; +import { phoneNumberPattern } from '@shared/models/settings.models'; +import { MatStepper } from '@angular/material/stepper'; + +@Component({ + selector: 'tb-sms-auth-dialog', + templateUrl: './sms-auth-dialog.component.html', + styleUrls: ['./authentication-dialog.component.scss'] +}) +export class SMSAuthDialogComponent extends DialogComponent { + + private authAccountConfig: TwoFactorAuthAccountConfig; + private config: AccountTwoFaSettings; + + phoneNumberPattern = phoneNumberPattern; + + smsConfigForm: FormGroup; + smsVerificationForm: FormGroup; + + @ViewChild('stepper', {static: false}) stepper: MatStepper; + + constructor(protected store: Store, + protected router: Router, + private twoFaService: TwoFactorAuthenticationService, + public dialogRef: MatDialogRef, + public fb: FormBuilder) { + super(store, router, dialogRef); + + this.smsConfigForm = this.fb.group({ + phone: ['', [Validators.required, Validators.pattern(phoneNumberPattern)]] + }); + + this.smsVerificationForm = this.fb.group({ + verificationCode: ['', [ + Validators.required, + Validators.minLength(6), + Validators.maxLength(6), + Validators.pattern(/^\d*$/) + ]] + }); + } + + nextStep() { + switch (this.stepper.selectedIndex) { + case 0: + if (this.smsConfigForm.valid) { + this.authAccountConfig = { + providerType: TwoFactorAuthProviderType.SMS, + useByDefault: true, + phoneNumber: this.smsConfigForm.get('phone').value as string + }; + this.twoFaService.submitTwoFaAccountConfig(this.authAccountConfig).subscribe(() => { + this.stepper.next(); + }); + } else { + this.showFormErrors(this.smsConfigForm); + } + break; + case 1: + if (this.smsVerificationForm.valid) { + this.twoFaService.verifyAndSaveTwoFaAccountConfig(this.authAccountConfig, + this.smsVerificationForm.get('verificationCode').value).subscribe((config) => { + this.config = config; + this.stepper.next(); + }); + } else { + this.showFormErrors(this.smsVerificationForm); + } + break; + } + } + + closeDialog() { + return this.dialogRef.close(this.config); + } + + private showFormErrors(form: FormGroup) { + Object.keys(form.controls).forEach(field => { + const control = form.get(field); + control.markAsTouched({onlySelf: true}); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.html b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.html new file mode 100644 index 0000000000..695d39860f --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.html @@ -0,0 +1,94 @@ + + +

security.2fa.dialog.enable-totp-title

+ + +
+ + +
+
+ + + done + + + {{ 'security.2fa.dialog.totp-step-label' | translate }} +
+

security.2fa.dialog.totp-step-description-open

+

security.2fa.dialog.totp-step-description-install

+
+ +
+
+
+ + {{ 'security.2fa.dialog.verification-step-label' | translate }} +
+

security.2fa.dialog.scan-qr-code

+ +

security.2fa.dialog.enter-verification-code

+ + + + + {{ 'security.2fa.dialog.verification-code-invalid' | translate }} + + +
+
+ +
+
+ + {{ 'security.2fa.dialog.activation-step-label' | translate }} +
+

security.2fa.dialog.success

+

security.2fa.dialog.activation-step-description-totp

+
+ +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.ts b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.ts new file mode 100644 index 0000000000..8bda837df3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/authentication-dialog/totp-auth-dialog.component.ts @@ -0,0 +1,93 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, ViewChild } from '@angular/core'; +import { DialogComponent } from '@shared/components/dialog.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { Router } from '@angular/router'; +import { MatDialogRef } from '@angular/material/dialog'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + AccountTwoFaSettings, + TotpTwoFactorAuthAccountConfig, + TwoFactorAuthProviderType +} from '@shared/models/two-factor-auth.models'; +import { MatStepper } from '@angular/material/stepper'; + +@Component({ + selector: 'tb-totp-auth-dialog', + templateUrl: './totp-auth-dialog.component.html', + styleUrls: ['./authentication-dialog.component.scss'] +}) +export class TotpAuthDialogComponent extends DialogComponent { + + private authAccountConfig: TotpTwoFactorAuthAccountConfig; + private config: AccountTwoFaSettings; + + totpConfigForm: FormGroup; + totpAuthURL: string; + + @ViewChild('stepper', {static: false}) stepper: MatStepper; + @ViewChild('canvas', {static: false}) canvasRef: ElementRef; + + constructor(protected store: Store, + protected router: Router, + private twoFaService: TwoFactorAuthenticationService, + public dialogRef: MatDialogRef, + public fb: FormBuilder) { + super(store, router, dialogRef); + this.twoFaService.generateTwoFaAccountConfig(TwoFactorAuthProviderType.TOTP).subscribe(accountConfig => { + this.authAccountConfig = accountConfig as TotpTwoFactorAuthAccountConfig; + this.totpAuthURL = this.authAccountConfig.authUrl; + this.authAccountConfig.useByDefault = true; + import('qrcode').then((QRCode) => { + QRCode.toCanvas(this.canvasRef.nativeElement, this.totpAuthURL); + this.canvasRef.nativeElement.style.width = 'auto'; + this.canvasRef.nativeElement.style.height = 'auto'; + }); + }); + this.totpConfigForm = this.fb.group({ + verificationCode: ['', [ + Validators.required, + Validators.minLength(6), + Validators.maxLength(6), + Validators.pattern(/^\d*$/) + ]] + }); + } + + onSaveConfig() { + if (this.totpConfigForm.valid) { + this.twoFaService.verifyAndSaveTwoFaAccountConfig(this.authAccountConfig, + this.totpConfigForm.get('verificationCode').value).subscribe((config) => { + this.config = config; + this.stepper.next(); + }); + } else { + Object.keys(this.totpConfigForm.controls).forEach(field => { + const control = this.totpConfigForm.get(field); + control.markAsTouched({onlySelf: true}); + }); + } + } + + closeDialog() { + return this.dialogRef.close(this.config); + } + +} diff --git a/ui-ngx/src/app/modules/home/pages/security/security-routing.module.ts b/ui-ngx/src/app/modules/home/pages/security/security-routing.module.ts new file mode 100644 index 0000000000..430635cd8e --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/security-routing.module.ts @@ -0,0 +1,84 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Injectable, NgModule } from '@angular/core'; +import { Resolve, RouterModule, Routes } from '@angular/router'; + +import { SecurityComponent } from './security.component'; +import { ConfirmOnExitGuard } from '@core/guards/confirm-on-exit.guard'; +import { Authority } from '@shared/models/authority.enum'; +import { User } from '@shared/models/user.model'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { UserService } from '@core/http/user.service'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { Observable } from 'rxjs'; +import { TwoFactorAuthProviderType } from '@shared/models/two-factor-auth.models'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; + +@Injectable() +export class UserProfileResolver implements Resolve { + + constructor(private store: Store, + private userService: UserService) { + } + + resolve(): Observable { + const userId = getCurrentAuthUser(this.store).userId; + return this.userService.getUser(userId); + } +} + +@Injectable() +export class UserTwoFAProvidersResolver implements Resolve> { + + constructor(private twoFactorAuthService: TwoFactorAuthenticationService) { + } + + resolve(): Observable> { + return this.twoFactorAuthService.getAvailableTwoFaProviders(); + } +} + +const routes: Routes = [ + { + path: 'security', + component: SecurityComponent, + canDeactivate: [ConfirmOnExitGuard], + data: { + auth: [Authority.SYS_ADMIN, Authority.TENANT_ADMIN, Authority.CUSTOMER_USER], + title: 'security.security', + breadcrumb: { + label: 'security.security', + icon: 'lock' + } + }, + resolve: { + user: UserProfileResolver, + providers: UserTwoFAProvidersResolver + } + } +]; + +@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule], + providers: [ + UserProfileResolver, + UserTwoFAProvidersResolver + ] +}) +export class SecurityRoutingModule { } diff --git a/ui-ngx/src/app/modules/home/pages/security/security.component.html b/ui-ngx/src/app/modules/home/pages/security/security.component.html new file mode 100644 index 0000000000..a79f2397b2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/security.component.html @@ -0,0 +1,173 @@ + +
+ + + profile.jwt-token + + +
+
{{ 'profile.token-valid-till' | translate }} {{ jwtTokenExpiration | date: 'yyyy-MM-dd HH:mm:ss' }}
+ +
+
+
+ + +
+
+
+

profile.change-password

+ + profile.current-password + + + + {{ 'security.password-requirement.incorrect-password-try-again' | translate }} + + + + login.new-password + + + + {{ 'security.password-requirement.password-not-meet-requirements' | translate }} + + + {{ changePassword.get('newPassword').getError('alreadyUsed') }} + + + {{ 'security.password-requirement.password-should-difference' | translate }} + + + {{ 'security.password-requirement.password-should-not-contain-spaces' | translate }} + + +
+ +
+ + login.new-password-again + + + + {{ 'security.password-requirement.new-passwords-not-match' | translate }} + + +
+ +
+ +
+
+ +
+

security.password-requirement.password-requirements

+

security.password-requirement.at-least

+

+ + {{ 'security.password-requirement.uppercase-letter' | translate : {count: passwordPolicy.minimumUppercaseLetters} }} +

+

+ + {{ 'security.password-requirement.lowercase-letter' | translate : {count: passwordPolicy.minimumLowercaseLetters} }} +

+

+ + {{ 'security.password-requirement.digit' | translate : {count: passwordPolicy.minimumDigits} }} +

+

+ + {{ 'security.password-requirement.special-character' | translate : {count: passwordPolicy.minimumSpecialCharacters} }} +

+

+ + {{ 'security.password-requirement.character' | translate : {count: passwordPolicy.minimumLength} }} +

+
+
+
+ + +
+
+
+
+ + + admin.2fa.2fa + + +
security.2fa.2fa-description
+
+ +

security.2fa.authenticate-with

+
+ +
+

{{ providersData.get(provider).name | translate }}

+
+
+ {{ providersData.get(provider).description | translate }} +
+ +
+ {{ providersData.get(provider).activatedHint | translate: providerDataInfo(provider) }} +
+
+ + +
+ + security.2fa.main-2fa-method + + +
+ +
+
+
+
+
diff --git a/ui-ngx/src/app/modules/home/pages/security/security.component.scss b/ui-ngx/src/app/modules/home/pages/security/security.component.scss new file mode 100644 index 0000000000..b593be3a2a --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/security.component.scss @@ -0,0 +1,130 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@import "../../../../../scss/constants"; + +:host { + .profile-container { + padding: 8px; + } + + mat-card.profile-card { + padding: 24px; + @media #{$mat-gt-sm} { + width: 80%; + } + @media #{$mat-gt-md} { + width: 55%; + } + @media #{$mat-gt-xl} { + width: 45%; + } + + .card-title { + font: 500 18px / 24px Roboto, "Helvetica Neue", sans-serif; + letter-spacing: 0.15px; + margin-top: 0; + } + + .mat-h4 { + font-weight: 500; + font-size: 14px; + letter-spacing: 0.25px; + margin: 0 0 4px; + } + + .change-password { + margin: 0; + + .mat-divider.mat-divider-vertical { + margin-bottom: 25px; + } + + .mat-form-field { + margin-bottom: 4px; + } + + .password-requirements > p { + margin: 0 0 8px; + letter-spacing: 0.25px; + color: rgba(0, 0, 0, 0.87); + } + + .mat-icon[data-mat-icon-name="check"] { + color: #24A148; + } + } + + .auth-title { + font-weight: 500; + margin: 0; + } + + .token-text { + font: 400 14px / 16px Roboto, "Helvetica Neue", sans-serif; + letter-spacing: 0.25px; + padding: 8px 0; + + > .date { + opacity: .7; + } + } + } + + .description { + color: rgba(0, 0, 0, 0.54); + letter-spacing: 0.25px; + margin-right: 8px; + } + + .mat-divider-horizontal { + left: 16px; + right: 16px; + width: auto; + } + + .provider { + padding: 24px 0; + + .provider-title { + font: 400 14px / 16px Roboto, "Helvetica Neue", sans-serif; + letter-spacing: 0.25px; + margin: 0 0 8px; + } + + .description { + max-width: 85%; + } + + .checkbox-label { + font-size: 14px; + letter-spacing: 0.25px; + opacity: 0.87; + } + + .mat-checkbox { + margin-top: 8px; + } + + .mat-stroked-button { + margin-top: 8px; + } + } +} +:host ::ng-deep { + .mat-form-field-appearance-fill .mat-form-field-underline::before { + background-color: transparent; + } +} diff --git a/ui-ngx/src/app/modules/home/pages/security/security.component.ts b/ui-ngx/src/app/modules/home/pages/security/security.component.ts new file mode 100644 index 0000000000..1ecfb66954 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/security.component.ts @@ -0,0 +1,382 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, OnDestroy, OnInit } from '@angular/core'; +import { User } from '@shared/models/user.model'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { + AbstractControl, + FormBuilder, + FormGroup, FormGroupDirective, + NgForm, + ValidationErrors, + ValidatorFn, + Validators +} from '@angular/forms'; +import { TranslateService } from '@ngx-translate/core'; +import { MatDialog } from '@angular/material/dialog'; +import { DialogService } from '@core/services/dialog.service'; +import { ActivatedRoute } from '@angular/router'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { DatePipe } from '@angular/common'; +import { ClipboardService } from 'ngx-clipboard'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + AccountTwoFaSettingProviders, + AccountTwoFaSettings, + BackupCodeTwoFactorAuthAccountConfig, + EmailTwoFactorAuthAccountConfig, + SmsTwoFactorAuthAccountConfig, + twoFactorAuthProvidersData, + TwoFactorAuthProviderType +} from '@shared/models/two-factor-auth.models'; +import { authenticationDialogMap } from '@home/pages/security/authentication-dialog/authentication-dialog.map'; +import { takeUntil, tap } from 'rxjs/operators'; +import { Observable, of, Subject } from 'rxjs'; +import { isDefinedAndNotNull, isEqual } from '@core/utils'; +import { AuthService } from '@core/auth/auth.service'; +import { UserPasswordPolicy } from '@shared/models/settings.models'; + +@Component({ + selector: 'tb-security', + templateUrl: './security.component.html', + styleUrls: ['./security.component.scss'] +}) +export class SecurityComponent extends PageComponent implements OnInit, OnDestroy { + + private readonly destroy$ = new Subject(); + private accountConfig: AccountTwoFaSettingProviders; + + twoFactorAuth: FormGroup; + changePassword: FormGroup; + + user: User; + passwordPolicy: UserPasswordPolicy; + + allowTwoFactorProviders: TwoFactorAuthProviderType[] = []; + providersData = twoFactorAuthProvidersData; + twoFactorAuthProviderType = TwoFactorAuthProviderType; + useByDefault: TwoFactorAuthProviderType = null; + activeSingleProvider = true; + + get jwtToken(): string { + return `Bearer ${localStorage.getItem('jwt_token')}`; + } + + get jwtTokenExpiration(): string { + return localStorage.getItem('jwt_token_expiration'); + } + + get expirationJwtData(): string { + const expirationData = this.datePipe.transform(this.jwtTokenExpiration, 'yyyy-MM-dd HH:mm:ss'); + return this.translate.instant('profile.valid-till', { expirationData }); + } + + constructor(protected store: Store, + private route: ActivatedRoute, + private translate: TranslateService, + private twoFaService: TwoFactorAuthenticationService, + public dialog: MatDialog, + public dialogService: DialogService, + public fb: FormBuilder, + private datePipe: DatePipe, + private authService: AuthService, + private clipboardService: ClipboardService) { + super(store); + } + + ngOnInit() { + this.buildTwoFactorForm(); + this.user = this.route.snapshot.data.user; + this.twoFactorLoad(this.route.snapshot.data.providers); + this.buildChangePasswordForm(); + this.loadPasswordPolicy(); + } + + ngOnDestroy() { + super.ngOnDestroy(); + this.destroy$.next(); + this.destroy$.complete(); + } + + private buildTwoFactorForm() { + this.twoFactorAuth = this.fb.group({ + TOTP: [false], + SMS: [false], + EMAIL: [false], + BACKUP_CODE: [{value: false, disabled: true}] + }); + this.twoFactorAuth.valueChanges.pipe( + takeUntil(this.destroy$) + ).subscribe((value: {TwoFactorAuthProviderType: boolean}) => { + const formActiveValue = Object.keys(value).filter(item => value[item] && item !== TwoFactorAuthProviderType.BACKUP_CODE); + this.activeSingleProvider = formActiveValue.length < 2; + if (formActiveValue.length) { + this.twoFactorAuth.get('BACKUP_CODE').enable({emitEvent: false}); + } else { + this.twoFactorAuth.get('BACKUP_CODE').disable({emitEvent: false}); + } + }); + } + + private twoFactorLoad(providers: TwoFactorAuthProviderType[]) { + if (providers.length) { + this.twoFaService.getAccountTwoFaSettings().subscribe(data => this.processTwoFactorAuthConfig(data)); + Object.values(TwoFactorAuthProviderType).forEach(type => { + if (providers.includes(type)) { + this.allowTwoFactorProviders.push(type); + } + }); + } + } + + private processTwoFactorAuthConfig(setting: AccountTwoFaSettings) { + this.accountConfig = setting?.configs || {}; + Object.values(TwoFactorAuthProviderType).forEach(provider => { + if (this.accountConfig[provider]) { + this.twoFactorAuth.get(provider).setValue(true); + if (this.accountConfig[provider].useByDefault) { + this.useByDefault = provider; + } + } else { + this.twoFactorAuth.get(provider).setValue(false); + } + }); + } + + private buildChangePasswordForm() { + this.changePassword = this.fb.group({ + currentPassword: [''], + newPassword: ['', Validators.required], + newPassword2: ['', this.samePasswordValidation(false, 'newPassword')] + }); + } + + private loadPasswordPolicy() { + this.authService.getUserPasswordPolicy().subscribe(policy => { + this.passwordPolicy = policy; + this.changePassword.get('newPassword').setValidators([ + this.passwordStrengthValidator(), + this.samePasswordValidation(true, 'currentPassword'), + Validators.required + ]); + this.changePassword.get('newPassword').updateValueAndValidity({emitEvent: false}); + }); + } + + private passwordStrengthValidator(): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + const value: string = control.value; + const errors: any = {}; + + if (this.passwordPolicy.minimumUppercaseLetters > 0 && + !new RegExp(`(?:.*?[A-Z]){${this.passwordPolicy.minimumUppercaseLetters}}`).test(value)) { + errors.notUpperCase = true; + } + + if (this.passwordPolicy.minimumLowercaseLetters > 0 && + !new RegExp(`(?:.*?[a-z]){${this.passwordPolicy.minimumLowercaseLetters}}`).test(value)) { + errors.notLowerCase = true; + } + + if (this.passwordPolicy.minimumDigits > 0 + && !new RegExp(`(?:.*?\\d){${this.passwordPolicy.minimumDigits}}`).test(value)) { + errors.notNumeric = true; + } + + if (this.passwordPolicy.minimumSpecialCharacters > 0 && + !new RegExp(`(?:.*?[\\W_]){${this.passwordPolicy.minimumSpecialCharacters}}`).test(value)) { + errors.notSpecial = true; + } + + if (!this.passwordPolicy.allowWhitespaces && /\s/.test(value)) { + errors.hasWhitespaces = true; + } + + if (this.passwordPolicy.minimumLength > 0 && value.length < this.passwordPolicy.minimumLength) { + errors.minLength = true; + } + + return isEqual(errors, {}) ? null : errors; + }; + } + + private samePasswordValidation(isSame: boolean, key: string): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + const value: string = control.value; + const keyValue = control.parent?.value[key]; + + if (isSame) { + return value === keyValue ? {samePassword: true} : null; + } + return value !== keyValue ? {differencePassword: true} : null; + }; + } + + trackByProvider(i: number, provider: TwoFactorAuthProviderType) { + return provider; + } + + copyToken() { + if (+this.jwtTokenExpiration < Date.now()) { + this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('profile.tokenCopiedWarnMessage'), + type: 'warn', + duration: 1500, + verticalPosition: 'bottom', + horizontalPosition: 'right' + })); + } else { + this.clipboardService.copyFromContent(this.jwtToken); + this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('profile.tokenCopiedSuccessMessage'), + type: 'success', + duration: 750, + verticalPosition: 'bottom', + horizontalPosition: 'right' + })); + } + } + + confirm2FAChange(event: MouseEvent, provider: TwoFactorAuthProviderType) { + event.stopPropagation(); + event.preventDefault(); + if (this.twoFactorAuth.get(provider).disabled) { + return; + } + if (this.twoFactorAuth.get(provider).value) { + const providerName = this.translate.instant(`security.2fa.provider.${provider.toLowerCase()}`); + this.dialogService.confirm( + this.translate.instant('security.2fa.disable-2fa-provider-title', {name: providerName}), + this.translate.instant('security.2fa.disable-2fa-provider-text', {name: providerName}), + ).subscribe(res => { + if (res) { + this.twoFactorAuth.disable({emitEvent: false}); + this.twoFaService.deleteTwoFaAccountConfig(provider) + .pipe(tap(() => this.twoFactorAuth.enable({emitEvent: false}))) + .subscribe(data => this.processTwoFactorAuthConfig(data)); + } + }); + } else { + this.createdNewAuthConfig(provider); + } + } + + private createdNewAuthConfig(provider: TwoFactorAuthProviderType) { + const dialogData = provider === TwoFactorAuthProviderType.EMAIL ? {email: this.user.email} : {}; + this.dialog.open(authenticationDialogMap.get(provider), { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: dialogData + }).afterClosed().subscribe(res => { + if (isDefinedAndNotNull(res)) { + this.processTwoFactorAuthConfig(res); + } + }); + } + + changeDefaultProvider(event: MouseEvent, provider: TwoFactorAuthProviderType) { + event.stopPropagation(); + event.preventDefault(); + if (this.useByDefault !== provider) { + this.twoFactorAuth.disable({emitEvent: false}); + this.twoFaService.updateTwoFaAccountConfig(provider, true) + .pipe(tap(() => this.twoFactorAuth.enable({emitEvent: false}))) + .subscribe(data => this.processTwoFactorAuthConfig(data)); + } + } + + generateNewBackupCode() { + const codeLeft = (this.accountConfig[TwoFactorAuthProviderType.BACKUP_CODE] as BackupCodeTwoFactorAuthAccountConfig).codesLeft; + let subscription: Observable; + if (codeLeft) { + subscription = this.dialogService.confirm( + 'Get new set of backup codes?', + `If you get new backup codes, ${codeLeft} remaining codes you have left will be unusable.`, + '', + 'Get new codes' + ); + } else { + subscription = of(true); + } + subscription.subscribe(res => { + if (res) { + this.twoFactorAuth.disable({emitEvent: false}); + this.twoFaService.deleteTwoFaAccountConfig(TwoFactorAuthProviderType.BACKUP_CODE) + .pipe(tap(() => this.twoFactorAuth.enable({emitEvent: false}))) + .subscribe(() => this.createdNewAuthConfig(TwoFactorAuthProviderType.BACKUP_CODE)); + } + }); + } + + providerDataInfo(provider: TwoFactorAuthProviderType) { + const info = {info: null}; + const providerConfig = this.accountConfig[provider]; + if (isDefinedAndNotNull(providerConfig)) { + switch (provider) { + case TwoFactorAuthProviderType.EMAIL: + info.info = (providerConfig as EmailTwoFactorAuthAccountConfig).email; + break; + case TwoFactorAuthProviderType.SMS: + info.info = (providerConfig as SmsTwoFactorAuthAccountConfig).phoneNumber; + break; + case TwoFactorAuthProviderType.BACKUP_CODE: + info.info = (providerConfig as BackupCodeTwoFactorAuthAccountConfig).codesLeft; + break; + } + } + return info; + } + + onChangePassword(form: FormGroupDirective): void { + if (this.changePassword.valid) { + this.authService.changePassword(this.changePassword.get('currentPassword').value, + this.changePassword.get('newPassword').value, {ignoreErrors: true}).subscribe(() => { + this.discardChanges(form); + }, + (error) => { + if (error.status === 400 && error.error.message === 'Current password doesn\'t match!') { + this.changePassword.get('currentPassword').setErrors({differencePassword: true}); + } else if (error.status === 400 && error.error.message.startsWith('Password must')) { + this.loadPasswordPolicy(); + } else if (error.status === 400 && error.error.message.startsWith('Password was already used')) { + this.changePassword.get('newPassword').setErrors({alreadyUsed: error.error.message}); + } else { + this.store.dispatch(new ActionNotificationShow({ + message: error.error.message, + type: 'error', + target: 'changePassword' + })); + } + }); + } else { + this.changePassword.markAllAsTouched(); + } + } + + discardChanges(form: FormGroupDirective, event?: MouseEvent) { + if (event) { + event.stopPropagation(); + } + form.resetForm({ + currentPassword: '', + newPassword: '', + newPassword2: '' + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/security/security.module.ts b/ui-ngx/src/app/modules/home/pages/security/security.module.ts new file mode 100644 index 0000000000..5db12c2a68 --- /dev/null +++ b/ui-ngx/src/app/modules/home/pages/security/security.module.ts @@ -0,0 +1,43 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SecurityComponent } from './security.component'; +import { SharedModule } from '@shared/shared.module'; +import { SecurityRoutingModule } from './security-routing.module'; +import { TotpAuthDialogComponent } from './authentication-dialog/totp-auth-dialog.component'; +import { SMSAuthDialogComponent } from '@home/pages/security/authentication-dialog/sms-auth-dialog.component'; +import { EmailAuthDialogComponent } from '@home/pages/security/authentication-dialog/email-auth-dialog.component'; +import { + BackupCodeAuthDialogComponent +} from '@home/pages/security/authentication-dialog/backup-code-auth-dialog.component'; + +@NgModule({ + declarations: [ + SecurityComponent, + TotpAuthDialogComponent, + SMSAuthDialogComponent, + EmailAuthDialogComponent, + BackupCodeAuthDialogComponent + ], + imports: [ + CommonModule, + SharedModule, + SecurityRoutingModule + ] +}) +export class SecurityModule { } diff --git a/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-routing.module.ts b/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-routing.module.ts index 709bb54e75..b2acabc0d5 100644 --- a/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-routing.module.ts +++ b/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-routing.module.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -20,6 +20,10 @@ import { RouterModule, Routes } from '@angular/router'; import { EntitiesTableComponent } from '../../components/entity/entities-table.component'; import { Authority } from '@shared/models/authority.enum'; import { TenantProfilesTableConfigResolver } from './tenant-profiles-table-config.resolver'; +import { EntityDetailsPageComponent } from '@home/components/entity/entity-details-page.component'; +import { ConfirmOnExitGuard } from '@core/guards/confirm-on-exit.guard'; +import { entityDetailsPageBreadcrumbLabelFunction } from '@home/pages/home-pages.models'; +import { BreadCrumbConfig } from '@shared/components/breadcrumb'; const routes: Routes = [ { @@ -41,6 +45,22 @@ const routes: Routes = [ resolve: { entitiesTableConfig: TenantProfilesTableConfigResolver } + }, + { + path: ':entityId', + component: EntityDetailsPageComponent, + canDeactivate: [ConfirmOnExitGuard], + data: { + breadcrumb: { + labelFunction: entityDetailsPageBreadcrumbLabelFunction, + icon: 'mdi:alpha-t-box' + } as BreadCrumbConfig, + auth: [Authority.SYS_ADMIN], + title: 'tenant-profile.tenant-profiles' + }, + resolve: { + entitiesTableConfig: TenantProfilesTableConfigResolver + } } ] } diff --git a/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-tabs.component.html b/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-tabs.component.html index 7b8e508ab1..4aa21e2aa5 100644 --- a/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-tabs.component.html +++ b/ui-ngx/src/app/modules/home/pages/tenant-profile/tenant-profile-tabs.component.html @@ -1,6 +1,6 @@
+ + {{ 'login.verify-your-identity' | translate }} + + +
+

login.select-way-to-verify

+ + + +
+
+
+
+

{{ providerDescription }}

+
+ + + + + {{ 'security.2fa.dialog.verification-code-invalid' | translate }} + + + {{ 'security.2fa.dialog.verification-code-incorrect' | translate }} + + + {{ 'security.2fa.dialog.verification-code-many-request' | translate }} + + +
+ + + +
+
+
+ {{ 'login.resend-code-wait' | translate : {time: countDownTime} }} +
+ +
+ +
+
+
+
+
+ +
diff --git a/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.scss b/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.scss new file mode 100644 index 0000000000..248d719b7b --- /dev/null +++ b/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.scss @@ -0,0 +1,94 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@import '../../../../../scss/constants'; + +:host { + display: flex; + flex: 1 1 0; + + .tb-two-factor-auth-login-content { + background-color: #eee; + + .tb-two-factor-auth-login-card { + padding: 48px 48px 48px 16px; + + @media #{$mat-gt-xs} { + width: 450px !important; + } + + .mat-card-title { + font: 400 28px / 36px Roboto, "Helvetica Neue", sans-serif; + } + + .mat-card-content { + margin-top: 44px; + margin-left: 40px; + } + + .mat-body { + letter-spacing: 0.25px; + line-height: 16px; + margin: 0; + } + + .code-block { + margin-top: 16px; + } + + .providers-container { + padding: 0; + + .mat-body { + padding-bottom: 8px; + } + } + + .timer { + font: 500 12px / 14px Roboto, "Helvetica Neue", sans-serif; + color: rgba(255, 255, 255, 0.8); + } + + .action-row:nth-child(n) { + min-height: 36px; + + .action-resend { + min-width: 50%; + } + } + } + } + + ::ng-deep { + button.provider { + text-align: start; + font-weight: 400; + + &:not(.mat-button-disabled) { + border-color: rgba(255, 255, 255, .8); + } + + .icon { + height: 18px; + width: 18px; + vertical-align: sub; + } + } + + .mat-form-field-invalid .mat-hint { + margin-top: 20px; + } + } +} diff --git a/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.ts b/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.ts new file mode 100644 index 0000000000..2a98f0b530 --- /dev/null +++ b/ui-ngx/src/app/modules/login/pages/login/two-factor-auth-login.component.ts @@ -0,0 +1,205 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, OnDestroy, OnInit } from '@angular/core'; +import { AuthService } from '@core/auth/auth.service'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { PageComponent } from '@shared/components/page.component'; +import { FormBuilder, Validators } from '@angular/forms'; +import { TwoFactorAuthenticationService } from '@core/http/two-factor-authentication.service'; +import { + twoFactorAuthProvidersLoginData, + TwoFactorAuthProviderType, + TwoFaProviderInfo +} from '@shared/models/two-factor-auth.models'; +import { TranslateService } from '@ngx-translate/core'; +import { interval, Subscription } from 'rxjs'; +import { isEqual } from '@core/utils'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; + +@Component({ + selector: 'tb-two-factor-auth-login', + templateUrl: './two-factor-auth-login.component.html', + styleUrls: ['./two-factor-auth-login.component.scss'] +}) +export class TwoFactorAuthLoginComponent extends PageComponent implements OnInit, OnDestroy { + + private providersInfo: TwoFaProviderInfo[]; + private prevProvider: TwoFactorAuthProviderType; + private timer: Subscription; + private minVerificationPeriod = 0; + private timerID: NodeJS.Timeout; + + showResendAction = false; + selectedProvider: TwoFactorAuthProviderType; + allowProviders: TwoFactorAuthProviderType[] = []; + + providersData = twoFactorAuthProvidersLoginData; + providerDescription = ''; + hideResendButton = true; + countDownTime = 0; + + maxLengthInput = 6; + inputMode = 'numeric'; + pattern = '[0-9]*'; + + verificationForm = this.fb.group({ + verificationCode: ['', [ + Validators.required, + Validators.minLength(6), + Validators.maxLength(6), + Validators.pattern(/^\d*$/) + ]] + }); + + constructor(protected store: Store, + private twoFactorAuthService: TwoFactorAuthenticationService, + private authService: AuthService, + private translate: TranslateService, + private fb: FormBuilder) { + super(store); + } + + ngOnInit() { + this.providersInfo = this.authService.twoFactorAuthProviders; + Object.values(TwoFactorAuthProviderType).forEach(provider => { + const providerConfig = this.providersInfo.find(config => config.type === provider); + if (providerConfig) { + if (providerConfig.default) { + this.selectedProvider = providerConfig.type; + this.providerDescription = this.translate.instant(this.providersData.get(providerConfig.type).description, { + contact: providerConfig.contact + }); + this.minVerificationPeriod = providerConfig?.minVerificationCodeSendPeriod || 30; + } + this.allowProviders.push(providerConfig.type); + } + }); + if (this.selectedProvider !== TwoFactorAuthProviderType.TOTP) { + this.sendCode(); + this.showResendAction = true; + } + this.timer = interval(1000).subscribe(() => this.updatedTime()); + } + + ngOnDestroy() { + super.ngOnDestroy(); + this.timer.unsubscribe(); + clearTimeout(this.timerID); + } + + sendVerificationCode() { + if (this.verificationForm.valid && this.selectedProvider) { + this.authService.checkTwoFaVerificationCode(this.selectedProvider, this.verificationForm.get('verificationCode').value).subscribe( + () => {}, + (error) => { + if (error.status === 400) { + this.verificationForm.get('verificationCode').setErrors({incorrectCode: true}); + } else if (error.status === 429) { + this.verificationForm.get('verificationCode').setErrors({tooManyRequest: true}); + this.timerID = setTimeout(() => { + let errors = this.verificationForm.get('verificationCode').errors; + delete errors.tooManyRequest; + if (isEqual(errors, {})) { + errors = null; + } + this.verificationForm.get('verificationCode').setErrors(errors); + }, 5000); + } else { + this.store.dispatch(new ActionNotificationShow({ + message: error.error.message, + type: 'error', + verticalPosition: 'top', + horizontalPosition: 'left' + })); + } + } + ); + } + } + + selectProvider(type: TwoFactorAuthProviderType) { + this.prevProvider = type === null ? this.selectedProvider : null; + this.selectedProvider = type; + this.showResendAction = false; + if (type !== null) { + this.verificationForm.get('verificationCode').reset(); + const providerConfig = this.providersInfo.find(config => config.type === type); + this.providerDescription = this.translate.instant(this.providersData.get(providerConfig.type).description, { + contact: providerConfig.contact + }); + if (type !== TwoFactorAuthProviderType.TOTP && type !== TwoFactorAuthProviderType.BACKUP_CODE) { + this.sendCode(); + this.showResendAction = true; + this.minVerificationPeriod = providerConfig?.minVerificationCodeSendPeriod || 30; + } + if (type === TwoFactorAuthProviderType.BACKUP_CODE) { + this.verificationForm.get('verificationCode').setValidators([ + Validators.required, + Validators.minLength(8), + Validators.maxLength(8), + Validators.pattern(/^[\dabcdef]*$/) + ]); + this.maxLengthInput = 8; + this.inputMode = 'text'; + this.pattern = '[0-9abcdef]*'; + } else { + this.verificationForm.get('verificationCode').setValidators([ + Validators.required, + Validators.minLength(6), + Validators.maxLength(6), + Validators.pattern(/^\d*$/) + ]); + this.maxLengthInput = 6; + this.inputMode = 'numeric'; + this.pattern = '[0-9]*'; + } + this.verificationForm.get('verificationCode').updateValueAndValidity({emitEvent: false}); + } + } + + sendCode($event?: Event) { + if ($event) { + $event.stopPropagation(); + } + this.hideResendButton = true; + this.countDownTime = 0; + this.twoFactorAuthService.requestTwoFaVerificationCodeSend(this.selectedProvider).subscribe(() => { + this.countDownTime = this.minVerificationPeriod; + }, () => { + this.countDownTime = this.minVerificationPeriod; + }); + } + + cancelLogin() { + if (this.prevProvider) { + this.selectedProvider = this.prevProvider; + this.prevProvider = null; + } else { + this.authService.logout(); + } + } + + private updatedTime() { + if (this.countDownTime > 0) { + this.countDownTime--; + if (this.countDownTime === 0) { + this.hideResendButton = false; + } + } + } +} diff --git a/ui-ngx/src/app/shared/animations/speed-dial-fab.animations.ts b/ui-ngx/src/app/shared/animations/speed-dial-fab.animations.ts index 61b7aaa922..c991c61521 100644 --- a/ui-ngx/src/app/shared/animations/speed-dial-fab.animations.ts +++ b/ui-ngx/src/app/shared/animations/speed-dial-fab.animations.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/shared/components/breadcrumb.component.html b/ui-ngx/src/app/shared/components/breadcrumb.component.html index 2c9b2e246d..c549751904 100644 --- a/ui-ngx/src/app/shared/components/breadcrumb.component.html +++ b/ui-ngx/src/app/shared/components/breadcrumb.component.html @@ -1,6 +1,6 @@
- +
@@ -33,8 +33,14 @@
- - +
+ cloud_upload + {{ dropLabel }} + + +
diff --git a/ui-ngx/src/app/shared/components/file-input.component.scss b/ui-ngx/src/app/shared/components/file-input.component.scss index 480902f067..1156f46470 100644 --- a/ui-ngx/src/app/shared/components/file-input.component.scss +++ b/ui-ngx/src/app/shared/components/file-input.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,19 +61,38 @@ $previewSize: 100px !default; position: relative; height: $previewSize; overflow: hidden; - border: dashed 2px; + border: 2px dashed rgba(0, 0, 0, 0.2); + border-radius: 4px; + box-sizing: border-box; - label { - display: flex; - flex-direction: column; - justify-content: center; + .upload-label { width: 100%; height: 100%; + padding: 0 16px; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; font-size: 16px; + color: rgba(0, 0, 0, 0.54); text-align: center; + .mat-icon { + margin-right: 17px; + } + } + } +} - @media #{$mat-gt-sm} { - font-size: 24px; +:host ::ng-deep { + button.browse-file { + padding: 0; + font-size: 16px; + span.mat-button-wrapper { + display: block; + label { + display: block; + cursor: pointer; + padding: 0 16px; } } } diff --git a/ui-ngx/src/app/shared/components/file-input.component.ts b/ui-ngx/src/app/shared/components/file-input.component.ts index 261ce1c166..ad2fd9f65e 100644 --- a/ui-ngx/src/app/shared/components/file-input.component.ts +++ b/ui-ngx/src/app/shared/components/file-input.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/shared/components/footer-fab-buttons.component.html b/ui-ngx/src/app/shared/components/footer-fab-buttons.component.html index 7e42c76cf5..1eae602456 100644 --- a/ui-ngx/src/app/shared/components/footer-fab-buttons.component.html +++ b/ui-ngx/src/app/shared/components/footer-fab-buttons.component.html @@ -1,6 +1,6 @@ +
+
+ + + +
+
+ +
+
+
+
+
+
+
diff --git a/ui-ngx/src/app/shared/components/html.component.scss b/ui-ngx/src/app/shared/components/html.component.scss new file mode 100644 index 0000000000..50ebbcf867 --- /dev/null +++ b/ui-ngx/src/app/shared/components/html.component.scss @@ -0,0 +1,65 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +.tb-html { + position: relative; + + &.tb-disabled { + color: rgba(0, 0, 0, .38); + } + + &.fill-height { + height: 100%; + } + + .tb-html-content-panel { + height: calc(100% - 40px); + border: 1px solid #c0c0c0; + + #tb-html-input { + width: 100%; + min-width: 200px; + height: 100%; + } + } + + &:not(.tb-fullscreen) { + padding-bottom: 15px; + } + + .tb-html-toolbar { + & > * { + &:not(:last-child) { + margin-right: 4px; + } + } + button.mat-button, button.mat-icon-button, button.mat-icon-button.tb-mat-32 { + background: rgba(220, 220, 220, .35); + align-items: center; + vertical-align: middle; + min-width: 32px; + min-height: 15px; + padding: 4px; + font-size: .8rem; + line-height: 15px; + &:not(.tb-help-popup-button) { + color: #7b7b7b; + } + } + .tb-help-popup-button-loading { + background: #f3f3f3; + } + } +} diff --git a/ui-ngx/src/app/shared/components/html.component.ts b/ui-ngx/src/app/shared/components/html.component.ts new file mode 100644 index 0000000000..7378cca7ea --- /dev/null +++ b/ui-ngx/src/app/shared/components/html.component.ts @@ -0,0 +1,213 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { + ChangeDetectorRef, + Component, + ElementRef, + forwardRef, + Input, + OnDestroy, + OnInit, + ViewChild, + ViewEncapsulation +} from '@angular/core'; +import { ControlValueAccessor, FormControl, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator } from '@angular/forms'; +import { Ace } from 'ace-builds'; +import { getAce } from '@shared/models/ace/ace.models'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { UtilsService } from '@core/services/utils.service'; +import { TranslateService } from '@ngx-translate/core'; +import { CancelAnimationFrame, RafService } from '@core/services/raf.service'; +import { ResizeObserver } from '@juggle/resize-observer'; +import { beautifyHtml } from '@shared/models/beautify.models'; + +@Component({ + selector: 'tb-html', + templateUrl: './html.component.html', + styleUrls: ['./html.component.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => HtmlComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => HtmlComponent), + multi: true, + } + ], + encapsulation: ViewEncapsulation.None +}) +export class HtmlComponent implements OnInit, OnDestroy, ControlValueAccessor, Validator { + + @ViewChild('htmlEditor', {static: true}) + htmlEditorElmRef: ElementRef; + + private htmlEditor: Ace.Editor; + private editorsResizeCaf: CancelAnimationFrame; + private editorResize$: ResizeObserver; + private ignoreChange = false; + + @Input() label: string; + + @Input() disabled: boolean; + + @Input() fillHeight: boolean; + + @Input() minHeight = '200px'; + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + fullscreen = false; + + modelValue: string; + + hasErrors = false; + + private propagateChange = null; + + constructor(public elementRef: ElementRef, + private utils: UtilsService, + private translate: TranslateService, + protected store: Store, + private raf: RafService, + private cd: ChangeDetectorRef) { + } + + ngOnInit(): void { + const editorElement = this.htmlEditorElmRef.nativeElement; + let editorOptions: Partial = { + mode: 'ace/mode/html', + showGutter: true, + showPrintMargin: true, + readOnly: this.disabled + }; + + const advancedOptions = { + enableSnippets: true, + enableBasicAutocompletion: true, + enableLiveAutocompletion: true + }; + + editorOptions = {...editorOptions, ...advancedOptions}; + getAce().subscribe( + (ace) => { + this.htmlEditor = ace.edit(editorElement, editorOptions); + this.htmlEditor.session.setUseWrapMode(true); + this.htmlEditor.setValue(this.modelValue ? this.modelValue : '', -1); + this.htmlEditor.setReadOnly(this.disabled); + this.htmlEditor.on('change', () => { + if (!this.ignoreChange) { + this.updateView(); + } + }); + // @ts-ignore + this.htmlEditor.session.on('changeAnnotation', () => { + const annotations = this.htmlEditor.session.getAnnotations(); + const hasErrors = annotations.filter(annotation => annotation.type === 'error').length > 0; + if (this.hasErrors !== hasErrors) { + this.hasErrors = hasErrors; + this.propagateChange(this.modelValue); + this.cd.markForCheck(); + } + }); + this.editorResize$ = new ResizeObserver(() => { + this.onAceEditorResize(); + }); + this.editorResize$.observe(editorElement); + } + ); + } + + ngOnDestroy(): void { + if (this.editorResize$) { + this.editorResize$.disconnect(); + } + } + + private onAceEditorResize() { + if (this.editorsResizeCaf) { + this.editorsResizeCaf(); + this.editorsResizeCaf = null; + } + this.editorsResizeCaf = this.raf.raf(() => { + this.htmlEditor.resize(); + this.htmlEditor.renderer.updateFull(); + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.htmlEditor) { + this.htmlEditor.setReadOnly(this.disabled); + } + } + + public validate(c: FormControl) { + return (!this.hasErrors) ? null : { + html: { + valid: false, + }, + }; + } + + beautifyHtml() { + beautifyHtml(this.modelValue, {indent_size: 4}).subscribe( + (res) => { + if (this.modelValue !== res) { + this.htmlEditor.setValue(res ? res : '', -1); + this.updateView(); + } + } + ); + } + + writeValue(value: string): void { + this.modelValue = value; + if (this.htmlEditor) { + this.ignoreChange = true; + this.htmlEditor.setValue(this.modelValue ? this.modelValue : '', -1); + this.ignoreChange = false; + } + } + + updateView() { + const editorValue = this.htmlEditor.getValue(); + if (this.modelValue !== editorValue) { + this.modelValue = editorValue; + this.propagateChange(this.modelValue); + this.cd.markForCheck(); + } + } +} diff --git a/ui-ngx/src/app/shared/components/image-input.component.html b/ui-ngx/src/app/shared/components/image-input.component.html index 2fe8cc4102..d9059eb3c2 100644 --- a/ui-ngx/src/app/shared/components/image-input.component.html +++ b/ui-ngx/src/app/shared/components/image-input.component.html @@ -1,6 +1,6 @@
- +
-
-
{{ (disabled ? 'dashboard.empty-image' : 'dashboard.no-image') | translate }}
- +
+
+
+
{{ (disabled ? 'dashboard.empty-image' : 'dashboard.no-image') | translate }}
+ +
+
+ +
+
-
+
+
+ cloud_upload + image-input.drop-image-or + + +
+
+
-
- - -
dashboard.maximum-upload-file-size
diff --git a/ui-ngx/src/app/shared/components/image-input.component.scss b/ui-ngx/src/app/shared/components/image-input.component.scss index 4f6608232c..7caa4c620c 100644 --- a/ui-ngx/src/app/shared/components/image-input.component.scss +++ b/ui-ngx/src/app/shared/components/image-input.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,7 +15,9 @@ */ @import "../../../scss/constants"; -$previewSize: 100px !default; +$containerHeight: 120px !default; +$previewContainerWidth: 168px !default; +$previewSize: 96px !default; :host { @@ -30,14 +32,35 @@ $previewSize: 100px !default; .tb-image-select-container { position: relative; width: 100%; + height: $containerHeight; + } + + .image-container { + position: relative; + float: left; + height: $containerHeight; + padding: 12px; + margin-right: 8px; + background: rgba(0, 0, 0, 0.03); + border-radius: 4px; + } + + .image-content-container { + background: #FFFFFF; + border: 1px solid rgba(0, 0, 0, 0.2); + border-radius: 4px; + padding-left: 8px; height: $previewSize; + &.no-padding { + padding-left: 0px; + } } .tb-image-preview { width: auto; - max-width: $previewSize - 2; + max-width: $previewSize - 2px; height: auto; - max-height: $previewSize - 2; + max-height: $previewSize - 2px; } .tb-image-preview-container { @@ -45,9 +68,9 @@ $previewSize: 100px !default; float: left; width: $previewSize; height: $previewSize; - margin-right: 12px; - vertical-align: top; - border: solid 1px; + margin-top: -1px; + margin-bottom: -1px; + border: 1px solid rgba(0, 0, 0, 0.54); div { width: 100%; @@ -67,14 +90,12 @@ $previewSize: 100px !default; .tb-image-clear-container { position: relative; float: right; - width: 48px; height: $previewSize; - } - - .tb-image-clear-btn { - position: absolute !important; - top: 50%; - transform: translate(0%, -50%) !important; + display: flex; + align-items: center; + &.full-height { + height: $containerHeight; + } } .file-input { @@ -83,21 +104,29 @@ $previewSize: 100px !default; .tb-flow-drop { position: relative; - height: $previewSize; + height: $containerHeight; overflow: hidden; - border: dashed 2px; + border: 2px dashed rgba(0, 0, 0, 0.2); + border-radius: 4px; + box-sizing: border-box; - label { - display: flex; - flex-direction: column; - justify-content: center; + &.float-left { + float: left; + } + + .upload-label { width: 100%; height: 100%; + padding: 0 16px; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; font-size: 16px; + color: rgba(0, 0, 0, 0.54); text-align: center; - - @media #{$mat-gt-sm} { - font-size: 24px; + .mat-icon { + margin-right: 17px; } } } @@ -106,3 +135,18 @@ $previewSize: 100px !default; margin-top: 8px; } } + +:host ::ng-deep { + button.browse-file { + padding: 0; + font-size: 16px; + span.mat-button-wrapper { + display: block; + label { + display: block; + cursor: pointer; + padding: 0 16px; + } + } + } +} diff --git a/ui-ngx/src/app/shared/components/image-input.component.ts b/ui-ngx/src/app/shared/components/image-input.component.ts index 3064163b89..6e36f545df 100644 --- a/ui-ngx/src/app/shared/components/image-input.component.ts +++ b/ui-ngx/src/app/shared/components/image-input.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ /// limitations under the License. /// -import { AfterViewInit, Component, forwardRef, Input, OnDestroy, ViewChild } from '@angular/core'; +import { AfterViewInit, ChangeDetectorRef, Component, forwardRef, Input, OnDestroy, ViewChild } from '@angular/core'; import { PageComponent } from '@shared/components/page.component'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; @@ -89,7 +89,8 @@ export class ImageInputComponent extends PageComponent implements AfterViewInit, private sanitizer: DomSanitizer, private dialog: DialogService, private translate: TranslateService, - private fileSize: FileSizePipe) { + private fileSize: FileSizePipe, + private cd: ChangeDetectorRef) { super(store); } @@ -144,6 +145,7 @@ export class ImageInputComponent extends PageComponent implements AfterViewInit, } private updateModel() { + this.cd.markForCheck(); this.propagateChange(this.imageUrl); } diff --git a/ui-ngx/src/app/shared/components/js-func.component.html b/ui-ngx/src/app/shared/components/js-func.component.html index ac662cba3e..dc79290181 100644 --- a/ui-ngx/src/app/shared/components/js-func.component.html +++ b/ui-ngx/src/app/shared/components/js-func.component.html @@ -1,6 +1,6 @@ -
- + +
-
+
-
- +
+
diff --git a/ui-ngx/src/app/shared/components/js-func.component.scss b/ui-ngx/src/app/shared/components/js-func.component.scss index 21f5b7d177..0df86ce5fa 100644 --- a/ui-ngx/src/app/shared/components/js-func.component.scss +++ b/ui-ngx/src/app/shared/components/js-func.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,19 +24,32 @@ height: 100%; } + &:not(.tb-js-func-title) { + .tb-js-func-panel { + margin-left: 15px; + } + } + + &.tb-js-func-title { + .tb-js-func-panel { + height: calc(100% - 40px); + } + } + .tb-js-func-panel { height: calc(100% - 80px); - margin-left: 15px; border: 1px solid #c0c0c0; #tb-javascript-input { width: 100%; min-width: 200px; height: 100%; + } + } - &:not(.fill-height) { - min-height: 200px; - } + &:not(.tb-fullscreen) { + &.tb-js-func-title { + padding-bottom: 15px; } } diff --git a/ui-ngx/src/app/shared/components/js-func.component.ts b/ui-ngx/src/app/shared/components/js-func.component.ts index 1d7b9b16aa..740273ed87 100644 --- a/ui-ngx/src/app/shared/components/js-func.component.ts +++ b/ui-ngx/src/app/shared/components/js-func.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -15,6 +15,7 @@ /// import { + ChangeDetectorRef, Component, ElementRef, forwardRef, @@ -69,6 +70,8 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, toastTargetId = `jsFuncEditor-${guid()}`; + @Input() functionTitle: string; + @Input() functionName: string; @Input() functionArgs: Array; @@ -81,6 +84,8 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, @Input() fillHeight: boolean; + @Input() minHeight = '200px'; + @Input() editorCompleter: TbEditorCompleter; @Input() globalVariables: Array; @@ -123,13 +128,14 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, errorAnnotationId = -1; private propagateChange = null; - private hasErrors = false; + public hasErrors = false; constructor(public elementRef: ElementRef, private utils: UtilsService, private translate: TranslateService, protected store: Store, - private raf: RafService) { + private raf: RafService, + private cd: ChangeDetectorRef) { } ngOnInit(): void { @@ -183,6 +189,7 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, if (this.hasErrors !== hasErrors) { this.hasErrors = hasErrors; this.propagateChange(this.modelValue); + this.cd.markForCheck(); } }); } @@ -271,6 +278,7 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, this.functionValid = this.validateJsFunc(); if (!this.functionValid) { this.propagateChange(this.modelValue); + this.cd.markForCheck(); this.store.dispatch(new ActionNotificationShow( { message: this.validationError, @@ -398,6 +406,7 @@ export class JsFuncComponent implements OnInit, OnDestroy, ControlValueAccessor, this.modelValue = editorValue; this.functionValid = true; this.propagateChange(this.modelValue); + this.cd.markForCheck(); } } } diff --git a/ui-ngx/src/app/shared/components/json-content.component.html b/ui-ngx/src/app/shared/components/json-content.component.html index b815ec6315..1654785510 100644 --- a/ui-ngx/src/app/shared/components/json-content.component.html +++ b/ui-ngx/src/app/shared/components/json-content.component.html @@ -1,6 +1,6 @@ -
- + + + +
+
+
+ +
+
+
+ +
+
diff --git a/ui-ngx/src/app/shared/components/markdown-editor.component.scss b/ui-ngx/src/app/shared/components/markdown-editor.component.scss new file mode 100644 index 0000000000..a4149c54d7 --- /dev/null +++ b/ui-ngx/src/app/shared/components/markdown-editor.component.scss @@ -0,0 +1,77 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +.markdown-content { + min-width: 400px; + &.tb-edit-mode { + .tb-markdown-view-container { + border: 1px solid #c0c0c0; + } + .tb-markdown-view { + padding: 20px; + } + &:not(.tb-fullscreen) { + padding-bottom: 15px; + .markdown-content-editor { + min-height: 200px; + max-height: 200px; + height: 200px; + } + .tb-markdown-view-container { + min-height: 200px; + max-height: 200px; + height: 200px; + } + } + } + &.tb-fullscreen { + background: #fff; + .markdown-content-editor { + height: calc(100% - 40px); + } + } + .markdown-content-editor { + position: relative; + height: 100%; + } + .tb-markdown-editor { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + border: 1px solid #c0c0c0; + } + .tb-markdown-view-container { + overflow: auto; + height: 100%; + } + .buttons-panel { + position: absolute; + top: 5px; + right: 24px; + z-index: 1; + button.edit-toggle { + min-width: 32px; + min-height: 15px; + padding: 4px; + margin: 0; + font-size: .8rem; + line-height: 15px; + color: #7b7b7b; + background: rgba(220, 220, 220, .35); + } + } +} diff --git a/ui-ngx/src/app/shared/components/markdown-editor.component.ts b/ui-ngx/src/app/shared/components/markdown-editor.component.ts new file mode 100644 index 0000000000..7c1c9c7c02 --- /dev/null +++ b/ui-ngx/src/app/shared/components/markdown-editor.component.ts @@ -0,0 +1,154 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'; +import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { Ace } from 'ace-builds'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { getAce } from '@shared/models/ace/ace.models'; + +@Component({ + selector: 'tb-markdown-editor', + templateUrl: './markdown-editor.component.html', + styleUrls: ['./markdown-editor.component.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MarkdownEditorComponent), + multi: true + } + ] +}) +export class MarkdownEditorComponent implements OnInit, ControlValueAccessor { + + @Input() label: string; + + @Input() disabled: boolean; + + @Input() readonly: boolean; + + @ViewChild('markdownEditor', {static: true}) + markdownEditorElmRef: ElementRef; + + private markdownEditor: Ace.Editor; + + editorMode = true; + + fullscreen = false; + + markdownValue: string; + renderValue: string; + + ignoreChange = false; + + private propagateChange = null; + + private requiredValue: boolean; + + get required(): boolean { + return this.requiredValue; + } + + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + constructor() { + } + + ngOnInit(): void { + if (!this.readonly) { + const editorElement = this.markdownEditorElmRef.nativeElement; + let editorOptions: Partial = { + mode: 'ace/mode/markdown', + showGutter: true, + showPrintMargin: false, + readOnly: false + }; + + const advancedOptions = { + enableSnippets: true, + enableBasicAutocompletion: true, + enableLiveAutocompletion: true + }; + + editorOptions = {...editorOptions, ...advancedOptions}; + + getAce().subscribe( + (ace) => { + this.markdownEditor = ace.edit(editorElement, editorOptions); + this.markdownEditor.session.setUseWrapMode(false); + this.markdownEditor.setValue(this.markdownValue ? this.markdownValue : '', -1); + this.markdownEditor.on('change', () => { + if (!this.ignoreChange) { + this.updateView(); + } + }); + } + ); + + } + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + } + + writeValue(value: string): void { + this.editorMode = true; + this.markdownValue = value; + this.renderValue = this.markdownValue ? this.markdownValue : ' '; + if (this.markdownEditor) { + this.ignoreChange = true; + this.markdownEditor.setValue(this.markdownValue ? this.markdownValue : '', -1); + this.ignoreChange = false; + } + } + + updateView() { + const editorValue = this.markdownEditor.getValue(); + if (this.markdownValue !== editorValue) { + this.markdownValue = editorValue; + this.renderValue = this.markdownValue ? this.markdownValue : ' '; + this.propagateChange(this.markdownValue); + } + } + + onFullscreen() { + if (this.markdownEditor) { + setTimeout(() => { + this.markdownEditor.resize(); + }, 0); + } + } + + toggleEditMode() { + this.editorMode = !this.editorMode; + if (this.editorMode && this.markdownEditor) { + setTimeout(() => { + this.markdownEditor.resize(); + }, 0); + } + } +} diff --git a/ui-ngx/src/app/shared/components/markdown.component.html b/ui-ngx/src/app/shared/components/markdown.component.html index b854aa3364..1b1eb7b8f9 100644 --- a/ui-ngx/src/app/shared/components/markdown.component.html +++ b/ui-ngx/src/app/shared/components/markdown.component.html @@ -1,6 +1,6 @@
- {{materialIconFormGroup.get('icon').value}} + {{materialIconFormGroup.get('icon').value}} - icon.icon - + {{ label }} + +
diff --git a/ui-ngx/src/app/shared/components/material-icon-select.component.scss b/ui-ngx/src/app/shared/components/material-icon-select.component.scss index 6fedd967d9..2227bdab95 100644 --- a/ui-ngx/src/app/shared/components/material-icon-select.component.scss +++ b/ui-ngx/src/app/shared/components/material-icon-select.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ :host { - .mat-icon { + .mat-icon.icon-value { padding: 4px; margin: 8px 4px 4px; cursor: pointer; diff --git a/ui-ngx/src/app/shared/components/material-icon-select.component.ts b/ui-ngx/src/app/shared/components/material-icon-select.component.ts index 12f7e3f11f..9fd245b7e7 100644 --- a/ui-ngx/src/app/shared/components/material-icon-select.component.ts +++ b/ui-ngx/src/app/shared/components/material-icon-select.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; import { DialogService } from '@core/services/dialog.service'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'tb-material-icon-select', @@ -35,9 +37,33 @@ import { DialogService } from '@core/services/dialog.service'; }) export class MaterialIconSelectComponent extends PageComponent implements OnInit, ControlValueAccessor { + @Input() + label = this.translate.instant('icon.icon'); + @Input() disabled: boolean; + private iconClearButtonValue: boolean; + get iconClearButton(): boolean { + return this.iconClearButtonValue; + } + @Input() + set iconClearButton(value: boolean) { + const newVal = coerceBooleanProperty(value); + if (this.iconClearButtonValue !== newVal) { + this.iconClearButtonValue = newVal; + } + } + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + private modelValue: string; private propagateChange = null; @@ -46,6 +72,7 @@ export class MaterialIconSelectComponent extends PageComponent implements OnInit constructor(protected store: Store, private dialogs: DialogService, + private translate: TranslateService, private fb: FormBuilder) { super(store); } @@ -104,4 +131,8 @@ export class MaterialIconSelectComponent extends PageComponent implements OnInit ); } } + + clear() { + this.materialIconFormGroup.get('icon').patchValue(null, {emitEvent: true}); + } } diff --git a/ui-ngx/src/app/shared/components/message-type-autocomplete.component.html b/ui-ngx/src/app/shared/components/message-type-autocomplete.component.html index 5aa3b79da7..e09cfb81ee 100644 --- a/ui-ngx/src/app/shared/components/message-type-autocomplete.component.html +++ b/ui-ngx/src/app/shared/components/message-type-autocomplete.component.html @@ -1,6 +1,6 @@ +
+ + +
+
+
+
+ {{ 'image-input.images' | translate }} [{{ $index }}] +
+
+ drag_indicator +
+
+ +
+
+ +
+
+
+
{{ 'image-input.no-images' | translate }}
+
+
+
+ cloud_upload + image-input.drop-images-or + + +
+
+
+
+
dashboard.maximum-upload-file-size
+
diff --git a/ui-ngx/src/app/shared/components/multiple-image-input.component.scss b/ui-ngx/src/app/shared/components/multiple-image-input.component.scss new file mode 100644 index 0000000000..a1594a69a4 --- /dev/null +++ b/ui-ngx/src/app/shared/components/multiple-image-input.component.scss @@ -0,0 +1,169 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@import "../../../scss/constants"; + +$imagesContainerHeight: 106px !default; +$containerHeight: 120px !default; +$previewSize: 64px !default; + +.image-card { + margin-bottom: 8px; + &.image-dnd-placeholder { + height: 82px; + width: 146px; + border: 2px dashed rgba(0, 0, 0, 0.2); + background: rgba(0, 0, 0, 0.1); + border-radius: 4px; + } + &.image-dragging { + display: none !important; + } +} + + +.image-title { + font-size: 11px; + font-weight: 400; + line-height: 14px; + color: rgba(0, 0, 0, 0.6); + padding-bottom: 4px; +} + +.image-content-container { + background: #FFFFFF; + border: 1px solid rgba(0, 0, 0, 0.2); + border-radius: 4px; + height: $previewSize; +} + +.tb-image-preview { + width: auto; + max-width: $previewSize - 2px; + height: auto; + max-height: $previewSize - 2px; +} + +.tb-image-preview-container { + position: relative; + width: $previewSize; + height: $previewSize; + margin-top: -1px; + margin-bottom: -1px; + border: 1px solid rgba(0, 0, 0, 0.54); + + .tb-image-preview { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + } +} + +.tb-image-action-container { + position: relative; + height: $previewSize - 2px; + display: flex; + align-items: center; + justify-content: center; + min-width: 40px; +} + +:host { + + .tb-container { + margin-top: 0; + label.tb-title { + display: block; + padding-bottom: 8px; + } + } + + .tb-image-select-container { + position: relative; + width: 100%; + } + + .images-container { + padding: 12px 12px 4px; + background: rgba(0, 0, 0, 0.03); + border-radius: 4px; + flex-wrap: wrap; + margin-bottom: 8px; + &.no-images { + height: $imagesContainerHeight; + padding-bottom: 12px; + align-items: center; + justify-content: center; + } + } + + .no-images-prompt { + font-size: 18px; + color: rgba(0, 0, 0, 0.54); + } + + .file-input { + display: none; + } + + .tb-flow-drop { + position: relative; + height: $containerHeight; + overflow: hidden; + border: 2px dashed rgba(0, 0, 0, 0.2); + border-radius: 4px; + box-sizing: border-box; + + &.float-left { + float: left; + } + + .upload-label { + width: 100%; + height: 100%; + padding: 0 16px; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + font-size: 16px; + color: rgba(0, 0, 0, 0.54); + text-align: center; + .mat-icon { + margin-right: 17px; + } + } + } + + .tb-hint{ + margin-top: 8px; + } +} + +:host ::ng-deep { + button.browse-file { + padding: 0; + font-size: 16px; + span.mat-button-wrapper { + display: block; + label { + display: block; + cursor: pointer; + padding: 0 16px; + } + } + } +} diff --git a/ui-ngx/src/app/shared/components/multiple-image-input.component.ts b/ui-ngx/src/app/shared/components/multiple-image-input.component.ts new file mode 100644 index 0000000000..ae372a86fd --- /dev/null +++ b/ui-ngx/src/app/shared/components/multiple-image-input.component.ts @@ -0,0 +1,210 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { AfterViewInit, ChangeDetectorRef, Component, forwardRef, Input, OnDestroy, ViewChild } from '@angular/core'; +import { PageComponent } from '@shared/components/page.component'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { ControlValueAccessor, FormArray, NG_VALUE_ACCESSOR, } from '@angular/forms'; +import { Subscription } from 'rxjs'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { DropDirective, FlowDirective } from '@flowjs/ngx-flow'; +import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; +import { UtilsService } from '@core/services/utils.service'; +import { DialogService } from '@core/services/dialog.service'; +import { TranslateService } from '@ngx-translate/core'; +import { FileSizePipe } from '@shared/pipe/file-size.pipe'; +import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; +import { DndDropEvent } from 'ngx-drag-drop'; +import { isUndefined } from '@core/utils'; + +@Component({ + selector: 'tb-multiple-image-input', + templateUrl: './multiple-image-input.component.html', + styleUrls: ['./multiple-image-input.component.scss'], + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MultipleImageInputComponent), + multi: true + } + ] +}) +export class MultipleImageInputComponent extends PageComponent implements AfterViewInit, OnDestroy, ControlValueAccessor { + + @Input() + label: string; + + @Input() + maxSizeByte: number; + + private requiredValue: boolean; + + get required(): boolean { + return this.requiredValue; + } + + @Input() + set required(value: boolean) { + const newVal = coerceBooleanProperty(value); + if (this.requiredValue !== newVal) { + this.requiredValue = newVal; + } + } + + @Input() + disabled: boolean; + + @Input() + inputId = this.utils.guid(); + + imageUrls: string[]; + safeImageUrls: SafeUrl[]; + + dragIndex: number; + + @ViewChild('flow', {static: true}) + flow: FlowDirective; + + @ViewChild('flowDrop', {static: true}) + flowDrop: DropDirective; + + autoUploadSubscription: Subscription; + + private propagateChange = null; + + private viewInited = false; + + constructor(protected store: Store, + private utils: UtilsService, + private sanitizer: DomSanitizer, + private dialog: DialogService, + private translate: TranslateService, + private fileSize: FileSizePipe, + private cd: ChangeDetectorRef) { + super(store); + } + + ngAfterViewInit() { + this.autoUploadSubscription = this.flow.events$.subscribe(event => { + if (event.type === 'filesAdded') { + const readers = []; + (event.event[0] as flowjs.FlowFile[]).forEach(file => { + readers.push(this.readImageUrl(file)); + }); + if (readers.length) { + Promise.all(readers).then((files) => { + files = files.filter(file => file.imageUrl != null || file.safeImageUrl != null); + this.imageUrls = this.imageUrls.concat(files.map(content => content.imageUrl)); + this.safeImageUrls = this.safeImageUrls.concat(files.map(content => content.safeImageUrl)); + this.updateModel(); + }); + } + } + }); + if (this.disabled) { + this.flowDrop.disable(); + } else { + this.flowDrop.enable(); + } + this.viewInited = true; + } + + private readImageUrl(file: flowjs.FlowFile): Promise { + return new Promise((resolve) => { + if (this.maxSizeByte && this.maxSizeByte < file.size) { + resolve({imageUrl: null, safeImageUrl: null}); + } + const reader = new FileReader(); + reader.onload = () => { + let imageUrl = null; + let safeImageUrl = null; + if (typeof reader.result === 'string' && reader.result.startsWith('data:image/')) { + imageUrl = reader.result; + if (imageUrl && imageUrl.length > 0) { + safeImageUrl = this.sanitizer.bypassSecurityTrustUrl(imageUrl); + } + } + resolve({imageUrl, safeImageUrl}); + }; + reader.onerror = () => { + resolve({imageUrl: null, safeImageUrl: null}); + }; + reader.readAsDataURL(file.file); + }); + } + + ngOnDestroy() { + this.autoUploadSubscription.unsubscribe(); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.viewInited) { + if (this.disabled) { + this.flowDrop.disable(); + } else { + this.flowDrop.enable(); + } + } + } + + writeValue(value: string[]): void { + this.imageUrls = value || []; + this.safeImageUrls = this.imageUrls.map(imageUrl => this.sanitizer.bypassSecurityTrustUrl(imageUrl)); + } + + private updateModel() { + this.cd.markForCheck(); + this.propagateChange(this.imageUrls); + } + + clearImage(index: number) { + this.imageUrls.splice(index, 1); + this.safeImageUrls.splice(index, 1); + this.updateModel(); + } + + imageDragStart(index: number) { + setTimeout(() => { + this.dragIndex = index; + this.cd.markForCheck(); + }); + } + + imageDragEnd() { + this.dragIndex = -1; + this.cd.markForCheck(); + } + + imageDrop(event: DndDropEvent) { + let index = event.index; + if (isUndefined(index)) { + index = this.safeImageUrls.length; + } + moveItemInArray(this.imageUrls, this.dragIndex, index); + moveItemInArray(this.safeImageUrls, this.dragIndex, index); + this.dragIndex = -1; + this.updateModel(); + } +} diff --git a/ui-ngx/src/app/shared/components/nav-tree.component.html b/ui-ngx/src/app/shared/components/nav-tree.component.html index 4635707c53..f3a0f90114 100644 --- a/ui-ngx/src/app/shared/components/nav-tree.component.html +++ b/ui-ngx/src/app/shared/components/nav-tree.component.html @@ -1,6 +1,6 @@ + +
+
+
+ {{ flagIcon }} + + + {{country.flag}} + {{' ' + country.name + ' +' + country.dialCode }} + + +
+ + {{ label | translate }} + + + + {{ 'phone-input.phone-input-required' | translate }} + + + {{ 'phone-input.phone-input-validation' | translate }} + + +
+
diff --git a/ui-ngx/src/app/shared/components/phone-input.component.scss b/ui-ngx/src/app/shared/components/phone-input.component.scss new file mode 100644 index 0000000000..acca75f560 --- /dev/null +++ b/ui-ngx/src/app/shared/components/phone-input.component.scss @@ -0,0 +1,55 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +:host ::ng-deep { + + .phone-input-container { + display: flex; + align-items: center; + + .phone-input { + width: 100%; + } + } + + .flags-select-container { + display: inline-block; + position: relative; + width: 50px; + height: 100%; + margin-right: 5px; + } + + .flag-container { + position: absolute; + font-size: 20px; + top: 50%; + left: 0; + transform: translate(0, -50%); + } + .country-select { + width: 45px; + height: 30px; + + .mat-select-trigger { + height: 100%; + width: 100%; + } + + .mat-select-value { + visibility: hidden; + } + } +} diff --git a/ui-ngx/src/app/shared/components/phone-input.component.ts b/ui-ngx/src/app/shared/components/phone-input.component.ts new file mode 100644 index 0000000000..47bdf8741c --- /dev/null +++ b/ui-ngx/src/app/shared/components/phone-input.component.ts @@ -0,0 +1,222 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, forwardRef, Input, OnInit } from '@angular/core'; +import { + ControlValueAccessor, + FormBuilder, + FormControl, + FormGroup, + NG_VALIDATORS, + NG_VALUE_ACCESSOR, + ValidationErrors, + Validator, + ValidatorFn, + Validators +} from '@angular/forms'; +import { TranslateService } from '@ngx-translate/core'; +import { Country, CountryData } from '@shared/models/country.models'; +import examples from 'libphonenumber-js/examples.mobile.json'; +import { CountryCode, getExampleNumber, parsePhoneNumberFromString } from 'libphonenumber-js'; +import { phoneNumberPattern } from '@shared/models/settings.models'; +import { Subscription } from 'rxjs'; +import { FloatLabelType, MatFormFieldAppearance } from '@angular/material/form-field/form-field'; + +@Component({ + selector: 'tb-phone-input', + templateUrl: './phone-input.component.html', + styleUrls: ['./phone-input.component.scss'], + providers: [ + CountryData, + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => PhoneInputComponent), + multi: true + }, + { + provide: NG_VALIDATORS, + useExisting: forwardRef(() => PhoneInputComponent), + multi: true + } + ] +}) +export class PhoneInputComponent implements OnInit, ControlValueAccessor, Validator { + + @Input() + disabled: boolean; + + @Input() + defaultCountry: CountryCode = 'US'; + + @Input() + enableFlagsSelect = true; + + @Input() + required = true; + + @Input() + floatLabel: FloatLabelType = 'auto'; + + @Input() + appearance: MatFormFieldAppearance = 'legacy'; + + @Input() + placeholder; + + @Input() + label = 'phone-input.phone-input-label'; + + allCountries: Array = this.countryCodeData.allCountries; + phonePlaceholder: string; + flagIcon: string; + phoneFormGroup: FormGroup; + phoneNumberPattern = phoneNumberPattern; + + private baseCode = 127397; + private countryCallingCode: string; + private modelValue: string; + private valueChange$: Subscription = null; + private propagateChange = (v: any) => { }; + + constructor(private translate: TranslateService, + private fb: FormBuilder, + private countryCodeData: CountryData) { + } + + ngOnInit(): void { + const validators: ValidatorFn[] = [Validators.pattern(phoneNumberPattern), this.validatePhoneNumber()]; + if (this.required) { + validators.push(Validators.required); + } + this.phoneFormGroup = this.fb.group({ + country: [this.defaultCountry, []], + phoneNumber: [null, validators] + }); + + this.valueChange$ = this.phoneFormGroup.get('phoneNumber').valueChanges.subscribe(value => { + this.updateModel(); + if (value) { + const parsedPhoneNumber = parsePhoneNumberFromString(value); + const country = this.phoneFormGroup.get('country').value; + if (parsedPhoneNumber?.country && parsedPhoneNumber?.country !== country) { + this.phoneFormGroup.get('country').patchValue(parsedPhoneNumber.country, {emitEvent: true}); + } + } + }); + + this.phoneFormGroup.get('country').valueChanges.subscribe(value => { + if (value) { + const code = this.countryCallingCode; + this.getFlagAndPhoneNumberData(value); + let phoneNumber = this.phoneFormGroup.get('phoneNumber').value; + if (phoneNumber) { + if (code !== this.countryCallingCode && phoneNumber.includes(code)) { + phoneNumber = phoneNumber.replace(code, this.countryCallingCode); + this.phoneFormGroup.get('phoneNumber').patchValue(phoneNumber); + } + } + } + }); + } + + ngOnDestroy() { + if (this.valueChange$) { + this.valueChange$.unsubscribe(); + } + } + + focus() { + const phoneNumber = this.phoneFormGroup.get('phoneNumber'); + this.phoneFormGroup.markAsPristine(); + this.phoneFormGroup.markAsUntouched(); + if (!phoneNumber.value) { + phoneNumber.patchValue(this.countryCallingCode); + } + } + + private getFlagAndPhoneNumberData(country) { + if (this.enableFlagsSelect) { + this.flagIcon = this.getFlagIcon(country); + } + this.getPhoneNumberData(country); + } + + private getPhoneNumberData(country): void { + const phoneData = getExampleNumber(country, examples); + this.phonePlaceholder = phoneData.number; + this.countryCallingCode = '+' + phoneData.countryCallingCode; + } + + private getFlagIcon(countryCode) { + return String.fromCodePoint(...countryCode.split('').map(country => this.baseCode + country.charCodeAt(0))); + } + + validatePhoneNumber(): ValidatorFn { + return (c: FormControl) => { + const phoneNumber = c.value; + if (phoneNumber) { + const parsedPhoneNumber = parsePhoneNumberFromString(phoneNumber); + if (!parsedPhoneNumber?.isValid() || !parsedPhoneNumber?.isPossible()) { + return { + invalidPhoneNumber: { + valid: false + } + }; + } + } + return null; + }; + } + + validate(): ValidationErrors | null { + return this.phoneFormGroup.get('phoneNumber').valid ? null : { + phoneFormGroup: false + }; + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (isDisabled) { + this.phoneFormGroup.disable({emitEvent: false}); + } else { + this.phoneFormGroup.enable({emitEvent: false}); + } + } + + writeValue(phoneNumber): void { + this.modelValue = phoneNumber; + const country = phoneNumber ? parsePhoneNumberFromString(phoneNumber)?.country : this.defaultCountry; + this.getFlagAndPhoneNumberData(country); + this.phoneFormGroup.patchValue({phoneNumber, country}, {emitEvent: !phoneNumber}); + } + + private updateModel() { + const phoneNumber = this.phoneFormGroup.get('phoneNumber'); + if (phoneNumber.valid && phoneNumber.value) { + this.modelValue = phoneNumber.value; + this.propagateChange(this.modelValue); + } else { + this.propagateChange(null); + } + } +} diff --git a/ui-ngx/src/app/shared/components/popover.component.scss b/ui-ngx/src/app/shared/components/popover.component.scss index 6a9c289fa1..2ef8e8bb34 100644 --- a/ui-ngx/src/app/shared/components/popover.component.scss +++ b/ui-ngx/src/app/shared/components/popover.component.scss @@ -1,5 +1,5 @@ /** - * Copyright © 2016-2021 The Thingsboard Authors + * Copyright © 2016-2022 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/shared/components/popover.component.ts b/ui-ngx/src/app/shared/components/popover.component.ts index bea56db633..ad2e90cc15 100644 --- a/ui-ngx/src/app/shared/components/popover.component.ts +++ b/ui-ngx/src/app/shared/components/popover.component.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. @@ -558,7 +558,9 @@ export class TbPopoverComponent implements OnDestroy, OnInit { onClickOutside(event: MouseEvent): void { if (this.tbHideOnClickOutside && !this.origin.elementRef.nativeElement.contains(event.target) && this.tbTrigger !== null) { - this.hide(); + if (!this.isTopOverlay(event.target as Element)) { + this.hide(); + } } } @@ -571,6 +573,21 @@ export class TbPopoverComponent implements OnDestroy, OnInit { this.tbAnimationDone.next(); } + private isTopOverlay(targetElement: Element): boolean { + const target = $(targetElement); + if (target.parents('.cdk-overlay-container').length) { + let targetOverlayContainerChild: JQuery; + if (target.hasClass('cdk-overlay-backdrop')) { + targetOverlayContainerChild = target; + } else { + targetOverlayContainerChild = target.parents('.cdk-overlay-pane').parent(); + } + const currentOverlayContainerChild = $(this.overlay.overlayRef.overlayElement).parent(); + return targetOverlayContainerChild.index() > currentOverlayContainerChild.index(); + } + return false; + } + private updateVisibilityByContent(): void { if (this.isEmpty()) { this.hide(); diff --git a/ui-ngx/src/app/shared/components/popover.models.ts b/ui-ngx/src/app/shared/components/popover.models.ts index 2e5b07fb0b..20f0125a98 100644 --- a/ui-ngx/src/app/shared/components/popover.models.ts +++ b/ui-ngx/src/app/shared/components/popover.models.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/shared/components/popover.service.ts b/ui-ngx/src/app/shared/components/popover.service.ts index 8eb3235ccd..4a3b59da93 100644 --- a/ui-ngx/src/app/shared/components/popover.service.ts +++ b/ui-ngx/src/app/shared/components/popover.service.ts @@ -1,5 +1,5 @@ /// -/// Copyright © 2016-2021 The Thingsboard Authors +/// Copyright © 2016-2022 The Thingsboard Authors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. diff --git a/ui-ngx/src/app/shared/components/protobuf-content.component.html b/ui-ngx/src/app/shared/components/protobuf-content.component.html index 23a16ece43..1e7403182f 100644 --- a/ui-ngx/src/app/shared/components/protobuf-content.component.html +++ b/ui-ngx/src/app/shared/components/protobuf-content.component.html @@ -1,6 +1,6 @@ + + + + + + + {{getDescription(queue)}} + + +
+
+ device-profile.no-device-profiles-found +
+ + + {{ translate.get('queue.no-queues-matching', + {queue: truncate.transform(searchText, true, 6, '...')}) | async }} + + +
+
+
+ + {{ 'queue.queue-required' | translate }} + +
diff --git a/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.scss b/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.scss new file mode 100644 index 0000000000..45a4ab9808 --- /dev/null +++ b/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.scss @@ -0,0 +1,29 @@ +/** + * Copyright © 2016-2022 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +::ng-deep { + .queue-option { + .mat-option-text { + display: inline; + } + .queue-option-description { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + } +} diff --git a/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.ts b/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.ts new file mode 100644 index 0000000000..897e041649 --- /dev/null +++ b/ui-ngx/src/app/shared/components/queue/queue-autocomplete.component.ts @@ -0,0 +1,223 @@ +/// +/// Copyright © 2016-2022 The Thingsboard Authors +/// +/// Licensed under the Apache License, Version 2.0 (the "License"); +/// you may not use this file except in compliance with the License. +/// You may obtain a copy of the License at +/// +/// http://www.apache.org/licenses/LICENSE-2.0 +/// +/// Unless required by applicable law or agreed to in writing, software +/// distributed under the License is distributed on an "AS IS" BASIS, +/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +/// See the License for the specific language governing permissions and +/// limitations under the License. +/// + +import { Component, ElementRef, forwardRef, Input, OnInit, ViewChild } from '@angular/core'; +import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { Observable, of } from 'rxjs'; +import { catchError, debounceTime, distinctUntilChanged, map, share, switchMap, tap } from 'rxjs/operators'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { TranslateService } from '@ngx-translate/core'; +import { coerceBooleanProperty } from '@angular/cdk/coercion'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType } from '@shared/models/entity-type.models'; +import { BaseData } from '@shared/models/base-data'; +import { EntityService } from '@core/http/entity.service'; +import { TruncatePipe } from '@shared/pipe/truncate.pipe'; +import { QueueInfo, ServiceType } from '@shared/models/queue.models'; +import { QueueService } from '@core/http/queue.service'; +import { PageLink } from '@shared/models/page/page-link'; +import { Direction } from '@shared/models/page/sort-order'; +import { emptyPageData } from '@shared/models/page/page-data'; + +@Component({ + selector: 'tb-queue-autocomplete', + templateUrl: './queue-autocomplete.component.html', + styleUrls: ['./queue-autocomplete.component.scss'], + providers: [{ + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => QueueAutocompleteComponent), + multi: true + }] +}) +export class QueueAutocompleteComponent implements ControlValueAccessor, OnInit { + + selectQueueFormGroup: FormGroup; + + modelValue: string | null; + + @Input() + labelText: string; + + @Input() + requiredText: string; + + private requiredValue: boolean; + get required(): boolean { + return this.requiredValue; + } + @Input() + set required(value: boolean) { + this.requiredValue = coerceBooleanProperty(value); + } + + @Input() + queueType: ServiceType; + + @Input() + disabled: boolean; + + @ViewChild('queueInput', {static: true}) queueInput: ElementRef; + + filteredQueues: Observable>>; + + searchText = ''; + + private dirty = false; + + private propagateChange = (v: any) => { }; + + constructor(private store: Store, + public translate: TranslateService, + public truncate: TruncatePipe, + private entityService: EntityService, + private queueService: QueueService, + private fb: FormBuilder) { + this.selectQueueFormGroup = this.fb.group({ + queueId: [null] + }); + } + + registerOnChange(fn: any): void { + this.propagateChange = fn; + } + + registerOnTouched(fn: any): void { + } + + ngOnInit() { + this.filteredQueues = this.selectQueueFormGroup.get('queueId').valueChanges + .pipe( + debounceTime(150), + tap(value => { + let modelValue; + if (typeof value === 'string' || !value) { + modelValue = null; + } else { + modelValue = value.id.id; + } + this.updateView(modelValue); + if (value === null) { + this.clear(); + } + }), + map(value => value ? (typeof value === 'string' ? value : value.name) : ''), + distinctUntilChanged(), + switchMap(name => this.fetchQueue(name) ), + share() + ); + } + + ngAfterViewInit(): void {} + + getCurrentEntity(): BaseData | null { + const currentRuleChain = this.selectQueueFormGroup.get('queueId').value; + if (currentRuleChain && typeof currentRuleChain !== 'string') { + return currentRuleChain as BaseData; + } else { + return null; + } + } + + setDisabledState(isDisabled: boolean): void { + this.disabled = isDisabled; + if (this.disabled) { + this.selectQueueFormGroup.disable({emitEvent: false}); + } else { + this.selectQueueFormGroup.enable({emitEvent: false}); + } + } + + textIsNotEmpty(text: string): boolean { + return (text && text.length > 0); + } + + writeValue(value: string | null): void { + this.searchText = ''; + if (value != null) { + const targetEntityType = EntityType.QUEUE; + this.entityService.getEntity(targetEntityType, value, {ignoreLoading: true, ignoreErrors: true}).subscribe( + (entity) => { + this.modelValue = entity.id.id; + this.selectQueueFormGroup.get('queueId').patchValue(entity, {emitEvent: false}); + }, + () => { + this.modelValue = null; + this.selectQueueFormGroup.get('queueId').patchValue('', {emitEvent: false}); + if (value !== null) { + this.propagateChange(this.modelValue); + } + } + ); + } else { + this.modelValue = null; + this.selectQueueFormGroup.get('queueId').patchValue('', {emitEvent: false}); + } + this.dirty = true; + } + + onFocus() { + if (this.dirty) { + this.selectQueueFormGroup.get('queueId').updateValueAndValidity({onlySelf: true, emitEvent: true}); + this.dirty = false; + } + } + + reset() { + this.selectQueueFormGroup.get('queueId').patchValue('', {emitEvent: false}); + } + + updateView(value: string | null) { + if (this.modelValue !== value) { + this.modelValue = value; + this.propagateChange(this.modelValue); + } + } + + displayQueueFn(queue?: BaseData): string | undefined { + return queue ? queue.name : undefined; + } + + fetchQueue(searchText?: string): Observable> { + this.searchText = searchText; + const pageLink = new PageLink(10, 0, searchText, { + property: 'name', + direction: Direction.ASC + }); + return this.queueService.getTenantQueuesByServiceType(pageLink, this.queueType, {ignoreLoading: true}).pipe( + catchError(() => of(emptyPageData())), + map(pageData => { + return pageData.data; + }) + ); + } + + getDescription(value) { + return value.additionalInfo?.description ? value.additionalInfo.description : + this.translate.instant( + 'queue.alt-description', + {submitStrategy: value.submitStrategy.type, processingStrategy: value.processingStrategy.type} + ); + } + + clear() { + this.selectQueueFormGroup.get('queueId').patchValue('', {emitEvent: true}); + setTimeout(() => { + this.queueInput.nativeElement.blur(); + this.queueInput.nativeElement.focus(); + }, 0); + } +} diff --git a/ui-ngx/src/app/shared/components/queue/queue-type-list.component.html b/ui-ngx/src/app/shared/components/queue/queue-type-list.component.html deleted file mode 100644 index c05e0acdc2..0000000000 --- a/ui-ngx/src/app/shared/components/queue/queue-type-list.component.html +++ /dev/null @@ -1,49 +0,0 @@ - - - {{ 'queue.name' | translate }} - - - - - - - - - {{ translate.get('queue.no-queues-matching', {queue: searchText}) | async }} - - - - - {{ 'queue.name_required' | translate }} - - device-profile.select-queue-hint - diff --git a/ui-ngx/src/app/shared/components/queue/queue-type-list.component.ts b/ui-ngx/src/app/shared/components/queue/queue-type-list.component.ts deleted file mode 100644 index 11fe16731b..0000000000 --- a/ui-ngx/src/app/shared/components/queue/queue-type-list.component.ts +++ /dev/null @@ -1,199 +0,0 @@ -/// -/// Copyright © 2016-2021 The Thingsboard Authors -/// -/// Licensed under the Apache License, Version 2.0 (the "License"); -/// you may not use this file except in compliance with the License. -/// You may obtain a copy of the License at -/// -/// http://www.apache.org/licenses/LICENSE-2.0 -/// -/// Unless required by applicable law or agreed to in writing, software -/// distributed under the License is distributed on an "AS IS" BASIS, -/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -/// See the License for the specific language governing permissions and -/// limitations under the License. -/// - -import { AfterViewInit, Component, ElementRef, forwardRef, Input, OnDestroy, OnInit, ViewChild } from '@angular/core'; -import { ControlValueAccessor, FormBuilder, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; -import { Observable, of } from 'rxjs'; -import { - catchError, - debounceTime, - distinctUntilChanged, - map, - publishReplay, - refCount, - switchMap, - tap -} from 'rxjs/operators'; -import { Store } from '@ngrx/store'; -import { AppState } from '@app/core/core.state'; -import { TranslateService } from '@ngx-translate/core'; -import { coerceBooleanProperty } from '@angular/cdk/coercion'; -import { QueueService } from '@core/http/queue.service'; -import { ServiceType } from '@shared/models/queue.models'; - -interface Queue { - queueName: string; -} - -@Component({ - selector: 'tb-queue-type-list', - templateUrl: './queue-type-list.component.html', - styleUrls: [], - providers: [{ - provide: NG_VALUE_ACCESSOR, - useExisting: forwardRef(() => QueueTypeListComponent), - multi: true - }] -}) -export class QueueTypeListComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy { - - queueFormGroup: FormGroup; - - modelValue: Queue | null; - - private requiredValue: boolean; - get required(): boolean { - return this.requiredValue; - } - @Input() - set required(value: boolean) { - this.requiredValue = coerceBooleanProperty(value); - } - - @Input() - disabled: boolean; - - @Input() - queueType: ServiceType; - - @ViewChild('queueInput', {static: true}) queueInput: ElementRef; - - filteredQueues: Observable>; - - queues: Observable>; - - searchText = ''; - - private dirty = false; - - private propagateChange = (v: any) => { }; - - constructor(private store: Store, - public translate: TranslateService, - private queueService: QueueService, - private fb: FormBuilder) { - this.queueFormGroup = this.fb.group({ - queue: [null] - }); - } - - registerOnChange(fn: any): void { - this.propagateChange = fn; - } - - registerOnTouched(fn: any): void { - } - - ngOnInit() { - this.filteredQueues = this.queueFormGroup.get('queue').valueChanges - .pipe( - debounceTime(150), - distinctUntilChanged(), - tap(value => { - let modelValue; - if (typeof value === 'string' || !value) { - modelValue = null; - } else { - modelValue = value; - } - this.updateView(modelValue); - }), - map(value => value ? (typeof value === 'string' ? value : value.queueName) : ''), - switchMap(queue => this.fetchQueues(queue) ) - ); - } - - ngAfterViewInit(): void { - } - - ngOnDestroy(): void { - } - - setDisabledState(isDisabled: boolean): void { - this.disabled = isDisabled; - if (this.disabled) { - this.queueFormGroup.disable({emitEvent: false}); - } else { - this.queueFormGroup.enable({emitEvent: false}); - } - } - - writeValue(value: string | null): void { - this.searchText = ''; - this.modelValue = value ? { queueName: value } : null; - this.queueFormGroup.get('queue').patchValue(this.modelValue, {emitEvent: false}); - this.dirty = true; - } - - onFocus() { - if (this.dirty) { - this.queueFormGroup.get('queue').updateValueAndValidity({onlySelf: true, emitEvent: true}); - this.dirty = false; - } - } - - updateView(value: Queue | null) { - if (this.modelValue !== value) { - this.modelValue = value; - this.propagateChange(this.modelValue ? this.modelValue.queueName : null); - } - } - - displayQueueFn(queue?: Queue): string | undefined { - return queue ? queue.queueName : undefined; - } - - fetchQueues(searchText?: string): Observable> { - this.searchText = searchText; - return this.getQueues().pipe( - catchError(() => of([] as Array)), - map(queues => { - const result = queues.filter( queue => { - return searchText ? queue.queueName.toUpperCase().startsWith(searchText.toUpperCase()) : true; - }); - if (result.length) { - result.sort((q1, q2) => q1.queueName.localeCompare(q2.queueName)); - } - return result; - }) - ); - } - - getQueues(): Observable> { - if (!this.queues) { - this.queues = this.queueService. - getTenantQueuesByServiceType(this.queueType, {ignoreLoading: true}).pipe( - map((queues) => { - return queues.map((queueName) => { - return { queueName }; - }); - }), - publishReplay(1), - refCount() - ); - } - return this.queues; - } - - clear() { - this.queueFormGroup.get('queue').patchValue(null, {emitEvent: true}); - setTimeout(() => { - this.queueInput.nativeElement.blur(); - this.queueInput.nativeElement.focus(); - }, 0); - } - -} diff --git a/ui-ngx/src/app/shared/components/relation/relation-type-autocomplete.component.html b/ui-ngx/src/app/shared/components/relation/relation-type-autocomplete.component.html index b572f6b9df..096d06c1ee 100644 --- a/ui-ngx/src/app/shared/components/relation/relation-type-autocomplete.component.html +++ b/ui-ngx/src/app/shared/components/relation/relation-type-autocomplete.component.html @@ -1,6 +1,6 @@