100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Gateways: Add tunnel auto close support to the edge gateway (#2198)
Panos Kalogeropoulos7b9fdd63e8e8
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientConnector.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientConnector.javaindex 8ebf9ea24..8fcff59ce 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayClientConnector.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayClientConnector.java@@ -52,6 +52,7 @@ import java.util.*;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CopyOnWriteArrayList;+import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicReference;import java.util.function.Consumer;@@ -101,6 +102,7 @@ public class GatewayClientConnector implements AutoCloseable {protected String tunnelHostname;protected Integer tunnelPort;protected CompletableFuture<Void> initFuture;+ protected final ConcurrentHashMap<GatewayTunnelSession, ScheduledFuture<?>> tunnelAutoCloseTasks = new ConcurrentHashMap<>();public GatewayClientConnector(GatewayConnection connection,GatewayTunnelFactory tunnelFactory,@@ -472,13 +474,16 @@ public class GatewayClientConnector implements AutoCloseable {GatewayTunnelSession session = tunnelFactory.createSession(tunnelHostname, tunnelPort, tunnelInfo, this::onTunnelSessionClosed);activeTunnelSessions.add(session);- // Do cleanup on timeout or error+ // Do cleanup on timeout or error, schedule auto-close on successsession.connectFuture.orTimeout(GatewayConnector.RESPONSE_TIMEOUT_MILLIS-1000, TimeUnit.MILLISECONDS).whenComplete((unused, throwable) -> {if (throwable != null) {LOG.log(Level.WARNING, "Gateway tunnel session failed to connect: " + connection + ", " + tunnelInfo, throwable);activeTunnelSessions.remove(session);session.disconnect();+ } else {+ // Schedule auto-close if autoCloseTime is set+ scheduleAutoCloseTunnel(session);}});@@ -530,6 +535,8 @@ public class GatewayClientConnector implements AutoCloseable {try {gatewayTunnelSession.disconnect();+ // Cancel any scheduled auto-close task+ cancelAutoCloseTunnel(gatewayTunnelSession);LOG.info("Tunnel stopped successfully: " + connection + ", " + gatewayTunnelSession);} catch (Exception e) {error = e.getMessage();@@ -547,6 +554,58 @@ public class GatewayClientConnector implements AutoCloseable {}}+ /**+ * Schedule tunnel auto-close+ */+ protected void scheduleAutoCloseTunnel(GatewayTunnelSession session) {+ if (session.getTunnelInfo().getAutoCloseTime() == null) {+ LOG.fine("No auto-close time set for tunnel: " + session);+ return;+ }++ long delayMillis = session.getTunnelInfo().getAutoCloseTime().toEpochMilli() - timerService.getCurrentTimeMillis();+ if (delayMillis <= 0) {+ LOG.warning("Auto-close time for tunnel session is in the past, closing immediately: " + session);+ autoCloseTunnel(session);+ return;+ }++ LOG.info("Scheduling auto-close for tunnel session at " + session.getTunnelInfo().getAutoCloseTime() + " (in " + delayMillis + "ms)");++ ScheduledFuture<?> task = Container.SCHEDULED_EXECUTOR.schedule(+ () -> autoCloseTunnel(session),+ delayMillis,+ TimeUnit.MILLISECONDS+ );++ tunnelAutoCloseTasks.put(session, task);+ }++ /**+ * Cancel the scheduled auto-close task for a tunnel.+ */+ protected void cancelAutoCloseTunnel(GatewayTunnelSession session) {+ ScheduledFuture<?> task = tunnelAutoCloseTasks.remove(session);+ if (task != null) {+ task.cancel(false);+ LOG.fine("Cancelled auto-close task for tunnel: " + session);+ }+ }++ /**+ * Automatically closes a tunnel when its timeout expires, called by the scheduled task.+ */+ protected void autoCloseTunnel(GatewayTunnelSession session) {+ LOG.info("Automatically closing tunnel due to timeout: " + session);++ try {+ activeTunnelSessions.remove(session);+ stopGatewayTunnel(session);+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Failed to automatically close tunnel: " + session + ", error=" + e.getMessage());+ }+ }+public GatewayConnection getConnection() {return connection;}diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.javaindex 5079a56d0..6f2661d56 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayConnector.java@@ -85,8 +85,8 @@ public class GatewayConnector {String expectedSyncResponseName;protected boolean tunnellingSupported;protected String gatewayVersion;+ protected boolean tunnelTimeoutManagementSupported;protected final Map<Class<? extends SharedEvent>, Consumer<SharedEvent>> eventConsumerMap = new HashMap<>();-protected static List<Integer> ALPHA_NUMERIC_CHARACTERS = new ArrayList<>(62);static {@@ -264,6 +264,10 @@ public class GatewayConnector {sendMessageToGateway(new GatewayInitDoneEvent());tunnellingSupported = response != null && response.isTunnelingSupported();gatewayVersion = response != null ? response.getVersion() : null;+ tunnelTimeoutManagementSupported = VersionInfo.isVersionGreaterOrEqual(gatewayVersion, "1.1.0");+ if (!Objects.equals(VersionInfo.getGatewayApiVersion(), gatewayVersion)) {+ LOG.warning("Remote gateway's Gateway API version does not match the central manager's gateway API version. Current Central Instance API version: " + VersionInfo.getGatewayApiVersion() + ", Remote Gateway API version: " + gatewayVersion + ". GatewayId: " + gatewayId);+ }LOG.finest("Tunnelling supported=" + tunnellingSupported + ": " + getGatewayIdString());publishAttributeEvent(new AttributeEvent(gatewayId, GatewayAsset.TUNNELING_SUPPORTED, tunnellingSupported));LOG.finest("Setting connection status=" + ConnectionStatus.CONNECTED + ": " + getGatewayIdString());@@ -362,6 +366,10 @@ public class GatewayConnector {return gatewayVersion;}+ public boolean isTunnelTimeoutManagementSupported() {+ return tunnelTimeoutManagementSupported;+ }+protected void publishAttributeEvent(AttributeEvent event) {assetProcessingService.sendAttributeEvent(event, GatewayService.class.getSimpleName());}diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayTunnelSession.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayTunnelSession.javaindex 936743334..55a456539 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayTunnelSession.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayTunnelSession.java@@ -24,6 +24,7 @@ package org.openremote.manager.gateway;import org.openremote.model.gateway.GatewayTunnelInfo;+import java.util.Objects;import java.util.concurrent.CompletableFuture;/**@@ -60,7 +61,19 @@ public class GatewayTunnelSession {return tunnelInfo;}- @Override+ @Override+ public boolean equals(Object o) {+ if (o == null || getClass() != o.getClass()) return false;+ GatewayTunnelSession that = (GatewayTunnelSession) o;+ return Objects.equals(tunnelInfo, that.tunnelInfo);+ }++ @Override+ public int hashCode() {+ return Objects.hashCode(tunnelInfo);+ }++ @Overridepublic String toString() {return "GatewayTunnelSession{" +"connectFuture=" + connectFuture +diff --git a/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java b/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.javaindex 24f9b832f..a2ae60326 100644--- a/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java@@ -26,13 +26,9 @@ import org.openremote.model.system.HealthStatusProvider;import org.openremote.model.system.StatusResource;import org.openremote.model.util.ValueUtil;-import java.io.IOException;-import java.io.InputStream;import java.util.HashMap;import java.util.List;import java.util.Map;-import java.util.Properties;-import java.util.logging.Level;import java.util.logging.Logger;public class StatusResourceImpl implements StatusResource {@@ -43,28 +39,14 @@ public class StatusResourceImpl implements StatusResource {public StatusResourceImpl(Container container, List<HealthStatusProvider> healthStatusProviderList) {this.healthStatusProviderList = healthStatusProviderList;- Properties versionProps = new Properties();String authServerUrl = "";- String version = null;+ String version = VersionInfo.getManagerVersion();ManagerIdentityService identityService = container.getService(ManagerIdentityService.class);if (identityService != null && identityService.getIdentityProvider().getFrontendURI() != null) {authServerUrl = identityService.getIdentityProvider().getFrontendURI();}- try (InputStream resourceStream = StatusResourceImpl.class.getClassLoader().getResourceAsStream("version.properties")) {- if (resourceStream != null) {- versionProps.load(resourceStream);- version = versionProps.getProperty("version");- }- } catch (IOException ignored) {- }-- if (version == null) {- LOG.log(Level.WARNING, "Failed to load manager version properties file: version.properties");- version = "0.0.0";- }-serverInfo = Map.of("version", version,"authServerUrl", authServerUrl,diff --git a/manager/src/main/java/org/openremote/manager/system/VersionInfo.java b/manager/src/main/java/org/openremote/manager/system/VersionInfo.javaindex fa0566d08..96cb8f5cc 100644--- a/manager/src/main/java/org/openremote/manager/system/VersionInfo.java+++ b/manager/src/main/java/org/openremote/manager/system/VersionInfo.java@@ -30,7 +30,7 @@ import java.util.Properties;public class VersionInfo {public static final String VERSION = loadVersion();- public static final String GATEWAY_API_VERSION = "1.0.0";+ public static final String GATEWAY_API_VERSION = "1.1.0";public static String getManagerVersion() {return VERSION;diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 2a751619a..cddb1f37c 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -34,6 +34,7 @@ import org.openremote.container.security.ClientCredentialsAuthFormimport org.openremote.container.security.IdentityServiceimport org.openremote.container.security.PasswordAuthFormimport org.openremote.container.security.keycloak.KeycloakIdentityProvider+import org.openremote.container.security.keycloak.KeycloakResourceimport org.openremote.container.timer.TimerServiceimport org.openremote.container.util.LogUtilimport org.openremote.container.web.WebClient@@ -63,6 +64,7 @@ import org.openremote.model.util.MapAccessimport org.slf4j.Loggerimport org.slf4j.LoggerFactory+import javax.net.ssl.SSLSessionimport java.util.concurrent.TimeUnitimport java.util.logging.Handlerimport java.util.stream.Collectors@@ -514,6 +516,11 @@ trait ContainerTrait {.scheme("http").host("127.0.0.1").port(serverPort)}+ UriBuilder serverUri(boolean secure, String serverHost, int serverPort) {+ UriBuilder.fromUri("")+ .scheme(secure ? "https" : "http").host(serverHost).port(serverPort)+ }+void stopContainer() {try {if (container != null) {@@ -565,6 +572,35 @@ trait ContainerTrait {.getAccessToken(realm, new ClientCredentialsAuthForm(clientId, clientSecret))}+ /**+ * Makes a call to a remote OpenRemote manager to retrieve an access token for a given user+ * */+ AccessTokenResponse authenticate(boolean secure,+ String host,+ String realm,+ String clientId,+ String username,+ String password) {++ String scheme = secure ? "https" : "http"+ String basePath = "/auth"+ String baseUrl = "${scheme}://${host}${basePath}"++ ResteasyClient client = ResteasyClientBuilder.newBuilder().hostnameVerifier {String h, SSLSession s -> true }.build()+ ResteasyWebTarget target = (ResteasyWebTarget) client.target(baseUrl)++ KeycloakResource keycloak = target.proxy(KeycloakResource)++ try {+ return keycloak.getAccessToken(+ realm,+ new PasswordAuthForm(clientId, username, password)+ )+ } finally {+ client.close()+ }+ }+ProducerTemplate getMessageProducerTemplate(Container container) {return container.getService(MessageBrokerService.class).getContext().createProducerTemplate()}diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovyindex a62c313a3..2d02f2a4d 100644--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy@@ -3,6 +3,9 @@ package org.openremote.test.gatewayimport io.netty.channel.ChannelHandlerimport jakarta.ws.rs.ForbiddenExceptionimport org.apache.http.client.utils.URIBuilder+import org.jboss.resteasy.client.jaxrs.ResteasyClient+import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder+import org.jboss.resteasy.client.jaxrs.ResteasyWebTargetimport org.openremote.agent.protocol.http.HTTPAgentimport org.openremote.agent.protocol.http.HTTPAgentLinkimport org.openremote.agent.protocol.io.AbstractNettyIOClient@@ -32,6 +35,7 @@ import org.openremote.model.geo.GeoJSONPointimport org.openremote.model.query.AssetQueryimport org.openremote.model.query.filter.RealmPredicateimport org.openremote.model.security.User+import org.openremote.model.system.StatusResourceimport org.openremote.model.util.UniqueIdentifierGeneratorimport org.openremote.model.util.ValueUtilimport org.openremote.model.value.ValueFormat@@ -41,7 +45,9 @@ import spock.lang.Ignoreimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import javax.net.ssl.SSLSessionimport java.nio.file.Paths+import java.time.Durationimport java.util.concurrent.CopyOnWriteArrayListimport java.util.concurrent.TimeUnitimport java.util.concurrent.atomic.AtomicBoolean@@ -344,7 +350,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {}when: "the gateway returns the capabilities"- def capabilitiesReplyEvent = new GatewayCapabilitiesResponseEvent(true)+ def capabilitiesReplyEvent = new GatewayCapabilitiesResponseEvent(true, false, null)capabilitiesReplyEvent.setMessageID(messageId)gatewayClient.sendMessage(SharedEvent.MESSAGE_PREFIX + ValueUtil.asJSON(capabilitiesReplyEvent).get())@@ -698,6 +704,20 @@ class GatewayTest extends Specification implements ManagerContainerTrait {readAssetsReplyEvent.setMessageID(messageId)gatewayClient.sendMessage(SharedEvent.MESSAGE_PREFIX + ValueUtil.asJSON(readAssetsReplyEvent).get())+ then: "the central manager should have requested the capabilities of the gateway"+ conditions.eventually {+ assert clientReceivedMessages.size() == 3+ assert clientReceivedMessages.get(2).contains(GatewayCapabilitiesRequestEvent.TYPE)+ def gatewayCapabilitiesRequest = ValueUtil.JSON.readValue(clientReceivedMessages[2].substring(SharedEvent.MESSAGE_PREFIX.length()), GatewayCapabilitiesRequestEvent.class)+ messageId = gatewayCapabilitiesRequest.messageID+ }++ when: "The Gateway also sends a Gateway Capabilities response indicating tunnelling is supported"+ capabilitiesReplyEvent = new GatewayCapabilitiesResponseEvent(true, true, null)+ capabilitiesReplyEvent.setMessageID(messageId)+ gatewayClient.sendMessage(SharedEvent.MESSAGE_PREFIX + ValueUtil.asJSON(capabilitiesReplyEvent).get())++then: "the gateway connector sync should be completed"conditions.eventually {def gatewayConnector = gatewayService.gatewayConnectorMap.get(gateway.getId().toLowerCase(Locale.ROOT))@@ -715,6 +735,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {conditions.eventually {gateway = assetStorageService.find(gateway.getId())assert gateway.getGatewayStatus().orElse(null) == ConnectionStatus.CONNECTED+ assert gateway.getTunnelingSupported().get() == true}and: "the gateway should have the correct assets"@@ -1269,4 +1290,174 @@ class GatewayTest extends Specification implements ManagerContainerTrait {assert mirroredLight.getAttribute(Asset.NOTES).isPresent()}}+++ /**+ * This test requires a manager instance with tunnelling configured, so is manual for now unfortunately.+ * Refer to "Gateway Tunnelling Setup" in the docs for setting up the required environment.+ *+ * Make sure to make the relevant gateway in the central instance, and change the rest of the variables below+ * to reflect your setup, but most of these should be unchanged if you use the same setup as the documentation.+ */+ @Ignore+ def "Gateway Tunneling Edge Gateway Integration test"() {+ given: "the container environment is started"++ def sshKeyPath = Paths.get("deployment/sish/client/client")+++ def conditions = new PollingConditions(timeout: 6000, delay: 0.2)+ // The port where this test's manager webserver will run. cannot use random ephemeral port because of+ // its randomization, which when generating the gateway tunnel ID, will then generate a different gateway ID each time.+ def webserverPort = 12345+ def config = defaultConfig(webserverPort)+ def container = startContainer(config << [(GatewayService.OR_GATEWAY_TUNNEL_SSH_KEY_FILE): sshKeyPath.toAbsolutePath().toString()], defaultServices())+ def gatewayClientService = container.getService(GatewayClientService.class)+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)++ and: "Central Instance information with tunnelling enabled"++ def centralInstanceHostname = "localhost"+ def centralInstancePort = 443+ def isCentralInstanceSecure = (centralInstancePort == 443)+ def centralInstanceRealm = managerTestSetup.realmMasterName+ def centralInstanceAutoCloseMinutes = 2+ def gatewayClientId = "gateway-5bpoensnt4kaoobkp1fwzo"+ def gatewayClientSecret = "86a4fdff-3fc0-4b42-a276-82cb9862a623"+ def gatewayAssetId = "5bPOENSnt4kaoObkP1FWZO"++ def accessToken = authenticate(+ (isCentralInstanceSecure),+ centralInstanceHostname,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)+ ).token+ def gatewayResource = getClientApiTarget(serverUri((isCentralInstanceSecure), centralInstanceHostname, centralInstancePort), MASTER_REALM, accessToken).proxy(GatewayServiceResource.class)++ when: "a new gateway client connection is created to connect to the central instance"++ def gatewayConnection = new GatewayConnection(+ managerTestSetup.realmCityName,+ centralInstanceHostname,+ centralInstancePort,+ centralInstanceRealm,+ gatewayClientId,+ gatewayClientSecret,+ (isCentralInstanceSecure),+ null,+ Map.of("test", new GatewayAssetSyncRule()),+ false+ )++ gatewayClientService.setConnection(gatewayConnection)++ then: "the gateway client should become connected"+ conditions.eventually {+ assert gatewayClientService.clientRealmMap.get(managerTestSetup.realmCityName) != null+ }++ and: "the gateway connection status should become CONNECTED"+ conditions.eventually {+ assert gatewayClientService.getConnectionStatus(managerTestSetup.realmCityName) == ConnectionStatus.CONNECTED+ }++ and: "Tunnelling is supported in this gateway"+ assert gatewayClientService.gatewayTunnelFactory != null++ when: "We suspend the thread to allow the tunnel to settle"+ Thread.sleep(5000)++ and: "we request (from the central manager) for a new tunnel to be created"+ def tunnelInfo = new GatewayTunnelInfo(+ centralInstanceRealm,+ gatewayAssetId,+ GatewayTunnelInfo.Type.HTTP,+ "localhost",+ webserverPort)++ def centralManagerTunnelInfo = gatewayResource.startTunnel(tunnelInfo);++ then: "gateway should have been opened"++ conditions.eventually {+ def res = gatewayResource.getAllActiveTunnelInfos(null, centralInstanceRealm);+ print(res)+ assert Arrays.stream(res).anyMatch({ info -> info.id == tunnelInfo.getId() })+ assert gatewayClientService.activeTunnels.mappingCount() == 1+ }++ /*+ At this point, a gateway has been created from the central instance to the gateway that is running on this test.++ We can now request `/auth` from the tunnel URL, and the request route would look like this:+ This Groovy test --> Central Instance --> Sish --> Gateway Proxy --> Keycloak/Manager++ For the "Sish --> Gateway Proxy" request to be routed correctly, we need to edit our local `/etc/hosts` file+ to route the <tunnelid>.<tunnelSSHHost> to localhost, like this:++ 127.0.0.1 gw-5fj1sxvwwfp7wvgqgve91n.localhost++ If that is setup, the request correctly routes through the tunnel to the gateway, and we can request the edge manager.++ To assert proper connectivity, we are going to request a new admin token from the tunnel URL to make sure the+ Keycloak connection works, but also request the server info, which proves that the request has reached the manager+ webserver.++ * */+ and: "We request a new admin token from the tunnel URL"++ def x = authenticate(true,+ centralManagerTunnelInfo.id + "." + centralManagerTunnelInfo.hostname,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ MASTER_REALM_ADMIN_USER,+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT))++ then: "the request should be successful"++ assert x.error == null++ and: "Response contains a valid access token"++ assert x.getExpiresIn() > 0++ when: "We request the info endpoint of the currently running manager"++ String scheme = isCentralInstanceSecure ? "https" : "http"+ String basePath = "/api/master"+ String baseUrl = "${scheme}://$centralManagerTunnelInfo.id.$centralManagerTunnelInfo.hostname$basePath"++ ResteasyClient client = ResteasyClientBuilder.newBuilder().hostnameVerifier { String h, SSLSession s -> true }.build()+ ResteasyWebTarget target = (ResteasyWebTarget) client.target(baseUrl)++ then: "The request should be successful"+ conditions.eventually {+ def info = target.proxy(StatusResource.class).getInfo()++ assert info != null+ assert info.size() > 0+ assert info.valueDescriptorSchemaHashes == ValueUtil.getValueDescriptorSchemaHashes()+ }+++ and: "The test has been correctly configured to auto-stop by the gateway itself"+ conditions.eventually {+ assert gatewayClientService.tunnelAutoCloseTasks.mappingCount() == 1+ assert gatewayClientService.tunnelAutoCloseTasks.get(centralManagerTunnelInfo.getId()) != null+ }++ when: "The timer is advanced forward by central instance's OR_GATEWAY_TUNNEL_AUTO_CLOSE_MINUTES to trigger auto-close"+ //TODO: This actually doesn't work.+ //the autoClose tunnel task is scheduled by the ScheduledExecutor, which is on a timeout basis, not a clock basis.++ advancePseudoClock(Duration.ofMinutes(centralInstanceAutoCloseMinutes).toMillis(), TimeUnit.MILLISECONDS)++ then: "The tunnel should be closed automatically by the gateway"+ conditions.eventually {+ assert gatewayClientService.tunnelAutoCloseTasks.mappingCount() == 0+ }++ }}diff --git a/test/src/test/groovy/org/openremote/test/system/VersionInfoTest.groovy b/test/src/test/groovy/org/openremote/test/system/VersionInfoTest.groovynew file mode 100644index 000000000..d8cdf1af3--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/system/VersionInfoTest.groovy@@ -0,0 +1,108 @@+package org.openremote.test.system++import org.openremote.manager.system.VersionInfo+import spock.lang.Specification+import spock.lang.Unroll++class VersionInfoTest extends Specification {++ @Unroll+ def "compareVersions('#v1', '#v2') should return #expected"() {+ expect:+ Integer.signum(VersionInfo.compareVersions(v1, v2)) == Integer.signum(expected)++ where:+ v1 | v2 || expected+ "1.0.0" | "1.0.0" || 0+ "1.0.0" | "1.0.1" || -1+ "1.0.1" | "1.0.0" || 1+ "1.0" | "1.0.0" || 0+ "1.0.0" | "1.0" || 0+ "2.0.0" | "1.9.9" || 1+ "1.9.9" | "2.0.0" || -1+ "1.2.3" | "1.2.3.4" || -1+ "1.2.3.4" | "1.2.3" || 1+ "10.0.0" | "2.0.0" || 1+ "2.0.0" | "10.0.0" || -1+ "1.0" | "1.0.0.0" || 0+ }++ @Unroll+ def "compareVersions with qualifiers: '#v1' vs '#v2'"() {+ expect:+ Integer.signum(VersionInfo.compareVersions(v1, v2)) == Integer.signum(expected)++ where:+ v1 | v2 || expected+ "1.0.0" | "1.0.0-SNAPSHOT"|| 0 // numeric parts are equal+ "1.1.0-SNAPSHOT"| "1.0.0" || 1 // 1.1 > 1.0+ "2.0-beta" | "1.9" || 1 // 2 > 1+ "1.0-alpha" | "1.0-beta" || 0 // both parse to 1.0+ }++ def "compareVersions should handle empty segments"() {+ expect:+ VersionInfo.compareVersions("1..0", "1.0.0") == 0+ VersionInfo.compareVersions("1.0.", "1.0.0") == 0+ }++ def "compareVersions should throw NullPointerException for null inputs"() {+ when:+ VersionInfo.compareVersions(null, "1.0.0")++ then:+ thrown(NullPointerException)++ when:+ VersionInfo.compareVersions("1.0.0", null)++ then:+ thrown(NullPointerException)+ }++ def "isVersionGreater should work correctly"() {+ expect:+ VersionInfo.isVersionGreater("2.0.0", "1.0.0") == true+ VersionInfo.isVersionGreater("1.0.0", "2.0.0") == false+ VersionInfo.isVersionGreater("1.0.0", "1.0.0") == false+ }++ def "isVersionGreaterOrEqual should work correctly"() {+ expect:+ VersionInfo.isVersionGreaterOrEqual("2.0.0", "1.0.0") == true+ VersionInfo.isVersionGreaterOrEqual("1.0.0", "1.0.0") == true+ VersionInfo.isVersionGreaterOrEqual("1.0.0", "2.0.0") == false+ }++ def "isVersionEqual should work correctly"() {+ expect:+ VersionInfo.isVersionEqual("1.0.0", "1.0.0") == true+ VersionInfo.isVersionEqual("1.0", "1.0.0") == true+ VersionInfo.isVersionEqual("1.0.0", "1.0.1") == false+ }++ def "isVersionLess should work correctly"() {+ expect:+ VersionInfo.isVersionLess("1.0.0", "2.0.0") == true+ VersionInfo.isVersionLess("2.0.0", "1.0.0") == false+ VersionInfo.isVersionLess("1.0.0", "1.0.0") == false+ }++ def "isVersionLessOrEqual should work correctly"() {+ expect:+ VersionInfo.isVersionLessOrEqual("1.0.0", "2.0.0") == true+ VersionInfo.isVersionLessOrEqual("1.0.0", "1.0.0") == true+ VersionInfo.isVersionLessOrEqual("2.0.0", "1.0.0") == false+ }++ def "parsePart should handle various formats"() {+ expect:+ VersionInfo.parsePart("123") == 123+ VersionInfo.parsePart("1-SNAPSHOT") == 1+ VersionInfo.parsePart("42-alpha") == 42+ VersionInfo.parsePart("0") == 0+ VersionInfo.parsePart("") == 0+ VersionInfo.parsePart("beta") == 0+ }+}+