Browse Source

Merge 6b72f86615 into 21ea755acf

pull/14494/merge
IF79l 3 hours ago
committed by GitHub
parent
commit
e61c021a5f
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 38
      TEST_README.md
  2. 69
      application/src/main/java/org/thingsboard/server/controller/PingController.java
  3. 97
      application/src/test/java/org/thingsboard/server/controller/PingControllerTest.java
  4. 4
      ui-ngx/src/app/core/http/device.service.ts
  5. 16
      ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html
  6. 24
      ui-ngx/src/app/modules/home/pages/device/device-tabs.component.ts

38
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

69
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<String, Object> 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<String, Object> response = new HashMap<>();
response.put("deviceId", deviceId.toString());
response.put("reachable", isReachable);
response.put("lastSeen", lastActivityTime);
return response;
}
}

97
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<String, Object> 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<String, Object> response = pingController.pingDeviceById(deviceId.getId());
Assert.assertEquals(false, response.get("reachable"));
}
}

4
ui-ngx/src/app/core/http/device.service.ts

@ -306,4 +306,8 @@ export class DeviceService {
})
);
}
public pingDevice(deviceId: string): Observable<any> {
return this.http.get<any>(`/api/device/ping/${deviceId}`);
}
}

16
ui-ngx/src/app/modules/home/pages/device/device-tabs.component.html

@ -6,12 +6,22 @@
-->
@if (entity) {
<mat-tab label="{{ 'attribute.attributes' | translate }}" #attributesTab="matTab">
<div style="padding: 15px 0 0 15px;">
<button mat-raised-button color="primary"
(click)="pingDevice($event)"
matTooltip="Check device connectivity">
<mat-icon>network_check</mat-icon>
Ping Device
</button>
</div>
<tb-attribute-table [defaultAttributeScope]="attributeScopes.CLIENT_SCOPE"
[active]="attributesTab.isActive"
[entityId]="entity.id"
[entityName]="entity.name">
</tb-attribute-table>
</mat-tab>
<mat-tab label="{{ 'attribute.latest-telemetry' | translate }}" #telemetryTab="matTab">
<tb-attribute-table [defaultAttributeScope]="latestTelemetryTypes.LATEST_TELEMETRY"
disableAttributeScopeSelection
@ -20,6 +30,7 @@
[entityName]="entity.name">
</tb-attribute-table>
</mat-tab>
@if (authUser.authority === authorities.TENANT_ADMIN) {
<mat-tab label="{{ 'entity.type-calculated-fields' | translate }}" #calculatedFieldsTab="matTab">
<tb-calculated-fields-table [active]="calculatedFieldsTab.isActive" [entityId]="entity.id" [ownerId]="ownerId"/>
@ -28,19 +39,24 @@
<tb-alarm-rules-table [active]="calculatedFieldsAlarmRules.isActive" [entityId]="entity.id" [entityName]="entity.name" [ownerId]="ownerId"></tb-alarm-rules-table>
</mat-tab>
}
<mat-tab label="{{ 'alarm.alarms' | translate }}" #alarmsTab="matTab">
<tb-alarm-table [active]="alarmsTab.isActive" [entityId]="entity.id"></tb-alarm-table>
</mat-tab>
<mat-tab label="{{ 'device.events' | translate }}" #eventsTab="matTab">
<tb-event-table [defaultEventType]="eventTypes.ERROR" [active]="eventsTab.isActive" [tenantId]="entity.tenantId.id"
[entityId]="entity.id"></tb-event-table>
</mat-tab>
<mat-tab label="{{ 'relation.relations' | translate }}" #relationsTab="matTab">
<tb-relation-table [active]="relationsTab.isActive" [entityId]="entity.id"></tb-relation-table>
</mat-tab>
<mat-tab label="{{ 'audit-log.audit-logs' | translate }}" #auditLogsTab="matTab">
<tb-audit-log-table detailsMode="true" [active]="auditLogsTab.isActive" [auditLogMode]="auditLogModes.ENTITY" [entityId]="entity.id"></tb-audit-log-table>
</mat-tab>
@if (authUser.authority === authorities.TENANT_ADMIN) {
<mat-tab label="{{ 'version-control.version-control' | translate }}" #versionControlTab="matTab">
<tb-version-control detailsMode="true" singleEntityMode="true"

24
ui-ngx/src/app/modules/home/pages/device/device-tabs.component.ts

@ -7,7 +7,7 @@ import { AppState } from '@core/core.state';
import { Device, DeviceInfo } from '@shared/models/device.models';
import { EntityTabsComponent } from '../../components/entity/entity-tabs.component';
import { EntityId } from "@shared/models/id/entity-id";
import { DeviceService } from '@core/http/device.service';
@Component({
selector: 'tb-device-tabs',
templateUrl: './device-tabs.component.html',
@ -18,7 +18,9 @@ export class DeviceTabsComponent extends EntityTabsComponent<Device> {
ownerId: EntityId;
constructor(protected store: Store<AppState>) {
constructor(protected store: Store<AppState>,
private deviceService: DeviceService) {
super(store);
}
@ -39,4 +41,22 @@ export class DeviceTabsComponent extends EntityTabsComponent<Device> {
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');
}
);
}
}

Loading…
Cancel
Save