diff --git a/TEST_README.md b/TEST_README.md new file mode 100644 index 0000000000..b747eb6373 --- /dev/null +++ b/TEST_README.md @@ -0,0 +1,38 @@ +# ThingsBoard Technical Assignment - Backend Extension + +**Participant:** Faisal Faris Al-Oufi + +## 1. Code Comprehension + +A summary of the core modules reviewed, detailing their purpose and key classes: + +| Module | Purpose | Key Classes & Role | +| :--- | :--- | :--- | +| **`application`** | The central service containing the core business logic, REST API controllers, and security enforcement. | `BaseController`, `PingController` | +| **`dao`** | The Data Access Object layer. Responsible for abstracting and managing database interactions (e.g., fetching device records). | `DeviceService` | +| **`transport`** | Handles device communication protocols (MQTT, HTTP, CoAP). This is the initial entry point for device telemetry data. | `MqttTransportService` | +| **`ui-ngx`** | The Angular web frontend. Provides the user interface for viewing data and managing entities. | `DeviceTabsComponent`, `DeviceService` (Angular HTTP service) | + +--- + +## 2. Overview of Implemented Changes + +| Task | Affected Files | Implementation Details | +| :--- | :--- | :--- | +| **Backend API** | `PingController.java` | Added the secure endpoint `GET /api/device/ping/{deviceId}`. Logic determines **`reachable`** based on the device's creation time being within the last 24 hours (for simplified demonstration). | +| **Unit Testing** | `PingControllerTest.java` | Implemented Mockito unit tests to verify the controller's logic, confirming correct `true` (reachable) and `false` (unreachable) responses. | +| **Frontend Service** | `device.service.ts` | Added the `pingDevice(deviceId: string)` method to correctly map the API call to the new backend endpoint. | +| **Frontend UI** | `device-tabs.component.ts/.html` | Implemented the `pingDevice` function in the component and integrated a "Ping Device" button on the UI, displaying the result in an **alert popup**. | + +--- + +## 3. Build & Test Instructions + +### Prerequisites +* Java Development Kit (JDK) **17** +* Apache Maven 3.6+ + +### Full Project Build +To clean and install the entire project: +```bash +mvn clean install -DskipTests \ No newline at end of file diff --git a/application/src/main/java/org/thingsboard/server/controller/PingController.java b/application/src/main/java/org/thingsboard/server/controller/PingController.java new file mode 100644 index 0000000000..7389154603 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/controller/PingController.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2016-2025 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +@RestController +@TbCoreComponent +@RequestMapping("/api") + +public class PingController extends BaseController { + + @Autowired + private DeviceService deviceService; + + @Operation(summary = "Ping Device by ID", description = "Pings a device by its ID to check connectivity.") + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") + @RequestMapping(value = "/device/ping/{deviceId}", method = RequestMethod.GET) + @ResponseBody + + public Map pingDeviceById( + @Parameter(description = "The ID of the device to ping") @PathVariable("deviceId") UUID deviceId) throws Exception { + SecurityUser user = getCurrentUser(); + TenantId tenantId = user.getTenantId(); + Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId)); + if (device == null) { + throw new IllegalArgumentException("Device not found with ID: " + deviceId); + } + long lastActivityTime = device.getCreatedTime(); + boolean isReachable = (System.currentTimeMillis() - lastActivityTime) <(24 * 60 * 60 * 1000) ; + + Map response = new HashMap<>(); + response.put("deviceId", deviceId.toString()); + response.put("reachable", isReachable); + response.put("lastSeen", lastActivityTime); + return response; + } +} \ No newline at end of file diff --git a/application/src/test/java/org/thingsboard/server/controller/PingControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/PingControllerTest.java new file mode 100644 index 0000000000..06c9fac0b3 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/controller/PingControllerTest.java @@ -0,0 +1,97 @@ +/** + * Copyright © 2016-2025 The Thingsboard Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.service.security.model.SecurityUser; + +import java.util.Map; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class PingControllerTest { + @Mock + private DeviceService deviceService; + + @Mock + private SecurityContext securityContext; + + @Mock + private Authentication authentication; + + @InjectMocks + private PingController pingController; + + private TenantId tenantId = new TenantId(UUID.randomUUID()); + private DeviceId deviceId = new DeviceId(UUID.randomUUID()); + + @Before + public void setUp() { + SecurityUser securityUser = new SecurityUser(); + securityUser.setTenantId(tenantId); + securityUser.setEmail("test@thingsboard.org"); + + when(securityContext.getAuthentication()).thenReturn(authentication); + when(authentication.getPrincipal()).thenReturn(securityUser); + SecurityContextHolder.setContext(securityContext); + +} + +@Test +public void testPingDeviceById_DeviceReachable() throws Exception { + Device device = new Device(); + device.setId(deviceId); + device.setTenantId(tenantId); + device.setCreatedTime(System.currentTimeMillis()); + + when(deviceService.findDeviceById(any(), any())).thenReturn(device); + + Map response = pingController.pingDeviceById(deviceId.getId()); + Assert.assertEquals(deviceId.getId().toString(), response.get("deviceId")); + Assert.assertTrue((Boolean) response.get("reachable")); +} + + +@Test +public void testPingDeviceById_DeviceNotReachable() throws Exception { + Device device = new Device(); + device.setId(deviceId); + device.setTenantId(tenantId); + device.setCreatedTime(System.currentTimeMillis() - (25 * 60 * 60 * 1000)); // 25 hours ago + + when(deviceService.findDeviceById(any(), any())).thenReturn(device); + + Map response = pingController.pingDeviceById(deviceId.getId()); + Assert.assertEquals(false, response.get("reachable")); +} +} \ No newline at end of file diff --git a/ui-ngx/src/app/core/http/device.service.ts b/ui-ngx/src/app/core/http/device.service.ts index 0c37df6a8b..940b3bd10a 100644 --- a/ui-ngx/src/app/core/http/device.service.ts +++ b/ui-ngx/src/app/core/http/device.service.ts @@ -306,4 +306,8 @@ export class DeviceService { }) ); } + + public pingDevice(deviceId: string): Observable { + return this.http.get(`/api/device/ping/${deviceId}`); + } } diff --git a/ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html b/ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html index 5d19c34ff3..772634e41f 100644 --- a/ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html +++ b/ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html @@ -6,12 +6,22 @@ --> @if (entity) { + +
+ +
+ + @if (authUser.authority === authorities.TENANT_ADMIN) { @@ -28,19 +39,24 @@ } + + + + + @if (authUser.authority === authorities.TENANT_ADMIN) { { ownerId: EntityId; - constructor(protected store: Store) { + constructor(protected store: Store, + private deviceService: DeviceService) { + super(store); } @@ -39,4 +41,22 @@ export class DeviceTabsComponent extends EntityTabsComponent { super.setEntity(entity); } +pingDevice($event: Event) { + if ($event) { + $event.stopPropagation(); + } + const id = this.entity.id.id; + + this.deviceService.pingDevice(id).subscribe( + (res) => { + const status = res.reachable ? 'Reachable' : 'Unreachable'; + const msg = `Device is ${status} (Last Seen: ${new Date(res.lastSeen).toLocaleString()})`; + alert(msg); + }, + (err) => { + console.error(err); + alert('Failed to ping device'); + } + ); + } }