]> git.basschouten.com Git - openhab-addons.git/commitdiff
Fix Java 17 compilation and test issues (#12353)
authorWouter Born <github@maindrain.net>
Wed, 23 Feb 2022 15:13:56 +0000 (16:13 +0100)
committerGitHub <noreply@github.com>
Wed, 23 Feb 2022 15:13:56 +0000 (16:13 +0100)
* Adds --add-opens to the surefire-maven-plugin config required for deserialization using Gson/XStream
* Upgrades plugin dependencies to JDK 17 compatible versions
* Replaces some reflection that no longer works on JDK 17
* Fixes issues when mocking Random
* Run Nashorn dependant tests only on JDK < 15

Signed-off-by: Wouter Born <github@maindrain.net>
bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/config/servlet/CreateBridgeServlet.java
bundles/org.openhab.binding.mielecloud/src/test/java/org/openhab/binding/mielecloud/internal/webservice/sse/ExponentialBackoffWithJitterTest.java
bundles/org.openhab.binding.netatmo/pom.xml
bundles/org.openhab.binding.tr064/pom.xml
bundles/org.openhab.io.hueemulation/src/test/java/org/openhab/io/hueemulation/internal/rest/ScheduleTests.java
bundles/org.openhab.transform.javascript/src/test/java/org/openhab/transform/javascript/internal/JavaScriptTransformationServiceTest.java
itests/org.openhab.binding.mielecloud.tests/src/main/java/org/openhab/binding/mielecloud/internal/config/ConfigFlowTest.java
itests/org.openhab.binding.mielecloud.tests/src/main/java/org/openhab/binding/mielecloud/internal/util/ReflectionUtil.java
pom.xml

index 1097f3cdaa90c4f8174b2689edb128bb6b11047a..fe8dc9c98839416b915863b0158798c86bd42680 100644 (file)
@@ -53,7 +53,6 @@ public final class CreateBridgeServlet extends AbstractRedirectionServlet {
 
     private static final String DEFAULT_LOCALE = "en";
 
-    private static final long ONLINE_WAIT_TIMEOUT_IN_MILLISECONDS = 5000;
     private static final long DISCOVERY_COMPLETION_TIMEOUT_IN_MILLISECONDS = 5000;
     private static final long CHECK_INTERVAL_IN_MILLISECONDS = 100;
 
@@ -62,6 +61,8 @@ public final class CreateBridgeServlet extends AbstractRedirectionServlet {
     private final Inbox inbox;
     private final ThingRegistry thingRegistry;
 
+    private long onlineWaitTimeoutInMilliseconds = 5000;
+
     /**
      * Creates a new {@link CreateBridgeServlet}.
      *
@@ -73,6 +74,10 @@ public final class CreateBridgeServlet extends AbstractRedirectionServlet {
         this.thingRegistry = thingRegistry;
     }
 
+    public void setOnlineWaitTimeoutInMilliseconds(long onlineWaitTimeoutInMilliseconds) {
+        this.onlineWaitTimeoutInMilliseconds = onlineWaitTimeoutInMilliseconds;
+    }
+
     @Override
     protected String getRedirectionDestination(HttpServletRequest request) {
         String bridgeUidString = request.getParameter(BRIDGE_UID_PARAMETER_NAME);
@@ -175,7 +180,7 @@ public final class CreateBridgeServlet extends AbstractRedirectionServlet {
     private void waitForBridgeToComeOnline(Thing bridge) {
         try {
             waitForConditionWithTimeout(() -> bridge.getStatus() == ThingStatus.ONLINE,
-                    ONLINE_WAIT_TIMEOUT_IN_MILLISECONDS);
+                    onlineWaitTimeoutInMilliseconds);
             waitForConditionWithTimeout(new DiscoveryResultCountDoesNotChangeCondition(),
                     DISCOVERY_COMPLETION_TIMEOUT_IN_MILLISECONDS);
         } catch (InterruptedException e) {
index e1c6dbbf12e2a7b9769fdba70db2018a45637cbe..b40ae5b7526c74caa79819ca5a889619a17e7f12 100644 (file)
@@ -75,7 +75,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenTheNumberOfFailedAttemptsIsNegativeThenZeroIsAssumedInstead() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(RETRY_INTERVAL);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -91,7 +91,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenThereIsNoFailedAttemptThenTheMaximalResultIsMinimumWaitTimePlusRetryInterval() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(RETRY_INTERVAL);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -107,7 +107,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenThereIsOneFailedAttemptThenTheMaximalResultIsMinimumWaitTimePlusTwiceTheRetryInterval() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(RETRY_INTERVAL * 2);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -123,7 +123,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenThereAreTwoFailedAttemptsThenTheMaximalResultIsMinimumWaitTimePlusFourTimesTheRetryInterval() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(RETRY_INTERVAL * 4);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -139,7 +139,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenThereAreTwoFailedAttemptsThenTheMinimalResultIsTheMinimumWaitTime() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(0L);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -155,7 +155,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenTheDrawnRandomValueIsNegativeThenItIsProjectedToAPositiveValue() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(-RETRY_INTERVAL * 4 - 1);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(MINIMUM_WAIT_TIME,
@@ -171,7 +171,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenTheResultWouldBeLargerThanTheMaximumThenItIsCappedToTheMaximum() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(MAXIMUM_WAIT_TIME - ALTERNATIVE_MINIMUM_WAIT_TIME);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(ALTERNATIVE_MINIMUM_WAIT_TIME,
@@ -187,7 +187,7 @@ public class ExponentialBackoffWithJitterTest {
     @Test
     public void whenTheResultWouldBeLargerThanTheAlternativeMaximumThenItIsCappedToTheAlternativeMaximum() {
         // given:
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         when(random.nextLong()).thenReturn(ALTERNATIVE_MAXIMUM_WAIT_TIME - ALTERNATIVE_MINIMUM_WAIT_TIME);
 
         ExponentialBackoffWithJitter backoffStrategy = new ExponentialBackoffWithJitter(ALTERNATIVE_MINIMUM_WAIT_TIME,
index 621b9739ab981ce56fcd3e8523d93a21d3d8c558..0c0e870cf407dfa063313aab2dfa0ed7f057f028 100644 (file)
             </configuration>
           </execution>
         </executions>
+        <dependencies>
+          <dependency>
+            <!-- Required for JDK 17 compatibility, see: https://github.com/swagger-api/swagger-codegen/issues/11253 -->
+            <groupId>com.github.jknack</groupId>
+            <artifactId>handlebars</artifactId>
+            <version>4.3.0</version>
+          </dependency>
+        </dependencies>
       </plugin>
     </plugins>
   </build>
index 4e1a040008ccf47f67a5e6ebaea287f96e71e810..e27bd7feb3a8e59ee16b4954955f8a875a5c2a15 100644 (file)
             </plugin>
           </plugins>
         </configuration>
+        <dependencies>
+          <dependency>
+            <!-- Required for JDK 17 compatibility, see: https://github.com/highsource/maven-jaxb2-plugin/issues/207 -->
+            <groupId>org.glassfish.jaxb</groupId>
+            <artifactId>jaxb-runtime</artifactId>
+            <version>2.3.6</version>
+          </dependency>
+        </dependencies>
       </plugin>
     </plugins>
   </build>
index f7eda550288d6ecf8cdd2bf118af8e9504f43d59..1d153cdef02b4d9cd355d8bc120966e48df23cd2 100644 (file)
@@ -89,7 +89,7 @@ public class ScheduleTests {
         commonSetup.start(new ResourceConfig().registerInstances(subject));
 
         // Mock random -> always return int=10 or the highest possible int if bounded
-        Random random = mock(Random.class);
+        Random random = mock(Random.class, withSettings().withoutAnnotations());
         doReturn(10).when(random).nextInt();
         doAnswer(a -> {
             Integer bound = a.getArgument(0);
index 7189ee6eb2b94dca1c0f7fcdfd64d7cb2d8f7a42..9bd40c29a9455a773942b42aaceed6f394a5e7da 100644 (file)
@@ -13,6 +13,7 @@
 package org.openhab.transform.javascript.internal;
 
 import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
 
 import java.io.File;
 import java.io.IOException;
@@ -40,6 +41,8 @@ import org.osgi.framework.BundleContext;
 @MockitoSettings(strictness = Strictness.WARN)
 public class JavaScriptTransformationServiceTest {
 
+    private static final boolean NASHORN_AVAILABLE = isNashornAvailable();
+
     private static final String BASE_FOLDER = "target";
     private static final String SRC_FOLDER = "conf";
     private static final String CONFIG_FOLDER = BASE_FOLDER + File.separator + SRC_FOLDER;
@@ -54,8 +57,25 @@ public class JavaScriptTransformationServiceTest {
         }
     };
 
+    /**
+     * Returns if the Nashorn JavaScript engine is available based on the Java specification version property.
+     * Nashorn has been removed from JDK 15 and onwards.
+     *
+     * @return {@code true} if Nashorn is available, {@code false} otherwise
+     */
+    private static boolean isNashornAvailable() {
+        try {
+            String javaVersion = System.getProperty("java.specification.version");
+            return javaVersion == null ? false : Long.parseLong(javaVersion) < 15;
+        } catch (NumberFormatException e) {
+            return false;
+        }
+    }
+
     @BeforeEach
     public void setUp() throws IOException {
+        assumeTrue(NASHORN_AVAILABLE);
+
         JavaScriptEngineManager manager = new JavaScriptEngineManager();
         processor = new TestableJavaScriptTransformationService(manager);
         copyDirectory(SRC_FOLDER, CONFIG_FOLDER);
@@ -63,8 +83,11 @@ public class JavaScriptTransformationServiceTest {
 
     @AfterEach
     public void tearDown() throws IOException {
-        try (Stream<Path> walk = Files.walk(Path.of(CONFIG_FOLDER))) {
-            walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
+        Path path = Path.of(CONFIG_FOLDER);
+        if (Files.exists(path)) {
+            try (Stream<Path> walk = Files.walk(path)) {
+                walk.sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
+            }
         }
     }
 
index 17fee8441be5827047086b20cf90352b70388462..1d21bafb6ceca10905d51e07e4e2c8c6a48234a2 100644 (file)
@@ -27,7 +27,6 @@ import org.openhab.binding.mielecloud.internal.handler.MieleBridgeHandler;
 import org.openhab.binding.mielecloud.internal.handler.MieleHandlerFactory;
 import org.openhab.binding.mielecloud.internal.util.AbstractConfigFlowTest;
 import org.openhab.binding.mielecloud.internal.util.MieleCloudBindingIntegrationTestConstants;
-import org.openhab.binding.mielecloud.internal.util.ReflectionUtil;
 import org.openhab.binding.mielecloud.internal.util.Website;
 import org.openhab.binding.mielecloud.internal.util.WebsiteCrawler;
 import org.openhab.binding.mielecloud.internal.webservice.MieleWebservice;
@@ -124,7 +123,7 @@ public class ConfigFlowTest extends AbstractConfigFlowTest {
     public void configFlowWaitTimeoutExpiresWhenBridgeDoesNotComeOnline() throws Exception {
         // given:
         setUpAuthorizationHandler();
-        ReflectionUtil.setPrivateStaticFinal(CreateBridgeServlet.class, "ONLINE_WAIT_TIMEOUT_IN_MILLISECONDS", 0);
+        getCreateBridgeServlet().setOnlineWaitTimeoutInMilliseconds(0);
 
         // when:
         configureBridgeWithConfigFlow();
index ffc6dba2d13549fb17b76a98e636da2ad8eb9e75..efc5929d9ceb84abf9e0ec6ade75c2f03dcf3f3b 100644 (file)
@@ -15,7 +15,6 @@ package org.openhab.binding.mielecloud.internal.util;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
 
 import org.eclipse.jdt.annotation.NonNullByDefault;
 import org.eclipse.jdt.annotation.Nullable;
@@ -80,29 +79,6 @@ public final class ReflectionUtil {
         field.set(object, value);
     }
 
-    /**
-     * Sets an attribute declared as {@code private static final}.
-     *
-     * @param clazz The class owning the static attribute.
-     * @param fieldName The name of the attribute.
-     * @param value The new value.
-     * @throws NoSuchFieldException if no field with the given name exists.
-     * @throws SecurityException if the operation is not allowed.
-     * @throws IllegalArgumentException if one of the passed parameters is invalid.
-     * @throws IllegalAccessException if the field is enforcing Java language access control and is inaccessible.
-     */
-    public static void setPrivateStaticFinal(Class<?> clazz, String fieldName, @Nullable Object value)
-            throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
-        Field field = clazz.getDeclaredField(fieldName);
-        field.setAccessible(true);
-
-        Field modifiersField = Field.class.getDeclaredField("modifiers");
-        modifiersField.setAccessible(true);
-        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
-
-        field.set(null, value);
-    }
-
     /**
      * Invokes a private method on an object.
      *
diff --git a/pom.xml b/pom.xml
index a51a6353a5aee9945fa411fdd513daf03d9598d5..299cf0cd22b44adf478a54e0ee2d5433c6678804 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -385,6 +385,10 @@ Import-Package: \\
           <artifactId>maven-surefire-plugin</artifactId>
           <version>3.0.0-M5</version>
           <configuration>
+            <argLine>
+              --add-opens java.base/java.lang=ALL-UNNAMED
+              --add-opens java.base/java.util=ALL-UNNAMED
+            </argLine>
             <systemPropertyVariables>
               <junit.jupiter.execution.timeout.default>15 m</junit.jupiter.execution.timeout.default>
             </systemPropertyVariables>