Browse Source
# Conflicts: # application/src/main/java/org/thingsboard/server/service/edge/rpc/EdgeGrpcService.javapull/16162/head
183 changed files with 6325 additions and 6424 deletions
@ -0,0 +1,30 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.solutions.data; |
|||
|
|||
import lombok.AccessLevel; |
|||
import lombok.Getter; |
|||
import lombok.RequiredArgsConstructor; |
|||
|
|||
/** |
|||
* The outcome of validating a solution template before anything is created: either the install can go ahead, or the |
|||
* entities of the tenant the template clashes with, reported as the markdown the install dialog renders. |
|||
*/ |
|||
@Getter |
|||
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) |
|||
public class SolutionValidationResult { |
|||
|
|||
private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); |
|||
|
|||
private final boolean passed; |
|||
private final String conflictReport; |
|||
|
|||
public static SolutionValidationResult passed() { |
|||
return PASSED; |
|||
} |
|||
|
|||
public static SolutionValidationResult conflictsFound(String conflictReport) { |
|||
return new SolutionValidationResult(false, conflictReport); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,325 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge.rpc; |
|||
|
|||
import com.google.common.util.concurrent.Futures; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; |
|||
import org.thingsboard.server.cache.TbTransactionalCache; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.msg.notification.NotificationRuleProcessor; |
|||
import org.thingsboard.server.gen.transport.TransportProtos.ToEdgeEventNotificationMsg; |
|||
import org.thingsboard.server.queue.TbQueueConsumer; |
|||
import org.thingsboard.server.queue.common.TbProtoQueueMsg; |
|||
import org.thingsboard.server.queue.common.consumer.QueueConsumerManager; |
|||
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
import org.thingsboard.server.service.executors.GrpcCallbackExecutorService; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ConcurrentMap; |
|||
import java.util.concurrent.Executors; |
|||
import java.util.concurrent.ScheduledExecutorService; |
|||
import java.util.concurrent.ScheduledFuture; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.doAnswer; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
/** |
|||
* Covers the reconnect race between a session that is being torn down and the session that has already |
|||
* taken the edge over: the teardown must not detach, cancel the edge event check of, or consume the new |
|||
* events flag of the session that replaced it. |
|||
*/ |
|||
class EdgeGrpcServiceReconnectTest { |
|||
|
|||
// long enough that an armed check never actually fires during a test
|
|||
private static final long NO_RECORDS_SLEEP_INTERVAL_MS = 60_000L; |
|||
private static final String THIS_NODE = "test-core"; |
|||
|
|||
private EdgeGrpcService service; |
|||
private ScheduledExecutorService edgeEventProcessingExecutorService; |
|||
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache; |
|||
|
|||
private TenantId tenantId; |
|||
private EdgeId edgeId; |
|||
private Edge edge; |
|||
|
|||
@BeforeEach |
|||
@SuppressWarnings("unchecked") |
|||
void setUp() { |
|||
tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
edgeId = new EdgeId(UUID.randomUUID()); |
|||
edge = new Edge(edgeId); |
|||
edge.setTenantId(tenantId); |
|||
edge.setName("test-edge"); |
|||
|
|||
EdgeEventStorageSettings storageSettings = new EdgeEventStorageSettings(); |
|||
ReflectionTestUtils.setField(storageSettings, "noRecordsSleepInterval", NO_RECORDS_SLEEP_INTERVAL_MS); |
|||
|
|||
GrpcCallbackExecutorService grpcCallbackExecutorService = mock(GrpcCallbackExecutorService.class); |
|||
// run future callbacks inline so the re-arm is observable without waiting on a pool
|
|||
doAnswer(invocation -> { |
|||
invocation.getArgument(0, Runnable.class).run(); |
|||
return null; |
|||
}).when(grpcCallbackExecutorService).execute(any()); |
|||
|
|||
EdgeContextComponent ctx = mock(EdgeContextComponent.class); |
|||
when(ctx.getEdgeEventStorageSettings()).thenReturn(storageSettings); |
|||
when(ctx.getGrpcCallbackExecutorService()).thenReturn(grpcCallbackExecutorService); |
|||
when(ctx.getRuleProcessor()).thenReturn(mock(NotificationRuleProcessor.class)); |
|||
|
|||
TbServiceInfoProvider serviceInfoProvider = mock(TbServiceInfoProvider.class); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
|
|||
edgeIdServiceIdCache = mock(TbTransactionalCache.class); |
|||
// this node is the recorded owner of the edge, which is what a live local session implies
|
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); |
|||
edgeEventProcessingExecutorService = Executors.newSingleThreadScheduledExecutor(); |
|||
|
|||
service = new EdgeGrpcService(); |
|||
ReflectionTestUtils.setField(service, "ctx", ctx); |
|||
ReflectionTestUtils.setField(service, "tsSubService", mock(TelemetrySubscriptionService.class)); |
|||
ReflectionTestUtils.setField(service, "clusterService", mock(TbClusterService.class)); |
|||
ReflectionTestUtils.setField(service, "serviceInfoProvider", serviceInfoProvider); |
|||
ReflectionTestUtils.setField(service, "edgeIdServiceIdCache", edgeIdServiceIdCache); |
|||
ReflectionTestUtils.setField(service, "edgeEventProcessingExecutorService", edgeEventProcessingExecutorService); |
|||
} |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
edgeEventProcessingExecutorService.shutdownNow(); |
|||
} |
|||
|
|||
@Test |
|||
void checkIsArmedForTheCurrentSession() { |
|||
EdgeGrpcSession session = newSession(); |
|||
sessions().put(edgeId, session); |
|||
|
|||
scheduleEdgeEventsCheck(session); |
|||
|
|||
ScheduledFuture<?> armed = edgeEventChecks().get(edgeId); |
|||
assertThat((Object) armed).as("check armed for the session that owns the edge").isNotNull(); |
|||
assertThat(armed.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void checkIsNotArmedForASupersededSession() { |
|||
EdgeGrpcSession current = newSession(); |
|||
EdgeGrpcSession superseded = newSession(); |
|||
sessions().put(edgeId, current); |
|||
scheduleEdgeEventsCheck(current); |
|||
ScheduledFuture<?> armedByCurrent = edgeEventChecks().get(edgeId); |
|||
|
|||
scheduleEdgeEventsCheck(superseded); |
|||
|
|||
assertThat((Object) edgeEventChecks().get(edgeId)) |
|||
.as("the superseded session must neither cancel nor replace the current session's check") |
|||
.isSameAs(armedByCurrent); |
|||
assertThat(armedByCurrent.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectOfTheCurrentSessionDetachesItAndCancelsItsCheck() { |
|||
EdgeGrpcSession session = newSession(); |
|||
onEdgeConnect(session); |
|||
ScheduledFuture<?> armedCheck = edgeEventChecks().get(edgeId); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
assertThat(sessions()).doesNotContainKey(edgeId); |
|||
assertThat(sessionsById()).doesNotContainKey(session.getSessionId()); |
|||
assertThat(armedCheck.isCancelled()).as("the detached session's check is cancelled").isTrue(); |
|||
verify(edgeIdServiceIdCache).evict(edgeId); |
|||
verify(session).destroy(); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectOfASupersededSessionKeepsTheReconnectedSessionAndItsCheck() { |
|||
EdgeGrpcSession first = newSession(); |
|||
onEdgeConnect(first); |
|||
// the edge reconnects before the gRPC stream of the first session is closed
|
|||
EdgeGrpcSession second = newSession(); |
|||
onEdgeConnect(second); |
|||
ScheduledFuture<?> armedBySecond = edgeEventChecks().get(edgeId); |
|||
|
|||
onEdgeDisconnect(first); |
|||
|
|||
assertThat(sessions().get(edgeId)).as("the reconnected session stays registered").isSameAs(second); |
|||
assertThat(sessionsById()).containsKey(second.getSessionId()); |
|||
assertThat((Object) edgeEventChecks().get(edgeId)) |
|||
.as("the check armed by the reconnected session survives the teardown of the one it replaced") |
|||
.isSameAs(armedBySecond); |
|||
assertThat(armedBySecond.isCancelled()).isFalse(); |
|||
verify(edgeIdServiceIdCache, never()).evict(edgeId); |
|||
} |
|||
|
|||
@Test |
|||
void disconnectDoesNotClearTheNewEventsFlag() { |
|||
EdgeGrpcSession session = newSession(); |
|||
onEdgeConnect(session); |
|||
assertThat(newEvents()).containsEntry(edgeId, true); |
|||
|
|||
onEdgeDisconnect(session); |
|||
|
|||
assertThat(newEvents()) |
|||
.as("clearing the flag here would wipe the one a reconnecting session has just raised") |
|||
.containsEntry(edgeId, true); |
|||
} |
|||
|
|||
@Test |
|||
void checkOfTheCurrentSessionConsumesTheFlagAndReArms() throws Exception { |
|||
EdgeGrpcSession session = newSession(); |
|||
when(session.processEdgeEvents()).thenReturn(Futures.immediateFuture(false)); |
|||
sessions().put(edgeId, session); |
|||
newEvents().put(edgeId, true); |
|||
migrationProcessed().put(edgeId, Boolean.TRUE); |
|||
|
|||
processEvents(session); |
|||
|
|||
assertThat(newEvents()).containsEntry(edgeId, false); |
|||
verify(session).processHighPriorityEvents(); |
|||
verify(session).processEdgeEvents(); |
|||
assertThat((Object) edgeEventChecks().get(edgeId)).as("the check re-arms itself").isNotNull(); |
|||
} |
|||
|
|||
@Test |
|||
void checkOfASupersededSessionLeavesTheFlagForTheSessionThatOwnsTheEdge() throws Exception { |
|||
EdgeGrpcSession superseded = newSession(); |
|||
EdgeGrpcSession current = newSession(); |
|||
sessions().put(edgeId, current); |
|||
newEvents().put(edgeId, true); |
|||
migrationProcessed().put(edgeId, Boolean.TRUE); |
|||
|
|||
// cancel(true) cannot stop a check that has already started, so it runs against the old session
|
|||
processEvents(superseded); |
|||
|
|||
assertThat(newEvents()) |
|||
.as("consuming the flag here would leave the reconnected session with nothing to fetch") |
|||
.containsEntry(edgeId, true); |
|||
verify(superseded, never()).processHighPriorityEvents(); |
|||
verify(superseded, never()).processEdgeEvents(); |
|||
assertThat(edgeEventChecks()).doesNotContainKey(edgeId); |
|||
} |
|||
|
|||
@Test |
|||
void zombieCleanupCancelsTheCheckOfTheSessionItRemoves() { |
|||
KafkaEdgeGrpcSession zombie = newZombieSession(); |
|||
when(zombie.destroy()).thenReturn(true); |
|||
sessions().put(edgeId, zombie); |
|||
scheduleEdgeEventsCheck(zombie); |
|||
ScheduledFuture<?> armedByZombie = edgeEventChecks().get(edgeId); |
|||
|
|||
cleanupZombieSessions(); |
|||
|
|||
assertThat(sessions()).doesNotContainKey(edgeId); |
|||
assertThat(armedByZombie.isCancelled()) |
|||
.as("the removed zombie must not leave an armed check behind") |
|||
.isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void zombieCleanupKeepsASessionThatReconnectedDuringTheSweep() { |
|||
KafkaEdgeGrpcSession zombie = newZombieSession(); |
|||
EdgeGrpcSession reconnected = newSession(); |
|||
sessions().put(edgeId, zombie); |
|||
// the edge reconnects while the zombie is being destroyed, i.e. after the scan picked it up
|
|||
when(zombie.destroy()).thenAnswer(invocation -> { |
|||
sessions().put(edgeId, reconnected); |
|||
scheduleEdgeEventsCheck(reconnected); |
|||
return true; |
|||
}); |
|||
|
|||
cleanupZombieSessions(); |
|||
|
|||
assertThat(sessions().get(edgeId)).isSameAs(reconnected); |
|||
ScheduledFuture<?> armedByReconnected = edgeEventChecks().get(edgeId); |
|||
assertThat((Object) armedByReconnected).as("the reconnected session keeps its check").isNotNull(); |
|||
assertThat(armedByReconnected.isCancelled()).isFalse(); |
|||
} |
|||
|
|||
private EdgeGrpcSession newSession() { |
|||
EdgeGrpcSession session = mock(EdgeGrpcSession.class); |
|||
stubSession(session); |
|||
return session; |
|||
} |
|||
|
|||
private KafkaEdgeGrpcSession newZombieSession() { |
|||
KafkaEdgeGrpcSession session = mock(KafkaEdgeGrpcSession.class); |
|||
stubSession(session); |
|||
@SuppressWarnings("unchecked") |
|||
QueueConsumerManager<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumerManager = mock(QueueConsumerManager.class); |
|||
@SuppressWarnings("unchecked") |
|||
TbQueueConsumer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> consumer = mock(TbQueueConsumer.class); |
|||
when(consumerManager.getConsumer()).thenReturn(consumer); |
|||
when(consumer.isStopped()).thenReturn(false); |
|||
when(session.getConsumer()).thenReturn(consumerManager); |
|||
return session; |
|||
} |
|||
|
|||
private void stubSession(EdgeGrpcSession session) { |
|||
when(session.getEdge()).thenReturn(edge); |
|||
when(session.getTenantId()).thenReturn(tenantId); |
|||
when(session.getSessionId()).thenReturn(UUID.randomUUID()); |
|||
when(session.isConnected()).thenReturn(false); |
|||
when(session.destroy()).thenReturn(true); |
|||
} |
|||
|
|||
private void onEdgeConnect(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "onEdgeConnect", edgeId, session); |
|||
} |
|||
|
|||
private void onEdgeDisconnect(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "onEdgeDisconnect", edge, session.getSessionId()); |
|||
} |
|||
|
|||
private void scheduleEdgeEventsCheck(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "scheduleEdgeEventsCheck", session); |
|||
} |
|||
|
|||
private void processEvents(EdgeGrpcSession session) { |
|||
ReflectionTestUtils.invokeMethod(service, "processEvents", session, edgeId, tenantId); |
|||
} |
|||
|
|||
private void cleanupZombieSessions() { |
|||
ReflectionTestUtils.invokeMethod(service, "cleanupZombieSessions"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, EdgeGrpcSession> sessions() { |
|||
return field("sessions"); |
|||
} |
|||
|
|||
private ConcurrentMap<UUID, EdgeGrpcSession> sessionsById() { |
|||
return field("sessionsById"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, ScheduledFuture<?>> edgeEventChecks() { |
|||
return field("sessionEdgeEventChecks"); |
|||
} |
|||
|
|||
private Map<EdgeId, Boolean> newEvents() { |
|||
return field("sessionNewEvents"); |
|||
} |
|||
|
|||
private ConcurrentMap<EdgeId, Boolean> migrationProcessed() { |
|||
return field("edgeEventsMigrationProcessed"); |
|||
} |
|||
|
|||
@SuppressWarnings("unchecked") |
|||
private <T> T field(String name) { |
|||
return (T) ReflectionTestUtils.getField(service, name); |
|||
} |
|||
|
|||
} |
|||
@ -1,45 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.security.auth.oauth2; |
|||
|
|||
import jakarta.servlet.http.Cookie; |
|||
import jakarta.servlet.http.HttpServletRequest; |
|||
import org.junit.Test; |
|||
import org.mockito.Mockito; |
|||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; |
|||
|
|||
import java.util.LinkedHashMap; |
|||
import java.util.Map; |
|||
|
|||
import static org.junit.Assert.assertEquals; |
|||
import static org.junit.Assert.assertNotNull; |
|||
import static org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository.OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME; |
|||
|
|||
public class CookieUtilsTest { |
|||
|
|||
@Test |
|||
public void serializeDeserializeOAuth2AuthorizationRequestTest() { |
|||
HttpCookieOAuth2AuthorizationRequestRepository cookieRequestRepo = new HttpCookieOAuth2AuthorizationRequestRepository(); |
|||
HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); |
|||
|
|||
Map<String, Object> additionalParameters = new LinkedHashMap<>(); |
|||
additionalParameters.put("param1", "value1"); |
|||
additionalParameters.put("param2", "value2"); |
|||
var request = OAuth2AuthorizationRequest.authorizationCode() |
|||
.authorizationUri("testUri").clientId("testId") |
|||
.scope("read", "write") |
|||
.additionalParameters(additionalParameters).build(); |
|||
|
|||
|
|||
Cookie cookie = new Cookie(OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(request)); |
|||
Mockito.when(servletRequest.getCookies()).thenReturn(new Cookie[]{cookie}); |
|||
|
|||
OAuth2AuthorizationRequest deserializedRequest = cookieRequestRepo.loadAuthorizationRequest(servletRequest); |
|||
|
|||
assertNotNull(deserializedRequest); |
|||
assertEquals(request.getGrantType(), deserializedRequest.getGrantType()); |
|||
assertEquals(request.getAuthorizationUri(), deserializedRequest.getAuthorizationUri()); |
|||
assertEquals(request.getClientId(), deserializedRequest.getClientId()); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,294 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.solutions; |
|||
|
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.junit.jupiter.api.io.TempDir; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.DashboardInfo; |
|||
import org.thingsboard.server.common.data.Device; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.asset.Asset; |
|||
import org.thingsboard.server.common.data.asset.AssetProfile; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.common.data.rule.RuleChainType; |
|||
import org.thingsboard.server.dao.asset.AssetProfileService; |
|||
import org.thingsboard.server.dao.asset.AssetService; |
|||
import org.thingsboard.server.dao.customer.CustomerService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.device.DeviceService; |
|||
import org.thingsboard.server.dao.edge.EdgeService; |
|||
import org.thingsboard.server.dao.rule.RuleChainService; |
|||
import org.thingsboard.server.service.solutions.data.SolutionValidationResult; |
|||
|
|||
import java.io.IOException; |
|||
import java.nio.file.Files; |
|||
import java.nio.file.Path; |
|||
import java.util.List; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
import java.util.stream.Collectors; |
|||
import java.util.stream.IntStream; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoInteractions; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
class DefaultSolutionServiceTest { |
|||
|
|||
private static final String CONFLICTS_INTRO = |
|||
"Some entities of the solution template already exist. Rename or delete them and install the template again:"; |
|||
// mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it
|
|||
private static final int LISTED_NAMES_PER_TYPE = 10; |
|||
private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE |
|||
+ " names of each type are listed. The rest are reported the next time the template is installed."; |
|||
|
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
|
|||
@Mock |
|||
private CustomerService customerService; |
|||
@Mock |
|||
private DeviceService deviceService; |
|||
@Mock |
|||
private AssetService assetService; |
|||
@Mock |
|||
private DashboardService dashboardService; |
|||
@Mock |
|||
private RuleChainService ruleChainService; |
|||
@Mock |
|||
private DeviceProfileService deviceProfileService; |
|||
@Mock |
|||
private AssetProfileService assetProfileService; |
|||
@Mock |
|||
private EdgeService edgeService; |
|||
|
|||
@InjectMocks |
|||
private DefaultSolutionService service; |
|||
|
|||
@TempDir |
|||
private Path tempDir; |
|||
|
|||
@Test |
|||
void testValidateSolutionNamesEveryConflictingEntity() throws IOException { |
|||
writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); |
|||
writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); |
|||
|
|||
Customer customer = new Customer(); |
|||
customer.setTitle("Existing customer"); |
|||
|
|||
when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); |
|||
Asset asset = new Asset(); |
|||
asset.setName("Existing asset"); |
|||
when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); |
|||
when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) |
|||
.thenReturn(existingDevice("Existing device")); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence( |
|||
CONFLICTS_INTRO, |
|||
"- **Customer**: 'Existing customer'", |
|||
"- **Asset**: 'Existing asset'", |
|||
"- **Device**: 'Existing device'"); |
|||
// the randomized customer title and the entities that do not exist yet are not reported
|
|||
assertThat(result.getConflictReport()) |
|||
.doesNotContain("Customer $random") |
|||
.doesNotContain("New device") |
|||
.doesNotContain("New asset"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionReportsConflictingDashboard() throws IOException { |
|||
writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); |
|||
|
|||
DashboardInfo dashboard = new DashboardInfo(); |
|||
dashboard.setTitle("Overview"); |
|||
when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); |
|||
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); |
|||
|
|||
RuleChain ruleChain = new RuleChain(); |
|||
ruleChain.setName("Name the install creates"); |
|||
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) |
|||
.thenReturn(List.of(ruleChain)); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { |
|||
writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); |
|||
writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); |
|||
writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); |
|||
|
|||
DeviceProfile deviceProfile = new DeviceProfile(); |
|||
deviceProfile.setName("thermostat"); |
|||
AssetProfile assetProfile = new AssetProfile(); |
|||
assetProfile.setName("building"); |
|||
Edge edge = new Edge(); |
|||
edge.setName("Main edge"); |
|||
when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); |
|||
when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); |
|||
when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()).containsSubsequence( |
|||
"- **Device profile**: 'thermostat'", |
|||
"- **Asset profile**: 'building'", |
|||
"- **Edge**: 'Main edge'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); |
|||
|
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); |
|||
verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + |
|||
"{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); |
|||
writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(ruleChainService); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); |
|||
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); |
|||
|
|||
RuleChain ruleChain = new RuleChain(); |
|||
ruleChain.setName("Edge chain"); |
|||
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) |
|||
.thenReturn(List.of(ruleChain)); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { |
|||
writeEntitiesFile("devices.json", "null"); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(deviceService); |
|||
} |
|||
|
|||
@ParameterizedTest |
|||
@ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) |
|||
void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { |
|||
List<String> names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); |
|||
writeEntitiesFile("devices.json", names.stream() |
|||
.map(name -> "{\"name\": \"" + name + "\"}") |
|||
.collect(Collectors.joining(",", "[", "]"))); |
|||
names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) |
|||
.thenReturn(existingDevice(name))); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
int hidden = conflictCount - LISTED_NAMES_PER_TYPE; |
|||
String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) |
|||
.map(name -> "'" + name + "'").collect(Collectors.joining(", ")); |
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed |
|||
+ (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); |
|||
if (hidden > 0) { |
|||
assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); |
|||
} else { |
|||
assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* The profile lists are the json file plus every file in the directory of the same name merged into one list, so |
|||
* this is where the same name genuinely can appear twice. |
|||
*/ |
|||
@Test |
|||
void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { |
|||
writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); |
|||
writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); |
|||
|
|||
DeviceProfile profile = new DeviceProfile(); |
|||
profile.setName("Sensor profile"); |
|||
when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); |
|||
verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionWithoutConflicts() throws IOException { |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionWithoutEntityFiles() { |
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, |
|||
deviceProfileService, assetProfileService, edgeService); |
|||
} |
|||
|
|||
private static Device existingDevice(String name) { |
|||
Device device = new Device(); |
|||
device.setName(name); |
|||
return device; |
|||
} |
|||
|
|||
private void writeFile(String relativePath, String content) throws IOException { |
|||
Path file = tempDir.resolve(relativePath); |
|||
Files.createDirectories(file.getParent()); |
|||
Files.writeString(file, content); |
|||
} |
|||
|
|||
private void writeEntitiesFile(String fileName, String content) throws IOException { |
|||
Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); |
|||
Files.writeString(entitiesDir.resolve(fileName), content); |
|||
} |
|||
|
|||
} |
|||
@ -1,13 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.common.data.iot_hub; |
|||
|
|||
import lombok.Data; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
|
|||
@Data |
|||
public class DashboardInstalledItemDescriptor implements IotHubInstalledItemDescriptor { |
|||
|
|||
private DashboardId dashboardId; |
|||
|
|||
} |
|||
@ -0,0 +1,109 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.queue.discovery; |
|||
|
|||
import org.apache.curator.framework.CuratorFramework; |
|||
import org.apache.curator.framework.CuratorFrameworkFactory; |
|||
import org.apache.curator.retry.RetryOneTime; |
|||
import org.apache.curator.test.TestingServer; |
|||
import org.apache.curator.utils.CloseableUtils; |
|||
import org.apache.zookeeper.data.Stat; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.springframework.context.ApplicationEventPublisher; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.server.gen.transport.TransportProtos; |
|||
|
|||
import java.time.Duration; |
|||
import java.util.List; |
|||
|
|||
import static org.awaitility.Awaitility.await; |
|||
import static org.junit.jupiter.api.Assertions.assertEquals; |
|||
import static org.junit.jupiter.api.Assertions.assertNotEquals; |
|||
import static org.junit.jupiter.api.Assertions.assertTrue; |
|||
import static org.mockito.Mockito.lenient; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class ZkDiscoveryServiceZkTest { |
|||
|
|||
private static final String ZK_NODES_DIR = "/thingsboard/nodes"; |
|||
private static final String PROTECTED_NODE_NAME_REGEX = "_c_[0-9a-f-]{36}-node-\\d{10}"; |
|||
|
|||
@Mock |
|||
private ApplicationEventPublisher applicationEventPublisher; |
|||
@Mock |
|||
private TbServiceInfoProvider serviceInfoProvider; |
|||
@Mock |
|||
private PartitionService partitionService; |
|||
|
|||
private final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-core-0").build(); |
|||
|
|||
private TestingServer zkServer; |
|||
private CuratorFramework observer; |
|||
private ZkDiscoveryService zkDiscoveryService; |
|||
|
|||
@BeforeEach |
|||
public void setup() throws Exception { |
|||
zkServer = new TestingServer(true); |
|||
observer = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), new RetryOneTime(100)); |
|||
observer.start(); |
|||
|
|||
lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo); |
|||
lenient().when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo); |
|||
|
|||
zkDiscoveryService = new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "zkUrl", zkServer.getConnectString()); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "zkRetryInterval", 100); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "zkConnectionTimeout", 3000); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "zkSessionTimeout", 3000); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard"); |
|||
ReflectionTestUtils.setField(zkDiscoveryService, "recalculateDelay", 0L); |
|||
zkDiscoveryService.init(); |
|||
zkDiscoveryService.onApplicationEvent(null); |
|||
} |
|||
|
|||
@AfterEach |
|||
public void tearDown() throws Exception { |
|||
ReflectionTestUtils.invokeMethod(zkDiscoveryService, "destroy"); |
|||
CloseableUtils.closeQuietly(observer); |
|||
zkServer.close(); |
|||
} |
|||
|
|||
@Test |
|||
public void publishCreatesSingleProtectedNodeAndExcludesItFromOtherServersTest() throws Exception { |
|||
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR); |
|||
|
|||
assertEquals(1, nodes.size()); |
|||
assertTrue(nodes.get(0).matches(PROTECTED_NODE_NAME_REGEX), nodes.get(0)); |
|||
assertEquals(ZK_NODES_DIR + "/" + nodes.get(0), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); |
|||
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> |
|||
assertTrue(zkDiscoveryService.getOtherServers().isEmpty())); |
|||
} |
|||
|
|||
@Test |
|||
public void sessionExpiryLeavesSingleNodeOwnedByCurrentSessionTest() throws Exception { |
|||
String nodeBeforeExpiry = observer.getChildren().forPath(ZK_NODES_DIR).get(0); |
|||
|
|||
zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration(); |
|||
|
|||
await().atMost(Duration.ofSeconds(30)) |
|||
.during(Duration.ofSeconds(2)) |
|||
.ignoreExceptions() |
|||
.untilAsserted(() -> { |
|||
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR); |
|||
assertEquals(1, nodes.size()); |
|||
String nodePath = ZK_NODES_DIR + "/" + nodes.get(0); |
|||
assertNotEquals(nodeBeforeExpiry, nodes.get(0)); |
|||
assertEquals(nodePath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath")); |
|||
Stat stat = observer.checkExists().forPath(nodePath); |
|||
long sessionId = zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getSessionId(); |
|||
assertEquals(sessionId, stat.getEphemeralOwner()); |
|||
assertTrue(zkDiscoveryService.getOtherServers().isEmpty()); |
|||
}); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,109 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.script.api.js; |
|||
|
|||
import delight.nashornsandbox.NashornSandbox; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.Mockito; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.script.api.ScriptType; |
|||
import org.thingsboard.script.api.TbScriptException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.stats.StatsFactory; |
|||
|
|||
import javax.script.ScriptEngine; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ExecutionException; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.assertj.core.api.Assertions.assertThatThrownBy; |
|||
import static org.mockito.Mockito.mock; |
|||
|
|||
/** |
|||
* Covers the JS global scope lifecycle against both backends the service can be configured with. |
|||
* The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since |
|||
* {@code js.local.use_js_sandbox} defaults to true. |
|||
*/ |
|||
class NashornJsInvokeServiceLifecycleTest { |
|||
|
|||
private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; |
|||
|
|||
private NashornJsInvokeService service; |
|||
private boolean useJsSandbox; |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
if (service != null) { |
|||
service.stop(); |
|||
} |
|||
} |
|||
|
|||
@ParameterizedTest(name = "useJsSandbox = {0}") |
|||
@ValueSource(booleans = {true, false}) |
|||
void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { |
|||
givenService(useJsSandbox); |
|||
UUID scriptId = UUID.randomUUID(); |
|||
|
|||
JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); |
|||
assertThat(hasGlobalProperty(scriptInfo)).isTrue(); |
|||
assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); |
|||
|
|||
service.doRelease(scriptId); |
|||
|
|||
assertThat(hasGlobalProperty(scriptInfo)).isFalse(); |
|||
assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) |
|||
.isInstanceOf(ExecutionException.class) |
|||
.cause() |
|||
.isInstanceOf(TbScriptException.class); |
|||
} |
|||
|
|||
@ParameterizedTest(name = "useJsSandbox = {0}") |
|||
@ValueSource(booleans = {true, false}) |
|||
void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { |
|||
givenService(useJsSandbox); |
|||
UUID releasedId = UUID.randomUUID(); |
|||
UUID retainedId = UUID.randomUUID(); |
|||
|
|||
JsScriptInfo released = eval(releasedId, "return {v: 1};"); |
|||
JsScriptInfo retained = eval(retainedId, "return {v: 2};"); |
|||
|
|||
service.doRelease(releasedId); |
|||
|
|||
assertThat(hasGlobalProperty(released)).isFalse(); |
|||
assertThat(hasGlobalProperty(retained)).isTrue(); |
|||
assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); |
|||
} |
|||
|
|||
private void givenService(boolean useJsSandbox) { |
|||
this.useJsSandbox = useJsSandbox; |
|||
service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); |
|||
ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); |
|||
ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); |
|||
ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); |
|||
ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); |
|||
ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); |
|||
ReflectionTestUtils.setField(service, "maxMemory", 104857600L); |
|||
service.init(); |
|||
} |
|||
|
|||
private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { |
|||
service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); |
|||
return service.scriptInfoMap.get(scriptId); |
|||
} |
|||
|
|||
private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { |
|||
return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); |
|||
} |
|||
|
|||
private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { |
|||
String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; |
|||
Object result = useJsSandbox |
|||
? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) |
|||
: ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); |
|||
return Boolean.TRUE.equals(result); |
|||
} |
|||
|
|||
} |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue