diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/AbortedException/AbortedExceptionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/AbortedException/AbortedExceptionTests.java index d0afed82..960362aa 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/AbortedException/AbortedExceptionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/AbortedException/AbortedExceptionTests.java @@ -29,10 +29,9 @@ import ee.jakarta.tck.concurrent.framework.junit.anno.Web; import jakarta.enterprise.concurrent.AbortedException; -@Web //TODO couldn't this be a unit test? +@Web // TODO couldn't this be a unit test? public class AbortedExceptionTests { - // TODO deploy as EJB and JSP artifacts @Deployment(name = "AbortedExceptionTests") public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class).addPackages(true, AbortedExceptionTests.class.getPackage()); @@ -112,41 +111,41 @@ public void AbortedExceptionThrowableTest() { @Test public void AbortedExceptionStringThrowableTest() { AbortedException thrown; - + String sExpected = "thisisthedetailmessage"; String sExpectedNull = null; final Throwable tExpected = new Throwable("thisisthethrowable"); final Throwable tExpectedNull = null; - + thrown = assertThrows(AbortedException.class, () -> { throw new AbortedException(sExpected, tExpected); }); - + assertNotNull(thrown.getMessage()); assertNotNull(thrown.getCause()); assertEquals(sExpected, thrown.getMessage()); assertEquals(tExpected, thrown.getCause()); - + thrown = assertThrows(AbortedException.class, () -> { throw new AbortedException(sExpected, tExpectedNull); }); - + assertNotNull(thrown.getMessage()); assertNull(thrown.getCause()); assertEquals(sExpected, thrown.getMessage()); - + thrown = assertThrows(AbortedException.class, () -> { throw new AbortedException(sExpectedNull, tExpected); }); - + assertNull(thrown.getMessage()); assertNotNull(thrown.getCause()); assertEquals(tExpected, thrown.getCause()); - + thrown = assertThrows(AbortedException.class, () -> { throw new AbortedException(sExpectedNull, tExpectedNull); }); - + assertNull(thrown.getMessage()); assertNull(thrown.getCause()); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/ContextServiceTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/ContextServiceTests.java index d2701c95..7c944bf7 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/ContextServiceTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/ContextServiceTests.java @@ -16,6 +16,10 @@ package ee.jakarta.tck.concurrent.api.ContextService; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; @@ -26,366 +30,294 @@ import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.jupiter.api.Test; +import ee.jakarta.tck.concurrent.common.fixed.counter.CounterRunnableTask; +import ee.jakarta.tck.concurrent.common.fixed.counter.WorkInterface; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestLogger; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ContextService; import jakarta.enterprise.concurrent.ManagedTaskListener; @Web +@Common( { PACKAGE.FIXED_COUNTER } ) public class ContextServiceTests { - private static final TestLogger log = TestLogger.get(ContextServiceTests.class); - - //TODO deploy as EJB and JSP artifacts - @Deployment(name="ContextServiceTests") - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class) - .addPackages(true, ContextServiceTests.class.getPackage()); - } - + // TODO deploy as EJB and JSP artifacts + @Deployment(name = "ContextServiceTests") + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class); + } + @Resource(lookup = TestConstants.DefaultContextService) public ContextService context; - /* - * @testName: ContextServiceWithIntf - * - * @assertion_ids: CONCURRENCY:JAVADOC:5 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using instance and interface. - */ - @Test - public void ContextServiceWithIntf() { - boolean pass = false; - try { - Runnable proxy = (Runnable) context.createContextualProxy(new TestRunnableWork(), Runnable.class); - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } - - /* - * @testName: ContextServiceWithIntfAndIntfNoImplemented - * - * @assertion_ids: CONCURRENCY:JAVADOC:6 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using instance and interface. if the instance does not implement the - * specified interface, IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithIntfAndIntfNoImplemented() { - boolean pass = false; - try { - Object proxy = context.createContextualProxy(new Object(), Runnable.class); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntf + * + * @assertion_ids: CONCURRENCY:JAVADOC:5 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using instance and interface. + */ + @Test + public void ContextServiceWithIntf() { + assertAll(() -> { + Runnable proxy = (Runnable) context.createContextualProxy(new CounterRunnableTask(), Runnable.class); + assertNotNull(proxy); + }); + } - /* - * @testName: ContextServiceWithIntfAndInstanceIsNull - * - * @assertion_ids: CONCURRENCY:JAVADOC:6 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using instance and interface. if the instance is null, - * IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithIntfAndInstanceIsNull() { - boolean pass = false; - try { - Object proxy = context.createContextualProxy(null, Runnable.class); - log.info(proxy.toString()); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntfAndIntfNoImplemented + * + * @assertion_ids: CONCURRENCY:JAVADOC:6 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using instance and interface. if the instance does not implement the + * specified interface, IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithIntfAndIntfNoImplemented() { + assertThrows(IllegalArgumentException.class, () -> { + context.createContextualProxy(new Object(), Runnable.class); + }); + } - /* - * @testName: ContextServiceWithMultiIntfs - * - * @assertion_ids: CONCURRENCY:JAVADOC:7 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using instance and multiple interfaces. - */ - @Test - public void ContextServiceWithMultiIntfs() { - boolean pass = false; - try { - Object proxy = context.createContextualProxy(new TestRunnableWork(), Runnable.class, TestWorkInterface.class); - pass = proxy instanceof Runnable && proxy instanceof TestWorkInterface; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntfAndInstanceIsNull + * + * @assertion_ids: CONCURRENCY:JAVADOC:6 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using instance and interface. if the instance is null, + * IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithIntfAndInstanceIsNull() { + assertThrows(IllegalArgumentException.class, () -> { + context.createContextualProxy(null, Runnable.class); + }); + } - /* - * @testName: ContextServiceWithMultiIntfsAndIntfNoImplemented - * - * @assertion_ids: CONCURRENCY:JAVADOC:8 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using instance and multi interfaces. if the instance does not implement the - * specified interface, IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithMultiIntfsAndIntfNoImplemented() { - boolean pass = false; - try { - Object proxy = context.createContextualProxy(new TestRunnableWork(), Runnable.class, TestWorkInterface.class, - ManagedTaskListener.class); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithMultiIntfs + * + * @assertion_ids: CONCURRENCY:JAVADOC:7 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using instance and multiple interfaces. + */ + @Test + public void ContextServiceWithMultiIntfs() { + assertAll(() -> { + Object proxy = context.createContextualProxy(new CounterRunnableTask(), Runnable.class, + WorkInterface.class); + assertNotNull(proxy); + assertTrue(proxy instanceof Runnable); + assertTrue(proxy instanceof WorkInterface); + }); + } - /* - * @testName: ContextServiceWithMultiIntfsAndInstanceIsNull - * - * @assertion_ids: CONCURRENCY:JAVADOC:8 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using object and multi interfaces. if the instance is null, - * IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithMultiIntfsAndInstanceIsNull() { - boolean pass = false; - try { - Object proxy = context.createContextualProxy(null, Runnable.class, TestWorkInterface.class); - log.info(proxy.toString()); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithMultiIntfsAndIntfNoImplemented + * + * @assertion_ids: CONCURRENCY:JAVADOC:8 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using instance and multi interfaces. if the instance does not implement the + * specified interface, IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithMultiIntfsAndIntfNoImplemented() { + assertThrows(IllegalArgumentException.class, () -> { + context.createContextualProxy(new CounterRunnableTask(), Runnable.class, WorkInterface.class, + ManagedTaskListener.class); + }); + } - /* - * @testName: ContextServiceWithIntfAndProperties - * - * @assertion_ids: CONCURRENCY:JAVADOC:9 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and interface. - */ - @Test - public void ContextServiceWithIntfAndProperties() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + /* + * @testName: ContextServiceWithMultiIntfsAndInstanceIsNull + * + * @assertion_ids: CONCURRENCY:JAVADOC:8 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using object and multi interfaces. if the instance is null, + * IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithMultiIntfsAndInstanceIsNull() { + assertThrows(IllegalArgumentException.class, () -> { + context.createContextualProxy(null, Runnable.class, WorkInterface.class); + }); + } - Runnable proxy = (Runnable) context.createContextualProxy(new TestRunnableWork(), execProps, Runnable.class); - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntfAndProperties + * + * @assertion_ids: CONCURRENCY:JAVADOC:9 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and interface. + */ + @Test + public void ContextServiceWithIntfAndProperties() { + assertAll(() -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: ContextServiceWithMultiIntfsAndProperties - * - * @assertion_ids: CONCURRENCY:JAVADOC:11 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and multiple interfaces. - */ - @Test - public void ContextServiceWithMultiIntfsAndProperties() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + Runnable proxy = (Runnable) context.createContextualProxy(new CounterRunnableTask(), execProps, + Runnable.class); + assertNotNull(proxy); + }); + } - Object proxy = context.createContextualProxy(new TestRunnableWork(), execProps, Runnable.class, - TestWorkInterface.class); - pass = proxy instanceof Runnable && proxy instanceof TestWorkInterface; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithMultiIntfsAndProperties + * + * @assertion_ids: CONCURRENCY:JAVADOC:11 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and multiple interfaces. + */ + @Test + public void ContextServiceWithMultiIntfsAndProperties() { + assertAll(() -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: ContextServiceWithIntfAndPropertiesAndIntfNoImplemented - * - * @assertion_ids: CONCURRENCY:JAVADOC:10 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and interface. if the instance does not implement - * the specified interface, IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithIntfAndPropertiesAndIntfNoImplemented() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + Object proxy = context.createContextualProxy(new CounterRunnableTask(), execProps, Runnable.class, + WorkInterface.class); + assertNotNull(proxy); + assertTrue(proxy instanceof Runnable); + assertTrue(proxy instanceof WorkInterface); + }); + } - Object proxy = context.createContextualProxy(new TestRunnableWork(), execProps, Runnable.class, - ManagedTaskListener.class); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntfAndPropertiesAndIntfNoImplemented + * + * @assertion_ids: CONCURRENCY:JAVADOC:10 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and interface. if the instance does not implement + * the specified interface, IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithIntfAndPropertiesAndIntfNoImplemented() { + assertThrows(IllegalArgumentException.class, () -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: ContextServiceWithIntfsAndPropertiesAndInstanceIsNull - * - * @assertion_ids: CONCURRENCY:JAVADOC:10 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and interfaces. if the instance is null, - * IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithIntfsAndPropertiesAndInstanceIsNull() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + context.createContextualProxy(new CounterRunnableTask(), execProps, Runnable.class, ManagedTaskListener.class); + }); + } - Object proxy = context.createContextualProxy(null, execProps, Runnable.class); - log.info(proxy.toString()); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithIntfsAndPropertiesAndInstanceIsNull + * + * @assertion_ids: CONCURRENCY:JAVADOC:10 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and interfaces. if the instance is null, + * IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithIntfsAndPropertiesAndInstanceIsNull() { + assertThrows(IllegalArgumentException.class, () -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: ContextServiceWithMultiIntfsAndPropertiesAndIntfNoImplemented - * - * @assertion_ids: CONCURRENCY:JAVADOC:12 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and multiple interfaces. if the instance does not - * implement the specified interface, IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithMultiIntfsAndPropertiesAndIntfNoImplemented() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + context.createContextualProxy(null, execProps, Runnable.class); + }); + } - Object proxy = context.createContextualProxy(new TestRunnableWork(), execProps, Runnable.class, - TestWorkInterface.class, ManagedTaskListener.class); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithMultiIntfsAndPropertiesAndIntfNoImplemented + * + * @assertion_ids: CONCURRENCY:JAVADOC:12 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and multiple interfaces. if the instance does not + * implement the specified interface, IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithMultiIntfsAndPropertiesAndIntfNoImplemented() { + assertThrows(IllegalArgumentException.class, () -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: ContextServiceWithMultiIntfsAndPropertiesAndInstanceIsNull - * - * @assertion_ids: CONCURRENCY:JAVADOC:12 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and multiple interfaces. if the instance is null, - * IllegalArgumentException will be thrown - */ - @Test - public void ContextServiceWithMultiIntfsAndPropertiesAndInstanceIsNull() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("vendor_a.security.tokenexpiration", "15000"); - execProps.put("USE_PARENT_TRANSACTION", "true"); + context.createContextualProxy(new CounterRunnableTask(), execProps, Runnable.class, WorkInterface.class, + ManagedTaskListener.class); + }); + } - Object proxy = context.createContextualProxy(null, execProps, Runnable.class, TestWorkInterface.class); - log.info(proxy.toString()); - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + /* + * @testName: ContextServiceWithMultiIntfsAndPropertiesAndInstanceIsNull + * + * @assertion_ids: CONCURRENCY:JAVADOC:12 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and multiple interfaces. if the instance is null, + * IllegalArgumentException will be thrown + */ + @Test + public void ContextServiceWithMultiIntfsAndPropertiesAndInstanceIsNull() { + assertThrows(IllegalArgumentException.class, () -> { + Map execProps = new HashMap(); + execProps.put("vendor_a.security.tokenexpiration", "15000"); + execProps.put("USE_PARENT_TRANSACTION", "true"); - /* - * @testName: GetExecutionProperties - * - * @assertion_ids: CONCURRENCY:JAVADOC:13 - * - * @test_Strategy: Lookup default ContextService object and create proxy object - * using ExecutionProperties and multiple interfaces. Retrieve - * ExecutionProperties from proxy object and verify property value. - */ - @Test - public void GetExecutionProperties() { - boolean pass = false; - try { - Map execProps = new HashMap(); - execProps.put("USE_PARENT_TRANSACTION", "true"); + context.createContextualProxy(null, execProps, Runnable.class, CounterRunnableTask.class); + }); + } - Object proxy = context.createContextualProxy(new TestRunnableWork(), execProps, Runnable.class, - TestWorkInterface.class); - Map returnedExecProps = context.getExecutionProperties(proxy); + /* + * @testName: GetExecutionProperties + * + * @assertion_ids: CONCURRENCY:JAVADOC:13 + * + * @test_Strategy: Lookup default ContextService object and create proxy object + * using ExecutionProperties and multiple interfaces. Retrieve + * ExecutionProperties from proxy object and verify property value. + */ + @Test + public void GetExecutionProperties() { + assertAll(() -> { + Map execProps = new HashMap(); + execProps.put("USE_PARENT_TRANSACTION", "true"); - if (!"true".equals(returnedExecProps.get("USE_PARENT_TRANSACTION"))) { - log.severe("Expected:true, actual message=" + returnedExecProps.get("USE_PARENT_TRANSACTION")); - } else { - pass = true; - } - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } + Object proxy = context.createContextualProxy(new CounterRunnableTask(), execProps, Runnable.class, + WorkInterface.class); + assertNotNull(proxy); + + Map returnedExecProps = context.getExecutionProperties(proxy); + assertEquals("true", returnedExecProps.get("USE_PARENT_TRANSACTION")); + }); + } - /* - * @testName: GetExecutionPropertiesNoProxy - * - * @assertion_ids: CONCURRENCY:JAVADOC:14 - * - * @test_Strategy: Lookup default ContextService object. Retrieve - * ExecutionProperties from plain object. - */ - @Test - public void GetExecutionPropertiesNoProxy() { - boolean pass = false; - try { - Map returnedExecProps = context.getExecutionProperties(new Object()); - pass = true; - } catch (IllegalArgumentException ie) { - pass = true; - } catch (Exception e) { - log.severe("Unexpected Exception Caught", e); - } - assertTrue(pass); - } -} + /* + * @testName: GetExecutionPropertiesNoProxy + * + * @assertion_ids: CONCURRENCY:JAVADOC:14 + * + * @test_Strategy: Lookup default ContextService object. Retrieve + * ExecutionProperties from plain object. + */ + @Test + public void GetExecutionPropertiesNoProxy() { + assertAll(() -> { + try { + context.getExecutionProperties(new Object()); + } catch (IllegalArgumentException ie) { + // Pass if IAE is thrown, but fail otherwise. + } + }); + } +} \ No newline at end of file diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWork.java deleted file mode 100644 index cf119c36..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWork.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.api.ContextService; - -public class TestRunnableWork implements Runnable, TestWorkInterface { - - public void run() { - - } - - public String doSomeWork() { - return "pass"; - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWorkNoDefaultConstructor.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWorkNoDefaultConstructor.java deleted file mode 100644 index c1e412d4..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestRunnableWorkNoDefaultConstructor.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.api.ContextService; - -public class TestRunnableWorkNoDefaultConstructor implements Runnable, TestWorkInterface { - - private TestRunnableWorkNoDefaultConstructor(String s) { - - } - - public static TestRunnableWorkNoDefaultConstructor getInstance() { - return new TestRunnableWorkNoDefaultConstructor("test"); - } - - @Override - public void run() { - } - - @Override - public String doSomeWork() { - return null; - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestWorkInterface.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestWorkInterface.java deleted file mode 100644 index 4b008094..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ContextService/TestWorkInterface.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.api.ContextService; - -public interface TestWorkInterface { - public String doSomeWork(); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/LastExecution/LastExecutionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/LastExecution/LastExecutionTests.java index 5852356c..d8dfe4d2 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/LastExecution/LastExecutionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/LastExecution/LastExecutionTests.java @@ -32,11 +32,11 @@ import ee.jakarta.tck.concurrent.common.fixed.counter.CounterRunnableTask; import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.TestName; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutors; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; @@ -48,7 +48,6 @@ public class LastExecutionTests { public static final String IDENTITY_NAME_TEST_ID = "lastExecutionGetIdentityNameTest"; - //TODO deploy as EJB and JSP artifacts @Deployment(name="LastExecutionTests") public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class) @@ -81,10 +80,10 @@ public void lastExecutionGetIdentityNameTest() { Map executionProperties = new HashMap(); executionProperties.put(ManagedTask.IDENTITY_NAME, IDENTITY_NAME_TEST_ID); - ScheduledFuture sf = scheduledExecutor.schedule( + ScheduledFuture sf = scheduledExecutor.schedule( ManagedExecutors.managedTask(new CounterRunnableTask(), executionProperties, null), new LogicDrivenTrigger(TestConstants.PollInterval.toMillis(), testname)); - TestUtil.waitTillFutureIsDone(sf); + Wait.waitTillFutureIsDone(sf); assertEquals( LogicDrivenTrigger.RIGHT_COUNT, // expected StaticCounter.getCount(), // actual @@ -101,10 +100,10 @@ public void lastExecutionGetIdentityNameTest() { @Test public void lastExecutionGetResultRunnableTest() { // test with runnable, LastExecution should return null - ScheduledFuture sf = scheduledExecutor + ScheduledFuture sf = scheduledExecutor .schedule(ManagedExecutors.managedTask(new CounterRunnableTask(), null, null), new LogicDrivenTrigger( TestConstants.PollInterval.toMillis(), testname)); - TestUtil.waitTillFutureIsDone(sf); + Wait.waitTillFutureIsDone(sf); assertEquals( LogicDrivenTrigger.RIGHT_COUNT, // expected @@ -122,9 +121,10 @@ public void lastExecutionGetResultRunnableTest() { @Test public void lastExecutionGetResultCallableTest() { // test with callable, LastExecution should return 1 - ScheduledFuture sf = scheduledExecutor.schedule(ManagedExecutors.managedTask(new CounterCallableTask(), null, null), + ScheduledFuture sf = scheduledExecutor.schedule(ManagedExecutors.managedTask( + new CounterCallableTask(), null, null), new LogicDrivenTrigger(TestConstants.PollInterval.toMillis(), testname)); - TestUtil.waitTillFutureIsDone(sf); + Wait.waitTillFutureIsDone(sf); assertEquals(LogicDrivenTrigger.RIGHT_COUNT, // expected StaticCounter.getCount(), // actual @@ -141,10 +141,10 @@ public void lastExecutionGetResultCallableTest() { */ @Test public void lastExecutionGetRunningTimeTest() { - ScheduledFuture sf = scheduledExecutor.schedule(ManagedExecutors.managedTask( + ScheduledFuture sf = scheduledExecutor.schedule(ManagedExecutors.managedTask( new CounterRunnableTask(TestConstants.PollInterval), null, null), new LogicDrivenTrigger(TestConstants.PollInterval.toMillis(), testname)); - TestUtil.waitTillFutureIsDone(sf); + Wait.waitTillFutureIsDone(sf); assertEquals( LogicDrivenTrigger.RIGHT_COUNT, // expected StaticCounter.getCount(), // actual diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/ManageableThreadTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/ManageableThreadTests.java deleted file mode 100644 index 0253b88a..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/ManageableThreadTests.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.api.ManageableThread; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.jupiter.api.Test; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.junit.anno.Web; -import jakarta.annotation.Resource; -import jakarta.enterprise.concurrent.ManageableThread; -import jakarta.enterprise.concurrent.ManagedThreadFactory; - -@Web -public class ManageableThreadTests { - - private static final TestLogger log = TestLogger.get(ManageableThreadTests.class); - - //TODO deploy as EJB and JSP artifacts - @Deployment(name="ManageableThreadTests") - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class) - .addPackages(true, ManageableThreadTests.class.getPackage()); - } - - @Resource(lookup = TestConstants.DefaultManagedThreadFactory) - public ManagedThreadFactory threadFactory; - - /* - * @testName: isShutdown - * - * @assertion_ids: CONCURRENCY:JAVADOC:20;CONCURRENCY:SPEC:99.1; - * - * @test_Strategy: Lookup default ManagedThreadFactory object and create new - * thread. Check return value of method isShutdown of new thread. - */ - @Test - public void isShutdown() { - boolean pass = false; - try { - ManageableThread m = (ManageableThread) threadFactory.newThread(new TestRunnableWork()); - pass = !m.isShutdown(); - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - assertTrue(pass); - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedExecutors/ManagedExecutorsTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedExecutors/ManagedExecutorsTests.java index 9967b254..52496536 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedExecutors/ManagedExecutorsTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedExecutors/ManagedExecutorsTests.java @@ -16,6 +16,11 @@ package ee.jakarta.tck.concurrent.api.ManagedExecutors; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; @@ -34,10 +39,10 @@ import ee.jakarta.tck.concurrent.common.tasks.RunnableTask; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; import jakarta.enterprise.concurrent.ManagedExecutors; @@ -86,27 +91,26 @@ private CallableTask createCallableTask(String expectedReturnValue) { } private void assertTaskAndListenerComplete(Future future, RunnableTask runnableTask) { - TestUtil.waitForTaskComplete(future); + Wait.waitForTaskComplete(future); assertListenerComplete(runnableTask); } private void assertTaskAndListenerComplete(String expectedResult, Future future, CallableTask callableTask) { - String result = TestUtil.waitForTaskComplete(future); - if (!expectedResult.endsWith(result)) - throw new RuntimeException("Task return different value with expected one."); + String result = Wait.waitForTaskComplete(future); + assertTrue(expectedResult.endsWith(result)); assertListenerComplete(callableTask); } private void assertListenerComplete(RunnableTask task) { // wait for the listener run done. - TestUtil.waitForListenerComplete(managedTaskListener); + Wait.waitForListenerComplete(managedTaskListener); + // check listener status. - if (!(managedTaskListener.eventCalled(ListenerEvent.SUBMITTED) - && managedTaskListener.eventCalled(ListenerEvent.STARTING) - && managedTaskListener.eventCalled(ListenerEvent.DONE))) { - throw new RuntimeException("TaskListener is not completely executed."); - } + assertTrue(managedTaskListener.eventCalled(ListenerEvent.SUBMITTED)); + assertTrue(managedTaskListener.eventCalled(ListenerEvent.STARTING)); + assertTrue(managedTaskListener.eventCalled(ListenerEvent.DONE)); + } /* @@ -130,10 +134,8 @@ public void run() { // to create new thread. So the thread used in this test is a non Manageable // Thread. Future future = Executors.newSingleThreadExecutor().submit(createdThread); - TestUtil.waitForTaskComplete(future); - if (shutdown) { - throw new RuntimeException("Failed because shutdown is set to be true when running job"); - } + Wait.waitForTaskComplete(future); + assertFalse(shutdown, "Failed because shutdown is set to be true when running job"); } /* @@ -156,10 +158,8 @@ public void run() { // ManagedThreadFactory // to create new (Manageable) thread. Future future = Executors.newSingleThreadExecutor(threadFactory).submit(createdThread); - TestUtil.waitForTaskComplete(future); - if (shutdown) { - throw new RuntimeException("Failed because shutdown is set to be true when running job"); - } + Wait.waitForTaskComplete(future); + assertFalse(shutdown, "Failed because shutdown is set to be true when running job"); } /* @@ -193,15 +193,9 @@ public void ManageRunnableTaskWithTaskListener() { @Test public void ManageRunnableTaskWithNullArg() { Runnable nullTask = null; - try { + assertThrows(IllegalArgumentException.class, () -> { ManagedExecutors.managedTask(nullTask, managedTaskListener); - } catch (IllegalArgumentException e) { - return; // expected - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - - throw new RuntimeException("Failed to get expected exception"); + }); } /* @@ -220,12 +214,11 @@ public void ManageRunnableTaskWithTaskListenerAndMap() { properties.put("key", "value"); RunnableTask runnableTask = createRunnableTask(); Runnable task = ManagedExecutors.managedTask(runnableTask, properties, managedTaskListener); - boolean pass = false; - if (task instanceof ManagedTask) { - ManagedTask managedTask = (ManagedTask) task; - if (managedTask.getExecutionProperties().get("key") != "value") - throw new RuntimeException("Failed to get expected property"); - } + + assertTrue(task instanceof ManagedTask); + ManagedTask managedTask = (ManagedTask) task; + + assertEquals("value", managedTask.getExecutionProperties().get("key")); assertTaskAndListenerComplete(executor.submit(task), runnableTask); } @@ -242,14 +235,10 @@ public void ManageRunnableTaskWithTaskListenerAndMap() { public void ManageRunnableTaskWithMapAndNullArg() { Runnable nullTask = null; Map properties = new HashMap(); - try { + + assertThrows(IllegalArgumentException.class, () -> { ManagedExecutors.managedTask(nullTask, properties, managedTaskListener); - } catch (IllegalArgumentException e) { - return; // expected - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - throw new RuntimeException("Failed to get expected exception"); + }); } /* @@ -283,14 +272,9 @@ public void ManageCallableTaskWithTaskListener() { @Test public void ManageCallableTaskWithNullArg() { Callable nullTask = null; - try { + assertThrows(IllegalArgumentException.class, () -> { ManagedExecutors.managedTask(nullTask, managedTaskListener); - } catch (IllegalArgumentException e) { - return; // expected - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - throw new RuntimeException("Failed to get expected exception"); + }); } /* @@ -314,13 +298,13 @@ public void ManageCallableTaskWithTaskListenerAndMap() { CallableTask callableTask = createCallableTask(expectedResultStr); Callable task = ManagedExecutors.managedTask((Callable) callableTask, properties, managedTaskListener); + + assertTrue(task instanceof ManagedTask); + + ManagedTask managedTask = (ManagedTask) task; + + assertEquals("value", managedTask.getExecutionProperties().get("key")); - boolean pass = false; - if (task instanceof ManagedTask) { - ManagedTask managedTask = (ManagedTask) task; - if (managedTask.getExecutionProperties().get("key") != "value") - throw new RuntimeException("Failed to get expected property"); - } assertTaskAndListenerComplete(expectedResultStr, executor.submit(task), callableTask); } @@ -337,13 +321,9 @@ public void ManageCallableTaskWithTaskListenerAndMap() { public void ManageCallableTaskWithMapAndNullArg() { Callable nullTask = null; Map properties = new HashMap(); - try { + + assertThrows(IllegalArgumentException.class, () -> { ManagedExecutors.managedTask(nullTask, properties, managedTaskListener); - } catch (IllegalArgumentException e) { - return; // expected - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - throw new RuntimeException("Failed to get expected exception"); + }); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedScheduledExecutorService/ManagedScheduledExecutorServiceTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedScheduledExecutorService/ManagedScheduledExecutorServiceTests.java index 243cb4fd..4183b739 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedScheduledExecutorService/ManagedScheduledExecutorServiceTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedScheduledExecutorService/ManagedScheduledExecutorServiceTests.java @@ -16,6 +16,10 @@ package ee.jakarta.tck.concurrent.api.ManagedScheduledExecutorService; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.concurrent.Callable; import java.util.concurrent.ScheduledFuture; @@ -28,10 +32,10 @@ import ee.jakarta.tck.concurrent.common.tasks.CommonTriggers; import ee.jakarta.tck.concurrent.common.tasks.RunnableTask; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; @@ -70,15 +74,11 @@ public static WebArchive createDeployment() { */ @Test public void normalScheduleProcess1Test() throws Exception { - ScheduledFuture result = scheduledExecutor.schedule( + ScheduledFuture result = scheduledExecutor.schedule( new RunnableTask(TEST_JNDI_EVN_ENTRY_JNDI_NAME, TEST_JNDI_EVN_ENTRY_VALUE, TEST_CLASSLOADER_CLASS_NAME), new CommonTriggers.OnceTrigger()); - TestUtil.waitForTaskComplete(result); - - Object obj = result.get(); - if (obj != null) { - throw new RuntimeException("expected null, instead got result: " + obj.toString()); - } + Wait.waitForTaskComplete(result); + assertNull(result.get()); } /* @@ -91,14 +91,10 @@ public void normalScheduleProcess1Test() throws Exception { @Test public void nullCommandScheduleProcessTest() { Runnable command = null; - - try { + + assertThrows(NullPointerException.class, () -> { scheduledExecutor.schedule(command, new CommonTriggers.OnceTrigger()); - } catch (NullPointerException e) { - return; // expected - } - - throw new RuntimeException("NullPointerException should be thrown when arg command is null"); + }); } /* @@ -114,20 +110,14 @@ public void nullCommandScheduleProcessTest() { */ @Test public void normalScheduleProcess2Test() throws Exception { - ScheduledFuture result = scheduledExecutor - .schedule( - (Callable) new CallableTask(TEST_JNDI_EVN_ENTRY_JNDI_NAME, TEST_JNDI_EVN_ENTRY_VALUE, + ScheduledFuture result = scheduledExecutor.schedule( (Callable) + new CallableTask(TEST_JNDI_EVN_ENTRY_JNDI_NAME, TEST_JNDI_EVN_ENTRY_VALUE, TEST_CLASSLOADER_CLASS_NAME, CALLABLETESTTASK1_RUN_RESULT), new CommonTriggers.OnceTrigger()); - TestUtil.waitForTaskComplete(result); + Wait.waitForTaskComplete(result); + + assertEquals(CALLABLETESTTASK1_RUN_RESULT, result.get()); - Object obj = result.get(); - - if (CALLABLETESTTASK1_RUN_RESULT.equals(obj)) { - return; - } else { - throw new RuntimeException("get wrong result:" + obj); - } } /* @@ -139,15 +129,11 @@ public void normalScheduleProcess2Test() throws Exception { */ @Test public void nullCallableScheduleProcessTest() { - Callable callable = null; - - try { + Callable callable = null; + + assertThrows(NullPointerException.class, () -> { scheduledExecutor.schedule(callable, new CommonTriggers.OnceTrigger()); - } catch (NullPointerException e) { - return; // expected - } - - throw new RuntimeException("NullPointerException should be thrown when arg command is null"); + }); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTask/ManagedTaskTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTask/ManagedTaskTests.java index ee28a356..dfa3ef65 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTask/ManagedTaskTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTask/ManagedTaskTests.java @@ -16,6 +16,7 @@ package ee.jakarta.tck.concurrent.api.ManagedTask; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashMap; @@ -67,13 +68,12 @@ public void GetExecutionProperties() { properties.put("key", "value"); Runnable runnableTask = createRunnableTask(); Runnable task = ManagedExecutors.managedTask(runnableTask, properties, managedTaskListener); - boolean pass = false; - - if (task instanceof ManagedTask) { - ManagedTask managedTask = (ManagedTask) task; - assertTrue(managedTask.getExecutionProperties().get("key") == "value", "failed to get expected property"); - } + assertTrue(task instanceof ManagedTask); + + ManagedTask managedTask = (ManagedTask) task; + + assertEquals("value", managedTask.getExecutionProperties().get("key")); } /* @@ -90,10 +90,11 @@ public void GetManagedTaskListener() { properties.put("key", "value"); RunnableTask runnableTask = createRunnableTask(); Runnable task = ManagedExecutors.managedTask(runnableTask, properties, managedTaskListener); + + assertTrue(task instanceof ManagedTask); + + ManagedTask managedTask = (ManagedTask) task; + assertEquals(managedTaskListener, managedTask.getManagedTaskListener()); - if (task instanceof ManagedTask) { - ManagedTask managedTask = (ManagedTask) task; - assertTrue(managedTask.getManagedTaskListener() == managedTaskListener, "Failed to get expected managedTaskListener"); - } } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/ManagedTaskListenerTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/ManagedTaskListenerTests.java index 2db7c9ad..3632dafb 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/ManagedTaskListenerTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/ManagedTaskListenerTests.java @@ -32,12 +32,13 @@ import ee.jakarta.tck.concurrent.common.managed.task.listener.ListenerEvent; import ee.jakarta.tck.concurrent.common.managed.task.listener.ManagedTaskListenerImpl; +import ee.jakarta.tck.concurrent.common.managed.task.listener.RunnableTaskWithStatus; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; import jakarta.enterprise.concurrent.ManagedExecutors; @@ -77,15 +78,16 @@ public void cleanup() { */ @Test public void TaskAborted() throws InterruptedException { - int blockTime = 3000;// (ms) + final Duration blockTime = Duration.ofMillis(3000); Runnable runnableTask = new RunnableTaskWithStatus(managedTaskListener, blockTime); Runnable taskWithListener = ManagedExecutors.managedTask(runnableTask, managedTaskListener); Future futureResult = executor.submit(taskWithListener); - TestUtil.sleep(Duration.ofMillis(1000)); + Wait.sleep(Duration.ofMillis(1000)); futureResult.cancel(true); - TestUtil.waitForListenerComplete(managedTaskListener, blockTime + TestConstants.WaitTimeout.toMillis(), - TestConstants.PollInterval.toMillis()); + Wait.waitForListenerComplete(managedTaskListener, TestConstants.WaitTimeout.plus(blockTime), + TestConstants.PollInterval); List events = managedTaskListener.events(); + assertTrue(events.contains(ListenerEvent.ABORTED), "Listener taskAborted failed"); assertTrue(futureResult.isCancelled(), "Listener taskAborted failed"); } @@ -102,14 +104,14 @@ public void TaskAborted() throws InterruptedException { @Test public void TaskDone() throws InterruptedException { // in cancel case - final int blockTime = 3000;// (ms) + final Duration blockTime = Duration.ofMillis(3000); Runnable taskToCancelled = new RunnableTaskWithStatus(managedTaskListener, blockTime); Runnable taskToCancelledWithListener = ManagedExecutors.managedTask(taskToCancelled, managedTaskListener); Future futureResult = executor.submit(taskToCancelledWithListener); - TestUtil.sleep(Duration.ofMillis(1000)); + Wait.sleep(Duration.ofMillis(1000)); futureResult.cancel(true); - TestUtil.waitForListenerComplete(managedTaskListener, blockTime + TestConstants.WaitTimeout.toMillis(), - TestConstants.PollInterval.toMillis()); + Wait.waitForListenerComplete(managedTaskListener, TestConstants.WaitTimeout.plus(blockTime), + TestConstants.PollInterval); List events = managedTaskListener.events(); assertTrue(events.contains(ListenerEvent.DONE), "Listener taskDone failed in cancel case"); managedTaskListener.clearEvents(); @@ -118,7 +120,7 @@ public void TaskDone() throws InterruptedException { Runnable runTask = new RunnableTaskWithStatus(managedTaskListener); Runnable runtaskWithListener = ManagedExecutors.managedTask(runTask, managedTaskListener); executor.submit(runtaskWithListener); - TestUtil.waitForListenerComplete(managedTaskListener); + Wait.waitForListenerComplete(managedTaskListener); List runevents = managedTaskListener.events(); assertTrue(runevents.contains(ListenerEvent.DONE), "Listener TaskDone failed"); managedTaskListener.clearEvents(); @@ -127,7 +129,7 @@ public void TaskDone() throws InterruptedException { Runnable taskWithException = new RunnableTaskWithException(managedTaskListener); Runnable taskWithExceptionListener = ManagedExecutors.managedTask(taskWithException, managedTaskListener); executor.submit(taskWithExceptionListener); - TestUtil.waitForListenerComplete(managedTaskListener); + Wait.waitForListenerComplete(managedTaskListener); List runeventsWithException = managedTaskListener.events(); log.fine("++ runeventsWithException : " + runeventsWithException); assertTrue(runeventsWithException.contains(ListenerEvent.DONE), @@ -150,7 +152,7 @@ public void TaskStarting() { Runnable runnableTask = new RunnableTaskWithStatus(managedTaskListener); Runnable taskWithListener = ManagedExecutors.managedTask(runnableTask, managedTaskListener); executor.submit(taskWithListener); - TestUtil.waitForListenerComplete(managedTaskListener); + Wait.waitForListenerComplete(managedTaskListener); List events = managedTaskListener.events(); int submitAt = events.indexOf(ListenerEvent.SUBMITTED); int startAt = events.indexOf(ListenerEvent.STARTING); @@ -176,7 +178,7 @@ public void TaskSubmitted() { Runnable runnableTask = new RunnableTaskWithStatus(managedTaskListener); Runnable taskWithListener = ManagedExecutors.managedTask(runnableTask, managedTaskListener); executor.submit(taskWithListener); - TestUtil.waitForListenerComplete(managedTaskListener); + Wait.waitForListenerComplete(managedTaskListener); List events = managedTaskListener.events(); int submitAt = events.indexOf(ListenerEvent.SUBMITTED); assertEquals(0, submitAt, "Listener TaskSubmitted failed to run in expected order"); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithException.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithException.java index 5fdd337c..883b587b 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithException.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithException.java @@ -18,12 +18,12 @@ import ee.jakarta.tck.concurrent.common.managed.task.listener.ListenerEvent; import ee.jakarta.tck.concurrent.common.managed.task.listener.ManagedTaskListenerImpl; +import ee.jakarta.tck.concurrent.common.managed.task.listener.RunnableTaskWithStatus; -public class RunnableTaskWithException implements Runnable { - private final ManagedTaskListenerImpl listener; +public class RunnableTaskWithException extends RunnableTaskWithStatus implements Runnable { public RunnableTaskWithException(ManagedTaskListenerImpl listener) { - this.listener = listener; + super(listener); } @Override diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/apitests/APITests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedThreadFactory/ManagedThreadFactoryTests.java similarity index 78% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/apitests/APITests.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedThreadFactory/ManagedThreadFactoryTests.java index 9e15e097..68cf16a8 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/apitests/APITests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedThreadFactory/ManagedThreadFactoryTests.java @@ -14,9 +14,10 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.apitests; +package ee.jakarta.tck.concurrent.api.ManagedThreadFactory; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.jboss.arquillian.container.test.api.Deployment; @@ -28,27 +29,41 @@ import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; import ee.jakarta.tck.concurrent.framework.TestClient; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManageableThread; import jakarta.enterprise.concurrent.ManagedThreadFactory; @Web @Common({PACKAGE.TASKS, PACKAGE.FIXED_COUNTER}) -public class APITests extends TestClient { +public class ManagedThreadFactoryTests extends TestClient { @Deployment(name="APITests") public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class) - .addPackages(true, APITests.class.getPackage()); + .addPackages(true, ManagedThreadFactoryTests.class.getPackage()); } @Resource(lookup = TestConstants.DefaultManagedThreadFactory) public ManagedThreadFactory threadFactory; + + /* + * @testName: isShutdown + * + * @assertion_ids: CONCURRENCY:JAVADOC:20;CONCURRENCY:SPEC:99.1; + * + * @test_Strategy: Lookup default ManagedThreadFactory object and create new + * thread. Check return value of method isShutdown of new thread. + */ + @Test + public void isShutdown() { + ManageableThread m = (ManageableThread) threadFactory.newThread(new CounterRunnableTask()); + assertFalse(m.isShutdown()); + } /* @@ -67,7 +82,7 @@ public void interruptThreadApiTest() { Thread thread = threadFactory.newThread(task); thread.start(); thread.interrupt(); - TestUtil.waitTillThreadFinish(thread); + Wait.waitTillThreadFinish(thread); assertEquals(0, StaticCounter.getCount()); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/SkippedException/SkippedExceptionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/SkippedException/SkippedExceptionTests.java index d976cc71..18e78553 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/SkippedException/SkippedExceptionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/SkippedException/SkippedExceptionTests.java @@ -16,21 +16,21 @@ package ee.jakarta.tck.concurrent.api.SkippedException; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.jupiter.api.Test; -import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; import jakarta.enterprise.concurrent.SkippedException; -@Web +@Web // TODO couldn't this be a unit test? public class SkippedExceptionTests { - - private static final TestLogger log = TestLogger.get(SkippedExceptionTests.class); //TODO deploy as EJB and JSP artifacts @Deployment(name="SkippedExceptionTests") @@ -48,21 +48,11 @@ public static WebArchive createDeployment() { */ @Test public void SkippedExceptionNoArgTest() { - boolean pass = false; - try { - throw new SkippedException(); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - if (se.getMessage() == null) { - log.info("Received expected null message"); - pass = true; - } else { - log.warning("SkippedException should have had null message, actual message=" + se.getMessage()); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - assertTrue(pass); + SkippedException thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(); + }); + + assertNull(thrown.getMessage()); } /* @@ -74,22 +64,14 @@ public void SkippedExceptionNoArgTest() { */ @Test public void SkippedExceptionStringTest() { - boolean pass = false; - String expected = "thisisthedetailmessage"; - try { - throw new SkippedException(expected); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - if (se.getMessage().equals(expected)) { - log.info("Received expected message"); - pass = true; - } else { - log.info("Expected:" + expected + ", actual message=" + se.getMessage()); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - assertTrue(pass); + final String expected = "thisisthedetailmessage"; + + SkippedException thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(expected); + }); + + assertNotNull(thrown.getMessage()); + assertEquals(expected, thrown.getMessage()); } /* @@ -101,41 +83,24 @@ public void SkippedExceptionStringTest() { */ @Test public void SkippedExceptionThrowableTest() { - boolean pass1 = false; - boolean pass2 = false; - Throwable expected = new Throwable("thisisthethrowable"); - try { - throw new SkippedException(expected); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - Throwable cause = se.getCause(); - if (cause.equals(expected)) { - log.info("Received expected cause"); - pass1 = true; - } else { - log.info("Expected:" + expected + ", actual message=" + cause); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - - expected = null; - try { - throw new SkippedException(expected); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - Throwable cause = se.getCause(); - if (cause == null) { - log.info("Received expected null cause"); - pass2 = true; - } else { - log.info("Expected:null, actual message=" + cause); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - assertTrue(pass1); - assertTrue(pass2); + SkippedException thrown; + + final Throwable expected = new Throwable("thisisthethrowable"); + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(expected); + }); + + assertNotNull(thrown.getCause()); + assertEquals(expected, thrown.getCause()); + + final Throwable expectedNull = null; + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(expectedNull); + }); + + assertNull(thrown.getCause()); } /* @@ -147,57 +112,43 @@ public void SkippedExceptionThrowableTest() { */ @Test public void SkippedExceptionStringThrowableTest() { - boolean pass1 = false; - boolean pass2 = false; - boolean pass3 = false; - boolean pass4 = false; - String sExpected = "thisisthedetailmessage"; - Throwable tExpected = new Throwable("thisisthethrowable"); - try { - throw new SkippedException(sExpected, tExpected); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - if (se.getMessage().equals(sExpected)) { - log.info("Received expected message"); - pass1 = true; - } else { - log.info("Expected:" + sExpected + ", actual message=" + se.getMessage()); - } - Throwable cause = se.getCause(); - if (cause.equals(tExpected)) { - log.info("Received expected cause"); - pass2 = true; - } else { - log.info("Expected:" + tExpected + ", actual message=" + cause); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - - tExpected = null; - try { - throw new SkippedException(sExpected, tExpected); - } catch (SkippedException se) { - log.info("SkippedException Caught as Expected"); - if (se.getMessage().equals(sExpected)) { - log.info("Received expected message"); - pass3 = true; - } else { - log.info("Expected:" + sExpected + ", actual message=" + se.getMessage()); - } - Throwable cause = se.getCause(); - if (cause == null) { - log.info("Received expected null cause"); - pass4 = true; - } else { - log.info("Expected:null, actual message=" + cause); - } - } catch (Exception e) { - log.warning("Unexpected Exception Caught", e); - } - assertTrue(pass1); - assertTrue(pass2); - assertTrue(pass3); - assertTrue(pass4); + SkippedException thrown; + + String sExpected = "thisisthedetailmessage"; + String sExpectedNull = null; + final Throwable tExpected = new Throwable("thisisthethrowable"); + final Throwable tExpectedNull = null; + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(sExpected, tExpected); + }); + + assertNotNull(thrown.getMessage()); + assertNotNull(thrown.getCause()); + assertEquals(sExpected, thrown.getMessage()); + assertEquals(tExpected, thrown.getCause()); + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(sExpected, tExpectedNull); + }); + + assertNotNull(thrown.getMessage()); + assertNull(thrown.getCause()); + assertEquals(sExpected, thrown.getMessage()); + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(sExpectedNull, tExpected); + }); + + assertNull(thrown.getMessage()); + assertNotNull(thrown.getCause()); + assertEquals(tExpected, thrown.getCause()); + + thrown = assertThrows(SkippedException.class, () -> { + throw new SkippedException(sExpectedNull, tExpectedNull); + }); + + assertNull(thrown.getMessage()); + assertNull(thrown.getCause()); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/Trigger/TriggerTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/api/Trigger/TriggerTests.java index 7488b6c1..94edd1b4 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/Trigger/TriggerTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/api/Trigger/TriggerTests.java @@ -16,15 +16,11 @@ package ee.jakarta.tck.concurrent.api.Trigger; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.assertFalse; import java.util.Date; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; @@ -35,108 +31,82 @@ import ee.jakarta.tck.concurrent.common.fixed.counter.CounterRunnableTask; import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; +import ee.jakarta.tck.concurrent.common.tasks.CommonTasks; import ee.jakarta.tck.concurrent.common.tasks.CommonTriggers; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Assertions; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; import jakarta.enterprise.concurrent.SkippedException; @Web -@Common({PACKAGE.FIXED_COUNTER, PACKAGE.TASKS}) +@Common({ PACKAGE.FIXED_COUNTER, PACKAGE.TASKS }) public class TriggerTests { - - //TODO deploy as EJB and JSP artifacts - @Deployment(name="TriggerTests") - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class) - .addPackages(true, TriggerTests.class.getPackage()); - } - - @Resource(lookup = TestConstants.DefaultManagedScheduledExecutorService) - public ManagedScheduledExecutorService scheduledExecutor; - @BeforeEach - public void reset() { - StaticCounter.reset(); - } - - /* - * @testName: triggerGetNextRunTimeTest - * - * @assertion_ids: CONCURRENCY:JAVADOC:46 - * - * @test_Strategy: Retrieve the next time that the task should run after. - * fix: https://github.com/jakartaee/concurrency/pull/222 - * Accepted TCK challenge: https://github.com/jakartaee/concurrency/issues/228 - * Can be reenabled in next release of Jakarta Concurrency - */ - @Disabled - public void triggerGetNextRunTimeTest() throws Exception { - ScheduledFuture sf = scheduledExecutor.schedule(new CounterRunnableTask(), - new CommonTriggers.TriggerFixedRate(new Date(), TestConstants.PollInterval.toMillis())); + // TODO deploy as EJB and JSP artifacts + @Deployment(name = "TriggerTests") + public static WebArchive createDeployment() { + return ShrinkWrap.create(WebArchive.class).addPackages(true, TriggerTests.class.getPackage()); + } - try { - if (StaticCounter.getCount() != 0) { - throw new RuntimeException("The first trigger is too fast."); - } + @Resource(lookup = TestConstants.DefaultManagedScheduledExecutorService) + public ManagedScheduledExecutorService scheduledExecutor; - TestUtil.sleep(TestConstants.WaitTimeout); - int result = StaticCounter.getCount(); - assertInRange(result, TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2); - } finally { - // make sure the task schedule by this case is stop - try { - TestUtil.sleep(TestConstants.WaitTimeout.multipliedBy(2)); - } catch (InterruptedException ignore) { - } - } - } + @BeforeEach + public void reset() { + StaticCounter.reset(); + } - /* - * @testName: triggerSkipRunTest - * - * @assertion_ids: CONCURRENCY:JAVADOC:47 - * - * @test_Strategy: Return true if this run instance should be skipped. This is - * useful if the task shouldn't run because it is late or if the task is paused - * or suspended. Once this task is skipped, the state of it's Future's result - * will throw a SkippedException. Unchecked exceptions will be wrapped in a - * SkippedException. - */ - @Test - public void triggerSkipRunTest() { - ScheduledFuture sf = scheduledExecutor.schedule(new Callable() { - public Object call() { - return "ok"; - } - }, new CommonTriggers.OnceTriggerDelaySkip(TestConstants.PollInterval.toMillis())); + /* + * @testName: triggerGetNextRunTimeTest + * + * @assertion_ids: CONCURRENCY:JAVADOC:46 + * + * @test_Strategy: Retrieve the next time that the task should run after. fix: + * https://github.com/jakartaee/concurrency/pull/222 Accepted TCK challenge: + * https://github.com/jakartaee/concurrency/issues/228 Can be reenabled in next + * release of Jakarta Concurrency + */ + @Disabled + public void triggerGetNextRunTimeTest() throws Exception { + Future result = scheduledExecutor.schedule(new CounterRunnableTask(), + new CommonTriggers.TriggerFixedRate(new Date(), TestConstants.PollInterval.toMillis())); + + assertFalse(StaticCounter.getCount() == 0, "The first trigger is too fast."); - long start = System.currentTimeMillis(); - try { - while (!sf.isDone()) { - try { - sf.get(100, TimeUnit.MILLISECONDS); - } catch (SkippedException se) { - return; - } catch (ExecutionException ee) { - } catch (TimeoutException | InterruptedException e) { - } - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - fail("wait task timeout"); - } - } - } finally { - sf.cancel(true); - } + try { + Wait.sleep(TestConstants.WaitTimeout); + Assertions.assertBetween(StaticCounter.getCount(), TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2); + } finally { + Wait.waitTillFutureIsDone(result); + } + } - fail("SkippedException should be caught."); - } - - private void assertInRange(int value, int min, int max) { - assertTrue(value > min && value < max, "Expected " + value + " to be in the exclusive range ( " + min + " - " + max + " )"); + /* + * @testName: triggerSkipRunTest + * + * @assertion_ids: CONCURRENCY:JAVADOC:47 + * + * @test_Strategy: Return true if this run instance should be skipped. This is + * useful if the task shouldn't run because it is late or if the task is paused + * or suspended. Once this task is skipped, the state of it's Future's result + * will throw a SkippedException. Unchecked exceptions will be wrapped in a + * SkippedException. + */ + @Test + public void triggerSkipRunTest() { + ScheduledFuture sf = scheduledExecutor.schedule( + new CommonTasks.SimpleCallable(), + new CommonTriggers.OnceTriggerDelaySkip(TestConstants.PollInterval)); + + try { + Wait.waitTillFutureThrowsException(sf, SkippedException.class); + } finally { + sf.cancel(true); + } } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterCallableTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterCallableTask.java index a8fb24d8..b4c3a8af 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterCallableTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterCallableTask.java @@ -20,7 +20,7 @@ import javax.naming.InitialContext; -public class CounterCallableTask implements Callable { +public class CounterCallableTask implements Callable { private String countSingletionJndi = ""; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterRunnableTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterRunnableTask.java index 7e97eb45..9c0c55b7 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterRunnableTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/counter/CounterRunnableTask.java @@ -20,26 +20,26 @@ import javax.naming.InitialContext; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; public class CounterRunnableTask implements Runnable { private String countSingletionJndi = ""; - private long sleepTime = 0; + private Duration sleepTime = Duration.ZERO; public CounterRunnableTask(String countSingletionJndi) { this.countSingletionJndi = countSingletionJndi; } - public CounterRunnableTask(String countSingletionJndi, long sleepTime) { + public CounterRunnableTask(String countSingletionJndi, Duration sleepTime) { this.countSingletionJndi = countSingletionJndi; this.sleepTime = sleepTime; } public void run() { try { - if (sleepTime > 0) { - TestUtil.sleep(Duration.ofMillis(sleepTime)); + if (! sleepTime.isZero()) { + Wait.sleep(sleepTime); } CounterInterface counter = InitialContext.doLookup(countSingletionJndi); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterCallableTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterCallableTask.java index fe8b520a..2c709611 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterCallableTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterCallableTask.java @@ -18,11 +18,12 @@ import java.util.concurrent.Callable; -public class CounterCallableTask implements Callable { +public class CounterCallableTask implements Callable, WorkInterface { - public Integer call() { - StaticCounter.inc(); - return StaticCounter.getCount(); - } + @Override + public Integer call() { + StaticCounter.inc(); + return StaticCounter.getCount(); + } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterRunnableTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterRunnableTask.java index 85e26d55..1f2a761d 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterRunnableTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/CounterRunnableTask.java @@ -18,26 +18,26 @@ import java.time.Duration; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; -public class CounterRunnableTask implements Runnable { - private Duration sleepTime = Duration.ZERO; +public class CounterRunnableTask implements Runnable, WorkInterface { + private Duration sleepTime = Duration.ZERO; - public CounterRunnableTask() { - } - - public CounterRunnableTask(Duration sleepTime) { + public CounterRunnableTask() { + } + + public CounterRunnableTask(Duration sleepTime) { this.sleepTime = sleepTime; } - public void run() { - try { - if (! sleepTime.isZero()) { - TestUtil.sleep(sleepTime); - } - StaticCounter.inc(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + public void run() { + try { + if (!sleepTime.isZero()) { + Wait.sleep(sleepTime); + } + StaticCounter.inc(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/StaticCounter.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/StaticCounter.java index 02ea1485..38df7536 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/StaticCounter.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/StaticCounter.java @@ -16,20 +16,39 @@ package ee.jakarta.tck.concurrent.common.fixed.counter; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.util.concurrent.atomic.AtomicInteger; + +import ee.jakarta.tck.concurrent.framework.TestConstants; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; + public class StaticCounter { - private static int count = 0; + private static AtomicInteger count = new AtomicInteger(0); - public static synchronized int getCount() { - return count; - } + public static int getCount() { + return count.get(); + } - public static synchronized void inc() { - count++; - } + public static void inc() { + count.incrementAndGet(); + } - public static synchronized void reset() { - count = 0; - } + public static void reset() { + count.set(0); + } + + public static void waitTill(int expected) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; expected != StaticCounter.getCount(); Wait.sleep(TestConstants.PollInterval)); + }); + } + + public static void waitTillSurpassed(int expected) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; expected <= StaticCounter.getCount(); Wait.sleep(TestConstants.PollInterval)); + }); + } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/WorkInterface.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/WorkInterface.java new file mode 100644 index 00000000..0dd70a03 --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/fixed/counter/WorkInterface.java @@ -0,0 +1,5 @@ +package ee.jakarta.tck.concurrent.common.fixed.counter; + +public interface WorkInterface { + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithStatus.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/managed/task/listener/RunnableTaskWithStatus.java similarity index 64% rename from tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithStatus.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/common/managed/task/listener/RunnableTaskWithStatus.java index 56c816dc..a4d2c198 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManagedTaskListener/RunnableTaskWithStatus.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/managed/task/listener/RunnableTaskWithStatus.java @@ -14,35 +14,32 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.api.ManagedTaskListener; +package ee.jakarta.tck.concurrent.common.managed.task.listener; -import java.util.concurrent.TimeUnit; +import java.time.Duration; -import ee.jakarta.tck.concurrent.common.managed.task.listener.ListenerEvent; -import ee.jakarta.tck.concurrent.common.managed.task.listener.ManagedTaskListenerImpl; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; public class RunnableTaskWithStatus implements Runnable { - private final ManagedTaskListenerImpl listener; - - private final int blockTime; + + protected final ManagedTaskListenerImpl listener; + + private final Duration blockTime; public RunnableTaskWithStatus(ManagedTaskListenerImpl listener) { this.listener = listener; - blockTime = 0; + blockTime = Duration.ZERO; } - RunnableTaskWithStatus(ManagedTaskListenerImpl listener, int blockTime) { + public RunnableTaskWithStatus(ManagedTaskListenerImpl listener, Duration blockTime) { this.listener = listener; this.blockTime = blockTime; } public void run() { listener.update(ListenerEvent.TASK_RUN); - if (blockTime > 0) { - try { - TimeUnit.SECONDS.sleep(blockTime); - } catch (InterruptedException e) { - } + if (! blockTime.isZero()) { + Wait.sleep(blockTime); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ApiCheckDriver.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ApiCheckDriver.java index 289869a7..a89a9cdc 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ApiCheckDriver.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ApiCheckDriver.java @@ -30,7 +30,9 @@ public final class ApiCheckDriver extends SignatureTestDriver implements Serializable { - /* flags for the Diff utility argument list */ + private static final long serialVersionUID = 1L; + + /* flags for the Diff utility argument list */ private static final String BASE_FLAG = "-base"; private static final String TEST_FLAG = "-test"; @@ -56,15 +58,15 @@ protected String normalizeFileName(File f) { protected String[] createTestArguments(String packageListFile, String mapFile, String signatureRepositoryDir, String packageOrClassUnderTest, String classpath, boolean bStaticMode) throws Exception { - Class pkgListClass = Class.forName("javasoft.sqe.apiCheck.PackageList"); - Constructor pkgCtor = pkgListClass.getDeclaredConstructor(new Class[] { String.class }); + Class pkgListClass = Class.forName("javasoft.sqe.apiCheck.PackageList"); + Constructor pkgCtor = pkgListClass.getDeclaredConstructor(new Class[] { String.class }); Object pkgInstance = pkgCtor.newInstance(new Object[] { packageListFile }); Method pkgMethod = pkgListClass.getDeclaredMethod("getSubPackagesFormatted", new Class[] { String.class }); String excludePkgs = (String) pkgMethod.invoke(pkgInstance, new Object[] { packageOrClassUnderTest }); - List sigArgsList = new LinkedList(); + List sigArgsList = new LinkedList<>(); sigArgsList.add(BASE_FLAG); sigArgsList.add(getSigFileInfo(packageOrClassUnderTest, mapFile, signatureRepositoryDir).getFile()); @@ -91,7 +93,7 @@ protected String[] createTestArguments(String packageListFile, String mapFile, S @Override protected boolean runSignatureTest(String packageOrClassName, String[] testArguments) throws Exception { - Class diffClass = Class.forName("javasoft.sqe.apiCheck.Diff"); + Class diffClass = Class.forName("javasoft.sqe.apiCheck.Diff"); Method mainMethod = diffClass.getDeclaredMethod("main", new Class[] { String[].class }); mainMethod.invoke(null, new Object[] { testArguments }); @@ -102,8 +104,8 @@ protected boolean runSignatureTest(String packageOrClassName, String[] testArgum @Override protected boolean runPackageSearch(String packageOrClassName, String[] testArguments) throws Exception { - Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); - Object sigTestInstance = sigTestClass.newInstance(); + Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); + Object sigTestInstance = sigTestClass.getConstructor().newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -120,7 +122,6 @@ protected boolean runPackageSearch(String packageOrClassName, String[] testArgum System.out.println(" testArguments[" + ii + "] = " + testArguments[ii]); } - @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ConcurrencySignatureTestRunner.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ConcurrencySignatureTestRunner.java index e299e68a..901f509d 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ConcurrencySignatureTestRunner.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/ConcurrencySignatureTestRunner.java @@ -208,7 +208,6 @@ public void signatureTest() throws Fault { String mapFile = null; String packageListFile = null; String signatureRepositoryDir = null; - Properties mapFileAsProps = null; try { InputStream inStreamMapfile = ConcurrencySignatureTestRunner.class.getClassLoader() @@ -223,8 +222,6 @@ public void signatureTest() throws Fault { packageListFile = pFile.getCanonicalPath(); log.info("packageFile location is :" + packageListFile); - mapFileAsProps = getSigTestDriver().loadMapFile(mapFile); - InputStream inStreamSigFile = ConcurrencySignatureTestRunner.class.getClassLoader() .getResourceAsStream("ee/jakarta/tck/concurrent/common/signature/" + SIG_FILE_NAME); File sigFile = writeStreamToSigFile(inStreamSigFile); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/PackageList.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/PackageList.java index fad1e46f..64b3ad30 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/PackageList.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/PackageList.java @@ -79,7 +79,7 @@ class PackageList { private String additionalPackageName; // Name of packages and sub-packages in the - private Set packageNames = new TreeSet(); + private Set packageNames = new TreeSet<>(); /** * Creates an instance of the PackageList class. The PackageList instance reads @@ -202,17 +202,17 @@ private boolean isComment(String line) { private void removeExistingPackage() { String delPackage = this.additionalPackageName; String packageName; - List delPkgs = new ArrayList(); + List delPkgs = new ArrayList<>(); // iterate over package set and find package names to remove - for (Iterator i = packageNames.iterator(); i.hasNext();) { - packageName = (String) i.next(); + for (Iterator i = packageNames.iterator(); i.hasNext();) { + packageName = i.next(); if (packageName.startsWith(delPackage)) { delPkgs.add(packageName); } } // actually remove the package names from the set for (int i = 0; i < delPkgs.size(); i++) { - packageName = (String) (delPkgs.get(i)); + packageName = delPkgs.get(i); packageNames.remove(packageName); System.out.println("PackageList.removeExistingPackage() \"" + packageName + "\""); } @@ -336,8 +336,8 @@ private void writePkgFile() throws Exception { try { out = new BufferedWriter(new FileWriter(packageFile)); writeHeader(out); - for (Iterator i = packageNames.iterator(); i.hasNext();) { - String packageName = (String) i.next(); + for (Iterator i = packageNames.iterator(); i.hasNext();) { + String packageName = i.next(); out.write(packageName); out.newLine(); System.out.println("PackageList.writePkgFile() \"" + packageName + "\""); @@ -358,10 +358,10 @@ private void writePkgFile() throws Exception { * package. */ public String[] getSubPackages(String pkgName) { - List result = new ArrayList(); + List result = new ArrayList<>(); String subPackageName = pkgName + "."; - for (Iterator i = packageNames.iterator(); i.hasNext();) { - String packageName = (String) i.next(); + for (Iterator i = packageNames.iterator(); i.hasNext();) { + String packageName = i.next(); if (packageName.startsWith(subPackageName)) { result.add(packageName); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestDriver.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestDriver.java index c9dd3df2..6c1d811c 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestDriver.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestDriver.java @@ -47,14 +47,14 @@ public class SigTestDriver extends SignatureTestDriver { private static final String CHECKVALUE_FLAG = "-CheckValue"; // only valid w/ // -static - private static final String NO_CHECKVALUE_FLAG = "-NoCheckValue"; +// private static final String NO_CHECKVALUE_FLAG = "-NoCheckValue"; private static final String SMODE_FLAG = "-mode"; // requires arg of bin or // src - private static final String DEBUG_FLAG = "-Debug"; +// private static final String DEBUG_FLAG = "-Debug"; - private static final String FORMATPLAIN_FLAG = "-FormatPlain"; +// private static final String FORMATPLAIN_FLAG = "-FormatPlain"; private static final String EXCLUDE_JDK_CLASS_FLAG = "-IgnoreJDKClass"; @@ -100,7 +100,7 @@ protected String[] createTestArguments(String packageListFile, String mapFile, S PackageList packageList = new PackageList(packageListFile); String[] subPackages = packageList.getSubPackages(packageOrClassUnderTest); - List command = new ArrayList(); + List command = new ArrayList<>(); if (bStaticMode) { // static mode allows finer level of constants checking @@ -150,7 +150,7 @@ protected String[] createTestArguments(String packageListFile, String mapFile, S @Override protected boolean runSignatureTest(String packageOrClassName, String[] testArguments) throws Exception { - Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); + Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); Object sigTestInstance = sigTestClass.getConstructor().newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -161,7 +161,6 @@ protected boolean runSignatureTest(String packageOrClassName, String[] testArgum System.out.println(" testArguments[" + ii + "] = " + testArguments[ii]); } - @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); @@ -183,8 +182,8 @@ protected boolean runSignatureTest(String packageOrClassName, String[] testArgum @Override protected boolean runPackageSearch(String packageOrClassName, String[] testArguments) throws Exception { - Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); - Object sigTestInstance = sigTestClass.newInstance(); + Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); + Object sigTestInstance = sigTestClass.getConstructor().newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); @@ -201,7 +200,6 @@ protected boolean runPackageSearch(String packageOrClassName, String[] testArgum System.out.println(" testArguments[" + ii + "] = " + testArguments[ii]); } - @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); @@ -223,8 +221,7 @@ protected boolean runPackageSearch(String packageOrClassName, String[] testArgum protected boolean verifyJTAJarForNoXA(String classpath, String repositoryDir) throws Exception { System.out.println("SigTestDriver#verifyJTAJarForNoXA - Starting:"); - boolean result = false; - List command = new ArrayList(); + List command = new ArrayList<>(); // Build Commandline for com.sun.tdk.signaturetest.SignatureTest command.add(STATIC_FLAG); @@ -243,11 +240,10 @@ protected boolean verifyJTAJarForNoXA(String classpath, String repositoryDir) th System.out.println(" testArguments[" + ii + "] = " + testArguments[ii]); } - Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); - Object sigTestInstance = sigTestClass.newInstance(); + Class sigTestClass = Class.forName("com.sun.tdk.signaturetest.SignatureTest"); + Object sigTestInstance = sigTestClass.getConstructor().newInstance(); ByteArrayOutputStream output = new ByteArrayOutputStream(); - @SuppressWarnings("unchecked") Method runMethod = sigTestClass.getDeclaredMethod("run", new Class[] { String[].class, PrintWriter.class, PrintWriter.class }); runMethod.invoke(sigTestInstance, new Object[] { testArguments, new PrintWriter(output, true), null }); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestEE.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestEE.java index 8d81b110..ce8bf828 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestEE.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestEE.java @@ -34,10 +34,6 @@ public abstract class SigTestEE { String[] sVehicles; - private Object theSharedObject; - - private Object theSharedObjectArray[]; - protected SignatureTestDriver driver; /** diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestResult.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestResult.java index 6152c658..1b462926 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestResult.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/signature/SigTestResult.java @@ -25,15 +25,17 @@ public class SigTestResult implements Serializable { - private static final String NL = System.getProperty("line.separator", "\n"); + private static final long serialVersionUID = 1L; - private List failedPkgs = new ArrayList(); + private static final String NL = System.getProperty("line.separator", "\n"); - private List passedPkgs = new ArrayList(); + private List failedPkgs = new ArrayList<>(); - private List failedClasses = new ArrayList(); + private List passedPkgs = new ArrayList<>(); - private List passedClasses = new ArrayList(); + private List failedClasses = new ArrayList<>(); + + private List passedClasses = new ArrayList<>(); // ---------------------------------------------------------- Public Methods @@ -106,11 +108,11 @@ public String toString() { // --------------------------------------------------------- Private Methods - private synchronized void formatList(List list, StringBuffer buf) { + private synchronized void formatList(List list, StringBuffer buf) { synchronized (this) { for (int i = 0; i < list.size(); i++) { - String pkg = (String) (list.get(i)); + String pkg = list.get(i); buf.append("\t\t").append(pkg).append(NL); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTasks.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTasks.java index e5b83b19..7262269c 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTasks.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTasks.java @@ -20,28 +20,28 @@ import java.util.concurrent.Callable; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; public class CommonTasks { public static final String SIMPLE_RETURN_STRING = "ok"; - public static class SimpleCallable implements Callable { - private long waitTime = 0; + public static class SimpleCallable implements Callable { + private Duration waitTime = Duration.ZERO; public SimpleCallable() { } - public SimpleCallable(long argWaitTime) { - this.waitTime = argWaitTime; + public SimpleCallable(Duration waitTime) { + this.waitTime = waitTime; } public String call() { try { - if (waitTime != 0) { - TestUtil.sleep(Duration.ofMillis(waitTime)); + if (!waitTime.isZero()) { + Wait.sleep(waitTime); } else { - TestUtil.sleep(TestConstants.PollInterval); + Wait.sleep(TestConstants.PollInterval); } } catch (Exception e) { throw new RuntimeException(e); @@ -53,14 +53,14 @@ public String call() { public static class SimpleRunnable implements Runnable { public void run() { try { - TestUtil.sleep(TestConstants.PollInterval); + Wait.sleep(TestConstants.PollInterval); } catch (Exception e) { throw new RuntimeException(e); } } } - public static class SimpleArgCallable implements Callable { + public static class SimpleArgCallable implements Callable { private int value = -1; public SimpleArgCallable(int arg) { @@ -69,7 +69,7 @@ public SimpleArgCallable(int arg) { public Integer call() { try { - TestUtil.sleep(TestConstants.PollInterval); + Wait.sleep(TestConstants.PollInterval); } catch (Exception e) { throw new RuntimeException(e); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTriggers.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTriggers.java index 9973588f..9f62f4b4 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTriggers.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/CommonTriggers.java @@ -16,6 +16,7 @@ package ee.jakarta.tck.concurrent.common.tasks; +import java.time.Duration; import java.util.Date; import ee.jakarta.tck.concurrent.framework.TestConstants; @@ -44,18 +45,18 @@ public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime) { * A trigger that will skip. */ public static class OnceTriggerDelaySkip implements Trigger { + + private Duration delay; - public OnceTriggerDelaySkip(long argDelay) { - delay = argDelay; + public OnceTriggerDelaySkip(Duration delay) { + this.delay = delay; } - private long delay; - public Date getNextRunTime(LastExecution lastExecutionInfo, Date taskScheduledTime) { if (lastExecutionInfo != null) { return null; } - return new Date(new Date().getTime() + delay); + return new Date(new Date().getTime() + delay.toMillis()); } public boolean skipRun(LastExecution lastExecutionInfo, Date scheduledRunTime) { diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/RunnableTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/RunnableTask.java index 6fbca816..499f921c 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/RunnableTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/tasks/RunnableTask.java @@ -18,7 +18,6 @@ import java.util.concurrent.TimeUnit; -import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/CancelledTransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/CancelledTransactedTask.java new file mode 100644 index 00000000..4d6fe4a8 --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/CancelledTransactedTask.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package ee.jakarta.tck.concurrent.common.transaction; + +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.concurrent.atomic.AtomicBoolean; + +import javax.naming.InitialContext; + +import ee.jakarta.tck.concurrent.framework.TestConstants; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; +import jakarta.transaction.UserTransaction; + +public class CancelledTransactedTask implements Runnable { + + public AtomicBoolean runQuery = new AtomicBoolean(false); + + public AtomicBoolean beginTransaction = new AtomicBoolean(false); + + public AtomicBoolean cancelTransaction = new AtomicBoolean(false); + + private final String sqlTemplate; + + public CancelledTransactedTask(String sqlTemplate) { + this.sqlTemplate = sqlTemplate; + } + + private void waitForRun() { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for (; !runQuery.get(); Wait.sleep(TestConstants.PollInterval)) + ; + }); + } + + @Override + public void run() { + try { + UserTransaction ut = InitialContext.doLookup(TestConstants.UserTransaction); + ut.begin(); + beginTransaction.set(true); + waitForRun(); + try (Connection conn = Connections.getConnection(false); + PreparedStatement pStmt = conn.prepareStatement(sqlTemplate);) { + String sTypeDesc = "Type-Cancelled-99"; + int newType = 991; + pStmt.setInt(1, newType); + pStmt.setString(2, sTypeDesc); + pStmt.executeUpdate(); + + // check if it is cancelled here + if (cancelTransaction.get()) { + ut.rollback(); + return; + } + + ut.commit(); + } catch (Exception e) { + try { + ut.rollback(); + } catch (Exception sqle) { + sqle.printStackTrace(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Connections.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Connections.java new file mode 100644 index 00000000..878075ec --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Connections.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ +package ee.jakarta.tck.concurrent.common.transaction; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.sql.DataSource; + +public class Connections { + + private Connections() { + //ignore + } + + private static DataSource ds; + + public static void setDataSource(DataSource ds) { + Connections.ds = ds; + } + + public static void unsetDataSource() { + Connections.ds = null; + } + + public static Connection getConnection(boolean autoCommit) { + Connection conn = null; + try { + conn = ds.getConnection(); // Try without user password for EE case + if (conn == null) { + conn = ds.getConnection(Constants.USERNAME, Constants.PASSWORD); // For standalone cases + } + if (null != conn) { + conn.setAutoCommit(autoCommit); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return conn; + } + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Constants.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Constants.java new file mode 100644 index 00000000..511c1496 --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Constants.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package ee.jakarta.tck.concurrent.common.transaction; + +public class Constants { + + public static final String CONTEXT_PATH = "/TransactionServlet"; + + public static final String PARAM_COMMIT = "isCommit"; + + public static final String COMMIT_TRUE = "isCommit=true"; + + public static final String COMMIT_FALSE = "isCommit=false"; + + public static final String COMMIT_CANCEL = "isCommit=cancel"; + + public static final String TABLE_P = "concurrencetable"; + + public static final String USERNAME = "user1"; + + public static final String PASSWORD = "password1"; + + public static final String SQL_TEMPLATE_DROP = "drop table concurrencetable"; + + public static final String SQL_TEMPLATE_CREATE = "create table concurrencetable (TYPE_ID int NOT NULL, TYPE_DESC varchar(32), primary key(TYPE_ID))"; + + public static final String SQL_TEMPLATE_INSERT = "insert into concurrencetable values(?, ?)"; + + public static final String SQL_TEMPLATE_DELETE = "delete from concurrencetable"; + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Counter.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Counter.java new file mode 100644 index 00000000..e1448aa8 --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/Counter.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ +package ee.jakarta.tck.concurrent.common.transaction; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; + +public class Counter { + + /** + * Get count of rows in test table to verify if a transaction was committed or rolled back. + * + * @return number of rows, or -1 if error occurred while attempting to access table. + */ + public static int getCount() { + try (Connection conn = Connections.getConnection(true);) { + return getCount(conn); + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } + + private static int getCount(Connection conn) { + final String queryStr = "select count(*) from " + Constants.TABLE_P; + + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery(queryStr); + if (rs.next()) { + return rs.getInt(1); + } + } catch (Exception e) { + e.printStackTrace(); + } + + return -1; + } + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/TransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/TransactedTask.java new file mode 100644 index 00000000..a64da77c --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/TransactedTask.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v. 2.0, which is available at + * http://www.eclipse.org/legal/epl-2.0. + * + * This Source Code may also be made available under the following Secondary + * Licenses when the conditions for such availability set forth in the + * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, + * version 2 with the GNU Classpath Exception, which is available at + * https://www.gnu.org/software/classpath/license.html. + * + * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 + */ + +package ee.jakarta.tck.concurrent.common.transaction; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.PreparedStatement; + +import javax.naming.InitialContext; + +import ee.jakarta.tck.concurrent.framework.TestConstants; +import jakarta.transaction.UserTransaction; + +public class TransactedTask implements WorkInterface { + + private static final long serialVersionUID = 1L; + + private final boolean beginTransaction; + + private final boolean isCommit; + + private final String sqlTemplate; + + public TransactedTask(boolean commitOrRollback, boolean beginTransaction, String sqlTemplate) { + this.sqlTemplate = sqlTemplate; + this.beginTransaction = beginTransaction; + this.isCommit = commitOrRollback; + } + + public TransactedTask(boolean commitOrRollback, String sqlTemplate) { + this.sqlTemplate = sqlTemplate; + this.beginTransaction = true; + this.isCommit = commitOrRollback; + } + + @Override + public void run() { + int originCount = Counter.getCount(); + UserTransaction ut = null; + + try { + if (beginTransaction) { + ut = InitialContext.doLookup(TestConstants.UserTransaction); + ut.begin(); + } + try (Connection conn = Connections.getConnection(false); + PreparedStatement pStmt = conn.prepareStatement(sqlTemplate);) { + + String sTypeDesc = "Type-99"; + int newType = 99; + pStmt.setInt(1, newType); + pStmt.setString(2, sTypeDesc); + pStmt.executeUpdate(); + + // commit or roll back transaction. + if (beginTransaction && isCommit) { + ut.commit(); + } + + if (beginTransaction && !isCommit) { + ut.rollback(); + } + + // check status. + int afterTransacted = Counter.getCount(); + + if (isCommit) { + assertEquals(originCount + 1, afterTransacted); + } else { + assertEquals(originCount, afterTransacted); + } + } catch (Exception e) { + try { + ut.rollback(); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void doWork() { + + UserTransaction ut = null; + + try { + if (beginTransaction) { + ut = InitialContext.doLookup(TestConstants.UserTransaction); + ut.begin(); + } + + try (Connection conn = Connections.getConnection(false); + PreparedStatement pStmt = conn.prepareStatement(sqlTemplate);) { + + String sTypeDesc = "Type-98"; + int newType = 98; + pStmt.setInt(1, newType); + pStmt.setString(2, sTypeDesc); + pStmt.executeUpdate(); + + // commit or roll back transaction. + if (beginTransaction && isCommit) { + ut.commit(); + } + + if (beginTransaction && !isCommit) { + ut.rollback(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/TestRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/WorkInterface.java similarity index 73% rename from tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/TestRunnableWork.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/WorkInterface.java index ad80bef4..309d0b41 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/api/ManageableThread/TestRunnableWork.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/common/transaction/WorkInterface.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -14,11 +14,10 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.api.ManageableThread; +package ee.jakarta.tck.concurrent.common.transaction; -public class TestRunnableWork implements Runnable { +import java.io.Serializable; - public void run() { - - } +public interface WorkInterface extends Runnable, Serializable { + public void doWork(); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestClient.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestClient.java index 4c4e2cf8..a9eb1f43 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestClient.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestClient.java @@ -21,9 +21,13 @@ import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.Enumeration; import java.util.Properties; /** @@ -106,7 +110,7 @@ private String assertSuccessfulURLResponse(URL url, Properties props) { if(withProps) { con.setRequestMethod("POST"); try( DataOutputStream wr = new DataOutputStream( con.getOutputStream())){ - wr.writeBytes( TestUtil.toEncodedString(props) ); + wr.writeBytes( toEncodedString(props) ); } } else { @@ -140,6 +144,23 @@ private String assertSuccessfulURLResponse(URL url, Properties props) { } } + static String toEncodedString(Properties args) throws UnsupportedEncodingException { + StringBuffer buf = new StringBuffer(); + Enumeration names = args.propertyNames(); + while (names.hasMoreElements()) { + String name = (String) names.nextElement(); + String value = args.getProperty(name); + + buf.append(URLEncoder.encode(name, StandardCharsets.UTF_8.name())) + .append("=") + .append(URLEncoder.encode(value, StandardCharsets.UTF_8.name())); + + if (names.hasMoreElements()) + buf.append("&"); + } + return buf.toString(); + } + /** * Override this method to return the servlet path for the suite of tests. * Used for the runTest() methods. diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestServlet.java index d864fb23..8ad4b5d8 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestServlet.java @@ -15,10 +15,16 @@ */ package ee.jakarta.tck.concurrent.framework; +import java.io.BufferedReader; +import java.io.DataOutputStream; import java.io.IOException; +import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLConnection; +import java.util.Properties; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; @@ -37,6 +43,8 @@ public class TestServlet extends HttpServlet { private static final TestLogger log = TestLogger.get(TestServlet.class); + public static final String nl = System.lineSeparator(); + private boolean runBeforeClass = true; public static final String SUCCESS = "SUCCESS"; @@ -141,4 +149,54 @@ protected void invokeTest(String method, HttpServletRequest request, HttpServlet + " with any of the following signatures: " + method + "(HttpServletRequest, HttpServletResponse) " + method + "()"); } + + /** + * HTTP convenience method for servlets to get a response from another servlet. + * Test clients should extend the {@link TestClient} class that has its own HTTP methods. + * + * @param con - the URLConnection + * @return String - response body + * @throws IOException + */ + public static String getResponse(URLConnection con) throws IOException { + try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + + StringBuffer response = new StringBuffer(); + + String line; + while ((line = br.readLine()) != null) { + response.append(line).append(nl); + } + + return response.toString(); + } + } + + /** + * HTTP convenience method for servlets to create a URLConnection and post properties + * to that connection. + * + * Test clients should extend the {@link TestClient} class that has its own HTTP methods. + * + * @param url - the URL to open a connection to + * @param props - the properties to put into the connection input stream + * + * @return the connection for further testing + * @throws IOException + */ + public static URLConnection sendPostData(URL url, Properties props) throws IOException { + log.info("Opening url connection to: " + url.toString()); + URLConnection urlConn = url.openConnection(); + // Begin POST of properties to SERVLET + String argString = TestClient.toEncodedString(props); + urlConn.setDoOutput(true); + urlConn.setDoInput(true); + urlConn.setUseCaches(false); + DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); + out.writeBytes(argString); + out.flush(); + out.close(); + // End POST + return urlConn; + } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestUtil.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestUtil.java deleted file mode 100644 index 9de49ca7..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/TestUtil.java +++ /dev/null @@ -1,299 +0,0 @@ -/* - * Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.framework; - -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Enumeration; -import java.util.Properties; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import ee.jakarta.tck.concurrent.common.managed.task.listener.ListenerEvent; -import ee.jakarta.tck.concurrent.common.managed.task.listener.ManagedTaskListenerImpl; - -/** - * Utility methods to be used on the client or server side. - * These utilities can be broken up into distinct categorities: - * - HTTP utilities - * - Context lookup utilities - * - Waiter utilities - * - Assertions - */ -public final class TestUtil { - public static final TestLogger log = TestLogger.get(TestUtil.class); - - public static final String nl = System.lineSeparator(); - - // ########## HTTP ########## - - /** - * HTTP convenience method for servlets to get a response from another servlet. - * Test clients should extend the {@link TestClient} class that has its own HTTP methods. - * - * @param con - the URLConnection - * @return String - response body - * @throws IOException - */ - public static String getResponse(URLConnection con) throws IOException { - try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()))) { - - StringBuffer response = new StringBuffer(); - - String line; - while ((line = br.readLine()) != null) { - response.append(line).append(nl); - } - - return response.toString(); - } - } - - /** - * HTTP convenience method for servlets to create a URLConnection and post properties - * to that connection. - * - * Test clients should extend the {@link TestClient} class that has its own HTTP methods. - * - * @param url - the URL to open a connection to - * @param props - the properties to put into the connection input stream - * - * @return the connection for further testing - * @throws IOException - */ - public static URLConnection sendPostData(URL url, Properties props) throws IOException { - log.info("Opening url connection to: " + url.toString()); - URLConnection urlConn = url.openConnection(); - // Begin POST of properties to SERVLET - String argString = TestUtil.toEncodedString(props); - urlConn.setDoOutput(true); - urlConn.setDoInput(true); - urlConn.setUseCaches(false); - DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); - out.writeBytes(argString); - out.flush(); - out.close(); - // End POST - return urlConn; - } - - static String toEncodedString(Properties args) throws UnsupportedEncodingException { - StringBuffer buf = new StringBuffer(); - Enumeration names = args.propertyNames(); - while (names.hasMoreElements()) { - String name = (String) names.nextElement(); - String value = args.getProperty(name); - - buf.append(URLEncoder.encode(name, StandardCharsets.UTF_8.name())) - .append("=") - .append(URLEncoder.encode(value, StandardCharsets.UTF_8.name())); - - if (names.hasMoreElements()) - buf.append("&"); - } - return buf.toString(); - } - - //########## Waiters ########## - - /** - * USE WITH CAUTION!! - * When possible tests should use waitFor methods to wait for specific condition to be meet. - * Pausing the thread for a specific duration will directly impact test performance but in some cases is required. - * - * Pauses the calling thread for the specified duration - * - * @param duration - duration to sleep - * @throws InterruptedException - */ - public static void sleep(Duration duration) throws InterruptedException { - log.config("Sleeping " + duration.toMillis() + " milliseconds"); - Thread.sleep(duration.toMillis()); - } - - /** - * Waits for task to complete, but will timeout after {@link TestConstants#WaitTimeout} - * @param future to wait for - * @return result - */ - public static T waitForTaskComplete(final Future future) { - return waitForTaskComplete(future, TestConstants.WaitTimeout.toMillis()); - } - - /** - * Waits for task to complete, but will timeout after specified timeout in millis - * @param future - the future to wait for - * @param maxWaitTimeMillis - the timeout - * @return result - */ - public static T waitForTaskComplete(final Future future, final long maxWaitTimeMillis) { - T result = null; - try { - result = future.get(maxWaitTimeMillis, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - throw new RuntimeException("waitForTaskComplete", e); - } catch (ExecutionException e) { - throw new RuntimeException("waitForTaskComplete", e); - } catch (TimeoutException e) { - throw new RuntimeException("failed to finish task in " + maxWaitTimeMillis + " milliseconds. ", e); - } catch (Exception e) { // may caught the exception thrown from the task - // submitted. - throw new RuntimeException("waitForTaskComplete failed to finish task", e); - } - return result; - } - - /** - * Wait for listener to complete, but will timeout after {@link TestConstants#WaitTimeout}, - * and will be polled ever {@link TestConstants#PollInterval} - * - * @param managedTaskListener - the listener to be polled - */ - public static void waitForListenerComplete(ManagedTaskListenerImpl managedTaskListener) { - waitForListenerComplete(managedTaskListener, TestConstants.WaitTimeout.toMillis(), TestConstants.PollInterval.toMillis()); - } - - /** - * Wait for listener to complete, but will timeout after a specified timeout, - * and will be polled ever specified interval - * - * @param managedTaskListener - the listener to be polled - * @param maxWaitTimeMillis - timeout - * @param pollIntervalMillis - poll interval - */ - public static void waitForListenerComplete(ManagedTaskListenerImpl managedTaskListener, long maxWaitTimeMillis, - long pollIntervalMillis) { - final long stopTime = System.currentTimeMillis() + maxWaitTimeMillis; - while (!managedTaskListener.eventCalled(ListenerEvent.DONE) && System.currentTimeMillis() < stopTime) { - try { - Thread.sleep(pollIntervalMillis); - } catch (InterruptedException e) { - throw new RuntimeException("Thread was inerrupted while sleeping", e); - } - } - } - - /** - * Waits for future to complete, but will timeout after {@link TestConstants#WaitTimeout}, - * and will be polled every {@link TestConstants#PollInterval} - * - * The difference between this method and waitForTaskComplete is that some - * scheduled task will return values for multiple times, in this situation - * waitForTaskComplete does not work. - * - * @param future - the future to wait for - */ - public static void waitTillFutureIsDone(Future future) { - long start = System.currentTimeMillis(); - - while (!future.isDone()) { - try { - Thread.sleep(TestConstants.PollInterval.toMillis()); - } catch (InterruptedException ignore) { - } - - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - throw new RuntimeException("Future did not finish before wait timeout elapsed."); - } - } - } - - /** - * Waits for future to throw an error, but will timeout after {@link TestConstants#WaitTimeout}, - * and will be polled every {@link TestConstants#PollInterval} - * - * @param future - the future to wait for - */ - public static void waitTillFutureThrowsException(Future future, Class expected) { - long start = System.currentTimeMillis(); - - while (true) { - try { - Thread.sleep(TestConstants.PollInterval.toMillis()); - future.get(); - } catch (InterruptedException ignore) { - } catch (Throwable e) { - if(e.getClass().equals(expected)) { - return; //expected - } - } - - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - throw new RuntimeException("Future did not throw exception before wait timeout elapased."); - } - } - } - - /** - * Waits until thread is finished, but will timeout after {@link TestConstants#WaitTimeout}, - * and will be polled every {@link TestConstants#PollInterval} - * - * @param thread - the thread to wait for - */ - public static void waitTillThreadFinish(Thread thread) { - long start = System.currentTimeMillis(); - - while (thread.isAlive()) { - try { - Thread.sleep(TestConstants.PollInterval.toMillis()); - } catch (InterruptedException ignore) { - } - - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - throw new RuntimeException("Thread did not finish before wait timeout elapsed."); - } - } - } - - //########## Custom assertions ########## - - public static void assertInRange(Object[] range, Object actual) { - String expected = ""; - for (Object each : range) { - expected += each.toString(); - expected += ","; - } - expected = expected.substring(0, expected.length() - 1); - String msg = "expected in " + expected + " but you got " + actual; - for (Object each : range) { - if (each.equals(actual)) { - return; - } - } - fail(msg); - } - - public static void assertIntInRange(int low, int high, int actual) { - String msg = "expected in range " + low + " , " + high; - msg += " but you got " + actual; - if (actual < low || actual > high) { - fail(msg); - } - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/arquillian/extensions/TCKFrameworkAppender.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/arquillian/extensions/TCKFrameworkAppender.java index 6797b2e8..15211715 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/arquillian/extensions/TCKFrameworkAppender.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/arquillian/extensions/TCKFrameworkAppender.java @@ -22,7 +22,7 @@ import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.TestServlet; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.extensions.AssertionExtension; @@ -39,7 +39,7 @@ public class TCKFrameworkAppender implements AuxiliaryArchiveAppender { private static final Logger log = Logger.getLogger(TCKFrameworkAppender.class.getCanonicalName()); - private static final Package utilPackage = TestUtil.class.getPackage(); + private static final Package utilPackage = TestServlet.class.getPackage(); private static final Package annoPackage = Common.class.getPackage(); private static final Package extePackage = AssertionExtension.class.getPackage(); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/anno/Common.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/anno/Common.java index 8621fdb2..16a02da4 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/anno/Common.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/anno/Common.java @@ -16,6 +16,7 @@ public enum PACKAGE { FIXED_COUNTER, MANAGED_TASK_LISTENER, TASKS, + TRANSACTION, SIGNATURE; private static final String prefix = "ee/jakarta/tck/concurrent/common/"; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Assertions.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Assertions.java new file mode 100644 index 00000000..5e661c49 --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Assertions.java @@ -0,0 +1,53 @@ +package ee.jakarta.tck.concurrent.framework.junit.extensions; + +import java.util.Iterator; + +/** + * Helper class for custom assertions not supported by JUnit 5 + */ +public class Assertions { + + private Assertions() { + //helper method + } + + /** + * Asserts expected integer is within the range ( lowerBound, upperBound ) (exclusive). + */ + public static void assertWithin(int expected, int lowerBound, int upperBound) { + if( lowerBound < expected && upperBound > expected ) { + return; //pass + } + + String message = "Expected " + expected + " to be within the range ( " + lowerBound + ", " + upperBound + " )"; + throw new AssertionError(message); + } + + /** + * Asserts expected integer is within the range [ lowerBound, upperBound ] [inclusive]. + */ + public static void assertBetween(int expected, int lowerBound, int upperBound) { + if( lowerBound <= expected && upperBound >= expected ) { + return; //pass + } + + String message = "Expected " + expected + " to be within the range [ " + lowerBound + ", " + upperBound + " ]"; + throw new AssertionError(message); + } + + /** + * Asserts expected object is within a range represented by an Iterable + */ + public static void assertRangeContains(Object expected, Iterable range) { + Iterator it = range.iterator(); + while(it.hasNext()) { + if(it.equals(expected)) { + return; //pass + } + } + + String message = "Expected " + expected + " to be within the range " + range.toString(); + throw new AssertionError(message); + } + +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Wait.java b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Wait.java new file mode 100644 index 00000000..5a7eb74d --- /dev/null +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/framework/junit/extensions/Wait.java @@ -0,0 +1,135 @@ +package ee.jakarta.tck.concurrent.framework.junit.extensions; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.time.Duration; +import java.util.concurrent.Future; + +import ee.jakarta.tck.concurrent.common.managed.task.listener.ListenerEvent; +import ee.jakarta.tck.concurrent.common.managed.task.listener.ManagedTaskListenerImpl; +import ee.jakarta.tck.concurrent.common.transaction.CancelledTransactedTask; +import ee.jakarta.tck.concurrent.framework.TestConstants; +import ee.jakarta.tck.concurrent.framework.TestLogger; + +/** + * Utility class for waiting for results. + * + * Prioritize polling for results, and discourages sleeping + */ +public class Wait { + + static TestLogger log = TestLogger.get(Wait.class); + + private Wait() { + //Utility class no constructor + } + + /** + * Waits for task to complete, but will timeout after {@link TestConstants#WaitTimeout} + * + * @param future to wait for + * @return result + */ + public static T waitForTaskComplete(final Future future) { + return waitForTaskComplete(future, TestConstants.WaitTimeout); + } + + /** + * Waits for task to complete, but will timeout after specified timeout + * @param future - the future to wait for + * @param timeout - the duration of timeout + * @return result - result returned from future, or null if timeout was exceeded + */ + public static T waitForTaskComplete(final Future future, final Duration timeout) { + return assertTimeoutPreemptively(timeout, () -> future.get()); + } + + /** + * Wait for listener to complete, but will timeout after {@link TestConstants#WaitTimeout}, + * and will be polled ever {@link TestConstants#PollInterval} + * + * @param managedTaskListener - the listener to be polled + */ + public static void waitForListenerComplete(ManagedTaskListenerImpl managedTaskListener) { + waitForListenerComplete(managedTaskListener, TestConstants.WaitTimeout, TestConstants.PollInterval); + } + + /** + * Wait for listener to complete, but will timeout after a specified timeout, + * and will be polled ever specified interval + * + * @param managedTaskListener - the listener to be polled + * @param maxWaitTimeMillis - timeout + * @param pollIntervalMillis - poll interval + */ + public static void waitForListenerComplete(ManagedTaskListenerImpl managedTaskListener, Duration timeout, Duration pollInterval) { + assertTimeoutPreemptively(timeout, () -> { + for(; ! managedTaskListener.eventCalled(ListenerEvent.DONE); sleep(TestConstants.PollInterval)); + }); + } + + /** + * Waits for future to complete, but will timeout after {@link TestConstants#WaitTimeout}, + * and will be polled every {@link TestConstants#PollInterval} + * + * The difference between this method and waitForTaskComplete is that some + * scheduled task will return values for multiple times, in this situation + * waitForTaskComplete does not work. + * + * @param future - the future to wait for + */ + public static void waitTillFutureIsDone(final Future future) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; ! future.isDone(); sleep(TestConstants.PollInterval)); + }); + } + + /** + * Waits for future to throw an error, but will timeout after {@link TestConstants#WaitTimeout}, + * and will be polled every {@link TestConstants#PollInterval} + * + * @param future - the future to wait for + */ + public static void waitTillFutureThrowsException(final Future future, final Class expected) { + assertThrows(expected, () -> { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; ; sleep(TestConstants.PollInterval)) { + future.get(); + } + }); + }); + } + + public static void waitCancelFuture(final Future future) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(future.cancel(true); !future.isDone(); sleep(TestConstants.PollInterval)); + }); + } + + /** + * Waits until thread is finished, but will timeout after {@link TestConstants#WaitTimeout}, + * and will be polled every {@link TestConstants#PollInterval} + * + * @param thread - the thread to wait for + */ + public static void waitTillThreadFinish(final Thread thread) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; thread.isAlive(); sleep(TestConstants.PollInterval)); + }); + } + + public static void waitForTransactionBegan(CancelledTransactedTask task) { + assertTimeoutPreemptively(TestConstants.WaitTimeout, () -> { + for(; ! task.beginTransaction.get(); sleep(TestConstants.PollInterval)); + }); + } + + public static void sleep(Duration time) { + try { + Thread.sleep(time.toMillis()); + } catch (InterruptedException e) { + throw new AssertionError("Interrupted while sleeping", e); + } + } +} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/BaseTestRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/BaseTestRunnableWork.java index fe8baf58..f7d32762 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/BaseTestRunnableWork.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/BaseTestRunnableWork.java @@ -19,7 +19,10 @@ import java.io.Serializable; public abstract class BaseTestRunnableWork implements Serializable, Runnable, TestWorkInterface { - private String message; + + private static final long serialVersionUID = 1L; + + private String message; public void run() { message = work(); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/ContextPropagateBean.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/ContextPropagateBean.java index 2a41f0cc..9a184840 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/ContextPropagateBean.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/ContextPropagateBean.java @@ -37,7 +37,7 @@ public class ContextPropagateBean implements ContextPropagateInterface { public TestWorkInterface createWorker(String classname) { try { return (TestWorkInterface) context.createContextualProxy( - Class.forName(classname).newInstance(), Runnable.class, TestWorkInterface.class); + Class.forName(classname).getConstructor().newInstance(), Runnable.class, TestWorkInterface.class); } catch (Exception en) { throw new RuntimeException(en); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/BaseTestRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/BaseTestRunnableWork.java similarity index 91% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/BaseTestRunnableWork.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/BaseTestRunnableWork.java index db735342..9f55e53b 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/BaseTestRunnableWork.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/BaseTestRunnableWork.java @@ -14,12 +14,15 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import java.io.Serializable; public abstract class BaseTestRunnableWork implements Serializable, Runnable, TestWorkInterface { - private String message; + + private static final long serialVersionUID = 1L; + + private String message; public void run() { message = work(); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ContextPropagationServletTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ContextPropagationServletTests.java similarity index 99% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ContextPropagationServletTests.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ContextPropagationServletTests.java index 2be3f9ae..4c2fd650 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ContextPropagationServletTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ContextPropagationServletTests.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import static org.junit.jupiter.api.Assertions.assertNotNull; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/DeserializeServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/DeserializeServlet.java similarity index 99% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/DeserializeServlet.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/DeserializeServlet.java index a8d72c0a..726db6ff 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/DeserializeServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/DeserializeServlet.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ProxyCreatorServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ProxyCreatorServlet.java similarity index 94% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ProxyCreatorServlet.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ProxyCreatorServlet.java index 3836377a..6daee3f8 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/ProxyCreatorServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/ProxyCreatorServlet.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -27,7 +27,6 @@ import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ContextService; import jakarta.servlet.annotation.WebServlet; @@ -58,7 +57,7 @@ public void testJNDIContextInServlet(HttpServletRequest req, HttpServletResponse Properties p = new Properties(); p.setProperty("proxy", proxyToString(proxy)); - result = TestUtil.getResponse(TestUtil.sendPostData(url, p)); + result = getResponse(sendPostData(url, p)); resp.getWriter().println(result); } @@ -77,7 +76,7 @@ public void testClassloaderInServlet(HttpServletRequest req, HttpServletResponse Properties p = new Properties(); p.setProperty("proxy", proxyToString(proxy)); - result = TestUtil.getResponse(TestUtil.sendPostData(url, p)); + result = getResponse(sendPostData(url, p)); resp.getWriter().println(result); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestClassloaderRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestClassloaderRunnableWork.java similarity index 95% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestClassloaderRunnableWork.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestClassloaderRunnableWork.java index 492d4ae3..c20135d0 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestClassloaderRunnableWork.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestClassloaderRunnableWork.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import ee.jakarta.tck.concurrent.framework.TestConstants; @@ -25,7 +25,7 @@ public class TestClassloaderRunnableWork extends BaseTestRunnableWork { protected String work() { try { Thread.currentThread().getContextClassLoader().loadClass( - "ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet.ProxyCreatorServlet"); + "ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet.ProxyCreatorServlet"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestJNDIRunnableWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestJNDIRunnableWork.java similarity index 98% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestJNDIRunnableWork.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestJNDIRunnableWork.java index d6ab29fa..08a0e233 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestJNDIRunnableWork.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestJNDIRunnableWork.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import javax.naming.InitialContext; import javax.naming.NamingException; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestWorkInterface.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestWorkInterface.java similarity index 98% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestWorkInterface.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestWorkInterface.java index 2cabc84a..f917e39f 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/TestWorkInterface.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/TestWorkInterface.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import java.io.Serializable; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/WorkInterfaceServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/WorkInterfaceServlet.java similarity index 99% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/WorkInterfaceServlet.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/WorkInterfaceServlet.java index c0c00f6b..e13f30df 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/WorkInterfaceServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/WorkInterfaceServlet.java @@ -14,7 +14,7 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate_servlet; +package ee.jakarta.tck.concurrent.spec.ContextService.contextPropagate.servlet; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/web.xml b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/web.xml similarity index 100% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate_servlet/web.xml rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/contextPropagate/servlet/web.xml diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Constants.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Constants.java deleted file mode 100644 index 9e420f85..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Constants.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ContextService.tx; - -import java.time.Duration; - -public final class Constants { - private Constants() { - }; - - public static final String UT_JNDI_NAME = "java:comp/UserTransaction"; - - public static final String DS_JNDI_NAME = "java:comp/env/jdbc/ContextServiceDB"; - - public static final String DS_DB_NAME = "memory:ContextServiceDB"; - - public static final String CONTEXT_SVC_JNDI_NAME = "java:comp/DefaultContextService"; - - public static final String TABLE_P = "concurrencetable"; - - public static final String USERNAME = "user1"; - - public static final String PASSWORD = "password1"; - - public static final String SQL_TEMPLATE_DROP = "drop table concurrencetable"; - - public static final String SQL_TEMPLATE_CREATE = "create table concurrencetable (TYPE_ID int NOT NULL, TYPE_DESC varchar(32), primary key(TYPE_ID))"; - - public static final String SQL_TEMPLATE_INSERT = "insert into concurrencetable values(?, ?)"; - - public static final String SQL_TEMPLATE_DELETE = "delete from concurrencetable"; - - public static final Duration POLL_INTERVAL = Duration.ofSeconds(1); - - public static final Duration POLL_TIMEOUT = Duration.ofSeconds(30); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestTransactionWork.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestTransactionWork.java deleted file mode 100644 index 5c7c1a7b..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestTransactionWork.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ContextService.tx; - -import java.io.Serializable; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - -import javax.naming.InitialContext; - -import jakarta.transaction.UserTransaction; - -@SuppressWarnings("serial") -public class TestTransactionWork implements TestWorkInterface, Serializable { - - protected String result; - - protected Connection con; - - protected String sqlTemplate; - - protected boolean beginTran = false; - - protected boolean commit = false; - - protected boolean rollback = false; - - protected String userName; - - protected String password; - - @Override - public void doSomeWork() { - UserTransaction ut = null; - - if (beginTran) { - try { - ut = InitialContext.doLookup(Constants.UT_JNDI_NAME); - ut.begin(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - PreparedStatement pStmt = null; - try { - con = Util.getConnection(false, userName, password); - pStmt = con.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-98"; - int newType = 98; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - - if (commit) { - ut.commit(); - } - - if (rollback) { - ut.rollback(); - } - } catch (Exception e) { - throw new RuntimeException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (con != null) - con.close(); - } catch (SQLException se) { - } - } - } - - @Override - public String getResult() { - return result; - } - - @Override - public void setConnection(Connection con) { - this.con = con; - } - - @Override - public void setSQLTemplate(String sqlTemplate) { - this.sqlTemplate = sqlTemplate; - } - - @Override - public void needBeginTx(boolean beginTx) { - this.beginTran = beginTx; - } - - @Override - public void needCommit(boolean commit) { - this.commit = commit; - } - - @Override - public void needRollback(boolean rollback) { - this.rollback = rollback; - } - - @Override - public void run() { - doSomeWork(); - } - - @Override - public void setUserName(String name) { - this.userName = name; - } - - @Override - public void setPassword(String pass) { - this.password = pass; - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestWorkInterface.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestWorkInterface.java deleted file mode 100644 index 62442fb1..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TestWorkInterface.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ContextService.tx; - -import java.io.Serializable; -import java.sql.Connection; - -public interface TestWorkInterface extends Runnable, Serializable { - public void doSomeWork(); - - public String getResult(); - - public void setConnection(Connection conn); - - public void setSQLTemplate(String sqlTemplate); - - public void needBeginTx(boolean beginTx); - - public void needCommit(boolean commit); - - public void needRollback(boolean rollback); - - public void setUserName(String name); - - public void setPassword(String pass); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionServlet.java index 3bf3b1d5..e36cb9b8 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionServlet.java @@ -26,6 +26,12 @@ import javax.sql.DataSource; +import ee.jakarta.tck.concurrent.common.transaction.Connections; +import ee.jakarta.tck.concurrent.common.transaction.Constants; +import ee.jakarta.tck.concurrent.common.transaction.Counter; +import ee.jakarta.tck.concurrent.common.transaction.TransactedTask; +import ee.jakarta.tck.concurrent.common.transaction.WorkInterface; +import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.TestServlet; import jakarta.annotation.Resource; @@ -37,11 +43,11 @@ import jakarta.transaction.UserTransaction; @SuppressWarnings({"serial", "unused"}) -@WebServlet("/TransactionServlet") +@WebServlet(Constants.CONTEXT_PATH) @DataSourceDefinition( - name = Constants.DS_JNDI_NAME, + name = "java:comp/env/jdbc/ContextServiceDB", className = "org.apache.derby.jdbc.EmbeddedDataSource", - databaseName = Constants.DS_DB_NAME, + databaseName = "memory:ContextServiceDB", properties = { "createDatabase=create" } @@ -50,20 +56,22 @@ public class TransactionServlet extends TestServlet { private static final TestLogger log = TestLogger.get(TransactionServlet.class); - @Resource(lookup = Constants.DS_JNDI_NAME) + @Resource(lookup = "java:comp/env/jdbc/ContextServiceDB") private DataSource ds; - @Resource(lookup = Constants.CONTEXT_SVC_JNDI_NAME) + @Resource(lookup = TestConstants.DefaultContextService) private ContextService cx; - @Resource(lookup = Constants.UT_JNDI_NAME) + @Resource(lookup = TestConstants.UserTransaction) private UserTransaction ut; @Override protected void before() throws RemoteException { log.enter("before"); - try (Connection conn = Util.getConnection(ds, Constants.USERNAME, Constants.PASSWORD, true); Statement stmt = conn.createStatement()) { + Connections.setDataSource(ds); + + try (Connection conn = Connections.getConnection(true); Statement stmt = conn.createStatement()) { try { stmt.executeUpdate(Constants.SQL_TEMPLATE_DROP); } catch (SQLException e) { @@ -77,224 +85,176 @@ protected void before() throws RemoteException { } public String testTransactionOfExecuteThreadAndCommit() throws ServletException { - PreparedStatement pStmt = null; - Connection conn = null; - Connection conn2 = null; - - try { - int originCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - ut.begin(); - conn = Util.getConnection(false, Constants.USERNAME, Constants.PASSWORD); - pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT); - pStmt.setInt(1, 99); - pStmt.setString(2, "Type-99"); - pStmt.addBatch(); - pStmt.setInt(1, 100); - pStmt.setString(2, "Type-100"); - pStmt.addBatch(); - pStmt.executeBatch(); + + int originCount = Counter.getCount(); - TestWorkInterface work = new TestTransactionWork(); - work.setUserName(Constants.USERNAME); - work.setPassword(Constants.PASSWORD); - work.setSQLTemplate(Constants.SQL_TEMPLATE_INSERT); - Map m = new HashMap(); - m.put(ManagedTask.TRANSACTION, ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD); - TestWorkInterface proxy = cx.createContextualProxy(work, m, TestWorkInterface.class); - proxy.doSomeWork(); - ut.commit(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - - return String.valueOf(afterTransacted - originCount); + try { + ut.begin(); + try (Connection conn = Connections.getConnection(false); PreparedStatement pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT);) { + pStmt.setInt(1, 99); + pStmt.setString(2, "Type-99"); + pStmt.addBatch(); + pStmt.setInt(1, 100); + pStmt.setString(2, "Type-100"); + pStmt.addBatch(); + pStmt.executeBatch(); + + WorkInterface work = new TransactedTask(false, false, Constants.SQL_TEMPLATE_INSERT); + + Map m = new HashMap<>(); + m.put(ManagedTask.TRANSACTION, ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD); + + WorkInterface proxy = cx.createContextualProxy(work, m, WorkInterface.class); + proxy.doWork(); + + ut.commit(); + + int afterTransacted = Counter.getCount(); + + return String.valueOf(afterTransacted - originCount); + } } catch (Exception e) { throw new ServletException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (conn != null) - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } } } public String testTransactionOfExecuteThreadAndRollback() throws ServletException { - PreparedStatement pStmt = null; - Connection conn = null; - Connection conn2 = null; - + + int originCount = Counter.getCount(); + try { - int originCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - ut.begin(); - conn = Util.getConnection(false, Constants.USERNAME, Constants.PASSWORD); - pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT); - pStmt.setInt(1, 99); - pStmt.setString(2, "Type-99"); - pStmt.addBatch(); - pStmt.setInt(1, 100); - pStmt.setString(2, "Type-100"); - pStmt.addBatch(); - pStmt.executeBatch(); + ut.begin(); + try ( Connection conn = Connections.getConnection(false); PreparedStatement pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT);) { + pStmt.setInt(1, 99); + pStmt.setString(2, "Type-99"); + pStmt.addBatch(); + pStmt.setInt(1, 100); + pStmt.setString(2, "Type-100"); + pStmt.addBatch(); + pStmt.executeBatch(); + + WorkInterface work = new TransactedTask(false, false, Constants.SQL_TEMPLATE_INSERT); - TestWorkInterface work = new TestTransactionWork(); - work.setUserName(Constants.USERNAME); - work.setPassword(Constants.PASSWORD); - work.setSQLTemplate(Constants.SQL_TEMPLATE_INSERT); - Map m = new HashMap(); - m.put(ManagedTask.TRANSACTION, ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD); - TestWorkInterface proxy = cx.createContextualProxy(work, m, TestWorkInterface.class); - proxy.doSomeWork(); - ut.rollback(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); + Map m = new HashMap<>(); + m.put(ManagedTask.TRANSACTION, ManagedTask.USE_TRANSACTION_OF_EXECUTION_THREAD); + + WorkInterface proxy = cx.createContextualProxy(work, m, WorkInterface.class); + proxy.doWork(); + + ut.rollback(); + + int afterTransacted = Counter.getCount(); - return String.valueOf(afterTransacted - originCount); - } catch (Exception e) { - throw new ServletException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (conn != null) - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + return String.valueOf(afterTransacted - originCount); + } + } catch (Exception e) { + throw new ServletException(e); + } } public String testSuspendAndCommit() throws ServletException { - PreparedStatement pStmt = null; - Connection conn = null; - Connection conn2 = null; - + + int originCount = Counter.getCount(); + try { - int originCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - ut.begin(); - conn = Util.getConnection(false, Constants.USERNAME, Constants.PASSWORD); - pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT); - pStmt.setInt(1, 99); - pStmt.setString(2, "Type-99"); - pStmt.addBatch(); - pStmt.setInt(1, 100); - pStmt.setString(2, "Type-100"); - pStmt.addBatch(); - pStmt.executeBatch(); - TestWorkInterface work = new TestTransactionWork(); - work.setUserName(Constants.USERNAME); - work.setPassword(Constants.PASSWORD); - work.setSQLTemplate(Constants.SQL_TEMPLATE_INSERT); - work.needBeginTx(true); - work.needCommit(true); - Map m = new HashMap(); - m.put(ManagedTask.TRANSACTION, ManagedTask.SUSPEND); - TestWorkInterface proxy = cx.createContextualProxy(work, m, TestWorkInterface.class); - proxy.doSomeWork(); - ut.rollback(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); + ut.begin(); + try (Connection conn = Connections.getConnection(false); PreparedStatement pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT);) { + + pStmt.setInt(1, 99); + pStmt.setString(2, "Type-99"); + pStmt.addBatch(); + pStmt.setInt(1, 100); + pStmt.setString(2, "Type-100"); + pStmt.addBatch(); + pStmt.executeBatch(); + + WorkInterface work = new TransactedTask(true, true, Constants.SQL_TEMPLATE_INSERT); + + Map m = new HashMap<>(); + m.put(ManagedTask.TRANSACTION, ManagedTask.SUSPEND); + + WorkInterface proxy = cx.createContextualProxy(work, m, WorkInterface.class); + proxy.doWork(); + + ut.rollback(); + + int afterTransacted = Counter.getCount(); - return String.valueOf(afterTransacted - originCount); - } catch (Exception e) { - throw new ServletException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (conn != null) - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + return String.valueOf(afterTransacted - originCount); + } + } catch (Exception e) { + throw new ServletException(e); + } + } - public String testSuspendAndRollback() throws ServletException { - PreparedStatement pStmt = null; - Connection conn = null; - Connection conn2 = null; - + public String testSuspendAndRollback() throws ServletException { + + int originCount = Counter.getCount(); + try { - int originCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - ut.begin(); - conn = Util.getConnection(false, Constants.USERNAME, Constants.PASSWORD); - pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT); - pStmt.setInt(1, 99); - pStmt.setString(2, "Type-99"); - pStmt.addBatch(); - pStmt.setInt(1, 100); - pStmt.setString(2, "Type-100"); - pStmt.addBatch(); - pStmt.executeBatch(); - TestWorkInterface work = new TestTransactionWork(); - work.setUserName(Constants.USERNAME); - work.setPassword(Constants.PASSWORD); - work.setSQLTemplate(Constants.SQL_TEMPLATE_INSERT); - work.needBeginTx(true); - work.needRollback(true); - Map m = new HashMap(); - m.put(ManagedTask.TRANSACTION, ManagedTask.SUSPEND); - TestWorkInterface proxy = cx.createContextualProxy(work, m, TestWorkInterface.class); - proxy.doSomeWork(); - ut.commit(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); + ut.begin(); + + try (Connection conn = Connections.getConnection(false); PreparedStatement pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT);) { + pStmt.setInt(1, 99); + pStmt.setString(2, "Type-99"); + pStmt.addBatch(); + pStmt.setInt(1, 100); + pStmt.setString(2, "Type-100"); + pStmt.addBatch(); + pStmt.executeBatch(); - return String.valueOf(afterTransacted - originCount); - } catch (Exception e) { - throw new ServletException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (conn != null) - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + WorkInterface work = new TransactedTask(false, true, Constants.SQL_TEMPLATE_INSERT); + + Map m = new HashMap<>(); + m.put(ManagedTask.TRANSACTION, ManagedTask.SUSPEND); + + WorkInterface proxy = cx.createContextualProxy(work, m, WorkInterface.class); + proxy.doWork(); + + ut.commit(); + + int afterTransacted = Counter.getCount(); + + return String.valueOf(afterTransacted - originCount); + } + } catch (Exception e) { + throw new ServletException(e); + } + } public String testDefaultAndCommit() throws ServletException { - PreparedStatement pStmt = null; - Connection conn = null; - Connection conn2 = null; - - try { - int originCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - ut.begin(); - conn = Util.getConnection(false, Constants.USERNAME, Constants.PASSWORD); - pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT); - pStmt.setInt(1, 99); - pStmt.setString(2, "Type-99"); - pStmt.addBatch(); - pStmt.setInt(1, 100); - pStmt.setString(2, "Type-100"); - pStmt.addBatch(); - pStmt.executeBatch(); - TestWorkInterface work = new TestTransactionWork(); - work.setUserName(Constants.USERNAME); - work.setPassword(Constants.PASSWORD); - work.setSQLTemplate(Constants.SQL_TEMPLATE_INSERT); - work.needBeginTx(true); - work.needCommit(true); - TestWorkInterface proxy = cx.createContextualProxy(work, TestWorkInterface.class); - proxy.doSomeWork(); - ut.rollback(); - // int afterTransacted = Util.getCount(Constants.TABLE_P, conn); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); + + int originCount = Counter.getCount(); + + try { + ut.begin(); + + try (Connection conn = Connections.getConnection(false); PreparedStatement pStmt = conn.prepareStatement(Constants.SQL_TEMPLATE_INSERT);) { + + pStmt.setInt(1, 99); + pStmt.setString(2, "Type-99"); + pStmt.addBatch(); + pStmt.setInt(1, 100); + pStmt.setString(2, "Type-100"); + pStmt.addBatch(); + pStmt.executeBatch(); + + WorkInterface work = new TransactedTask(true, true, Constants.SQL_TEMPLATE_INSERT); + + WorkInterface proxy = cx.createContextualProxy(work, WorkInterface.class); + proxy.doWork(); + + ut.rollback(); + + int afterTransacted = Counter.getCount(); - return String.valueOf(afterTransacted - originCount); - } catch (Exception e) { - throw new ServletException(e); - } finally { - try { - if (pStmt != null) - pStmt.close(); - if (conn != null) - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + return String.valueOf(afterTransacted - originCount); + } + } catch (Exception e) { + throw new ServletException(e); + } + } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionTests.java index f724a54a..acfb4a8b 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/TransactionTests.java @@ -26,10 +26,13 @@ import org.junit.jupiter.api.Test; import ee.jakarta.tck.concurrent.framework.TestClient; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.TestName; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; @Web @RunAsClient //Requires client testing due to annotation configuration +@Common({ PACKAGE.TRANSACTION }) public class TransactionTests extends TestClient { @ArquillianResource diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Util.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Util.java deleted file mode 100644 index 76a1146f..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ContextService/tx/Util.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ContextService.tx; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import ee.jakarta.tck.concurrent.framework.TestLogger; - -public class Util { - - private static final TestLogger log = TestLogger.get(Util.class); - - private Util() { - } - - public static Connection getConnection(DataSource ds, String user, String pwd, boolean autoCommit) { - Connection conn = null; - try { - conn = ds.getConnection(); // Try without user password for EE case - if (conn == null) { - conn = ds.getConnection(user, pwd); // For standalone cases - } - if (null != conn) { - conn.setAutoCommit(autoCommit); - } - } catch (SQLException e) { - log.severe("failed to get connection.", e); - } - return conn; - } - - public static int getCount(String tableName, String username, String password) { - Connection conn = getConnection(true, username, password); - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - /** - * get count by specifying connection. the caller should take care of closing - * connection. - * - * @param conn - * @param tableName - * @param username - * @param password - * @return - */ - public static int getCount(Connection conn, String tableName, String username, String password) { - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - public static Connection getConnection(boolean autoCommit, String username, String password) { - DataSource ds; - try { - ds = InitialContext.doLookup(Constants.DS_JNDI_NAME); - } catch (NamingException e) { - throw new RuntimeException(e); - } - Connection conn = Util.getConnection(ds, username, password, autoCommit); - return conn; - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/InheritedAPITests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/InheritedAPITests.java index 5b5d56d7..db08a6a9 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/InheritedAPITests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/InheritedAPITests.java @@ -17,32 +17,41 @@ package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.inheritedapi; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.ExecutionException; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.jupiter.api.Test; +import ee.jakarta.tck.concurrent.common.fixed.counter.CounterRunnableTask; +import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; +import ee.jakarta.tck.concurrent.common.tasks.CommonTasks; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Assertions; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; @Web +@Common({ PACKAGE.TASKS, PACKAGE.FIXED_COUNTER }) public class InheritedAPITests { @Deployment(name = "InheritedAPITests") public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class).addClass(Task.class); + return ShrinkWrap.create(WebArchive.class); } @Resource(lookup = TestConstants.DefaultManagedExecutorService) @@ -67,74 +76,89 @@ public static WebArchive createDeployment() { @Test public void testExecute() { - Task commonTask = new Task.CommonTask(0); - executor.execute(commonTask); - // wait for a while. try { - TimeUnit.SECONDS.sleep(3); - } catch (InterruptedException e) { - fail(e.toString()); + executor.execute(new CounterRunnableTask()); + StaticCounter.waitTill(1); + } finally { + StaticCounter.reset(); } } @Test - public void testSubmit() { - Task commonTask = new Task.CommonTask(0); - Future noRes = executor.submit((Runnable) commonTask); - try { - TestUtil.waitForTaskComplete(noRes); - } catch (Exception e) { - fail(e.toString()); - } + public void testSubmit() throws Exception { + Future result = executor.submit(new CommonTasks.SimpleCallable()); + Wait.waitTillFutureIsDone(result); + assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); + + result = executor.submit(new CommonTasks.SimpleRunnable()); + Wait.waitTillFutureIsDone(result); + result.get(); + + result = executor.submit(new CommonTasks.SimpleRunnable(), CommonTasks.SIMPLE_RETURN_STRING); + Wait.waitTillFutureIsDone(result); + assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); } @Test public void testInvokeAny() { - Task.CommonTask commonTask0 = new Task.CommonTask(0); - Task.CommonTask commonTask1 = new Task.CommonTask(1); - List tasks = new ArrayList(); - tasks.add(commonTask0); - tasks.add(commonTask1); - int res = -1; try { - res = executor.invokeAny(tasks); - } catch (InterruptedException e) { - fail(e.toString()); - } catch (ExecutionException e) { - fail(e.toString()); + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleArgCallable(1)); + taskList.add(new CommonTasks.SimpleArgCallable(2)); + taskList.add(new CommonTasks.SimpleArgCallable(3)); + Integer result = executor.invokeAny(taskList); + Assertions.assertBetween(result, 1, 3); + + result = executor.invokeAny(taskList, TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); + Assertions.assertBetween(result, 1, 3); + } catch (Exception e) { + throw new RuntimeException(e); } - assertTrue(tasks.get(res).isRan()); + + assertThrows(TimeoutException.class, () -> { + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + executor.invokeAny(taskList, TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); + }); } @Test public void testInvokeAll() { - Task.CommonTask commonTask0 = new Task.CommonTask(0); - Task.CommonTask commonTask1 = new Task.CommonTask(1); - List tasks = new ArrayList(); - tasks.add(commonTask0); - tasks.add(commonTask1); - List> res = null; try { - res = executor.invokeAll(tasks); - TestUtil.waitForTaskComplete(res.get(0)); - TestUtil.waitForTaskComplete(res.get(1)); + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleArgCallable(1)); + taskList.add(new CommonTasks.SimpleArgCallable(2)); + taskList.add(new CommonTasks.SimpleArgCallable(3)); + List> resultList = executor.invokeAll(taskList); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); + } + assertEquals(resultList.get(0).get(), 1); + assertEquals(resultList.get(1).get(), 2); + assertEquals(resultList.get(2).get(), 3); + + resultList = executor.invokeAll(taskList, TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); + } + assertEquals(resultList.get(0).get(), 1); + assertEquals(resultList.get(1).get(), 2); + assertEquals(resultList.get(2).get(), 3); } catch (Exception e) { - fail(e.toString()); + fail(e.getMessage()); } - assertTrue(commonTask0.isRan()); - assertTrue(commonTask1.isRan()); - } - @Test - public void testAtMostOnce() { - Task.CommonTask commonTask = new Task.CommonTask(0); - Future future = executor.submit((Runnable) commonTask); try { - TestUtil.waitForTaskComplete(future); - } catch (Exception e) { - fail(e.toString()); + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + List> resultList = executor.invokeAll(taskList, TestConstants.PollInterval.getSeconds(),TimeUnit.SECONDS); + for (Future each : resultList) { + Wait.waitTillFutureThrowsException(each, CancellationException.class); + } + } catch (Exception ex) { + fail(ex.getMessage()); } - // check number. - assertEquals(commonTask.runCount(), 1); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/Task.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/Task.java deleted file mode 100644 index 9ece7c66..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/inheritedapi/Task.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.inheritedapi; - -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicInteger; - -public abstract class Task implements Runnable, Callable { - protected boolean ran; - - protected final int taskId; - - protected final AtomicInteger count = new AtomicInteger(0); - - public Task(int id) { - taskId = id; - } - - boolean isRan() { - return ran; - } - - public int runCount() { - return count.get(); - } - - static class CommonTask extends Task { - public CommonTask(int id) { - super(id); - } - - @Override - public void run() { - // each time add count when run called - count.incrementAndGet(); - ran = true; - } - - @Override - public Integer call() throws Exception { - ran = true; - return taskId; - } - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityServlet.java index f171cfec..533a1ee8 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityServlet.java @@ -22,7 +22,7 @@ import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedExecutorService; import jakarta.servlet.annotation.WebServlet; @@ -39,7 +39,7 @@ public class SecurityServlet extends TestServlet { public void managedExecutorServiceAPISecurityTest(HttpServletRequest req, HttpServletResponse res) throws Exception { req.login("javajoe", "javajoe"); Future future = executor.submit(new SecurityTestTask()); - Object result = TestUtil.waitForTaskComplete(future); + Object result = Wait.waitForTaskComplete(future); assertEquals(result, TestConstants.SimpleReturnValue); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityTestTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityTestTask.java index c8c414b0..bea9f5d3 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityTestTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/security/SecurityTestTask.java @@ -23,7 +23,7 @@ import ee.jakarta.tck.concurrent.framework.EJBJNDIProvider; -public class SecurityTestTask implements Callable { +public class SecurityTestTask implements Callable { public String call() { try { diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/CancelledTransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/CancelledTransactedTask.java deleted file mode 100644 index 79143173..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/CancelledTransactedTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.tx; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.time.Duration; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; -import jakarta.transaction.UserTransaction; - -public class CancelledTransactedTask implements Runnable { - private volatile boolean runFlag; - - private volatile boolean transactionBegan; - - private volatile boolean cancelled; - - private final String username, password, sqlTemplate; - - public CancelledTransactedTask(String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - } - - public void resume() { - runFlag = true; - } - - public void cancelTask() { - cancelled = true; - } - - public boolean transactionBegin() { - return transactionBegan; - } - - @Override - public void run() { - Connection conn = Util.getConnection(false, username, password); - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - if (ut == null) { - // error if no transaction can be obtained in task. - throw new RuntimeException("didn't get user transaction inside the submitted task."); - } else { - PreparedStatement pStmt = null; - try { - ut.begin(); - transactionBegan = true; - while (!runFlag) { - TestUtil.sleep(Duration.ofMillis(500)); - } - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-Cancelled-99"; - int newType = 991; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // check if it is cancelled here - if (cancelled) { - ut.rollback(); - return; - } - ut.commit(); - } catch (Exception e) { - try { - ut.rollback(); - } catch (Exception e1) { - e1.printStackTrace(); - } - e.printStackTrace(); - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Constants.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Constants.java deleted file mode 100644 index 42c8032b..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Constants.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.tx; - -import java.time.Duration; - -public final class Constants { - private Constants() { - }; - - public static final String CONTEXT_PATH = "/TransactionServlet"; - - public static final String DS_JNDI_NAME = "java:comp/env/jdbc/ManagedExecutorServiceDB"; - - public static final String DS_DB_NAME = "memory:ManagedExecutorServiceDB"; - - public static final String PARAM_COMMIT = "isCommit"; - - public static final String COMMIT_TRUE = "isCommit=true"; - - public static final String COMMIT_FALSE = "isCommit=false"; - - public static final String COMMIT_CANCEL = "isCommit=cancel"; - - public static final String TABLE_P = "concurrencetable"; - - public static final String USERNAME = "user1"; - - public static final String PASSWORD = "password1"; - - public static final String SQL_TEMPLATE_DROP = "drop table concurrencetable"; - - public static final String SQL_TEMPLATE_CREATE = "create table concurrencetable (TYPE_ID int NOT NULL, TYPE_DESC varchar(32), primary key(TYPE_ID))"; - - public static final String SQL_TEMPLATE_INSERT = "insert into concurrencetable values(?, ?)"; - - public static final String SQL_TEMPLATE_DELETE = "delete from concurrencetable"; - - public static final Duration POLL_INTERVAL = Duration.ofSeconds(1); - - public static final Duration POLL_TIMEOUT = Duration.ofSeconds(30); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactedTask.java deleted file mode 100644 index 02bbdba5..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactedTask.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.tx; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestLogger; -import jakarta.transaction.UserTransaction; - -public class TransactedTask implements Runnable { - - private static final TestLogger log = TestLogger.get(TransactedTask.class); - - private final boolean isCommit; - - private final String username, password, sqlTemplate; - - public TransactedTask(boolean commitOrRollback, String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - isCommit = commitOrRollback; - } - - @Override - public void run() { - boolean pass = false; - String tableName = Constants.TABLE_P; - int originCount = Util.getCount(tableName, username, password); - - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - if (ut == null) { - // error if no transaction can be obtained in task. - throw new RuntimeException("didn't get user transaction inside the submitted task."); - } else { - Connection conn = Util.getConnection(false, username, password); - PreparedStatement pStmt = null; - try { - ut.begin(); - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-99"; - int newType = 99; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // commit or roll back transaction. - if (isCommit) { - ut.commit(); - } else { - ut.rollback(); - } - // check status. - int afterTransacted = Util.getCount(tableName, username, password); - if (isCommit) { - pass = (afterTransacted == originCount + 1); - } else { - pass = (afterTransacted == originCount); - } - } catch (Exception e) { - log.severe("Got exception when trying to run TransactedTask", e); - try { - ut.rollback(); - } catch (Exception e1) { - log.finer("Got exception when trying to do rollback on failed test", e1); - } - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception e) { - log.finer("Got exception when trying to close connection and statment", e); - } - } - assertTrue(pass, "didn't get expected result with transacted task."); - } - } - -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionServlet.java index 6e1e2007..bf3230d9 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionServlet.java @@ -27,10 +27,15 @@ import javax.sql.DataSource; +import ee.jakarta.tck.concurrent.common.transaction.CancelledTransactedTask; +import ee.jakarta.tck.concurrent.common.transaction.Connections; +import ee.jakarta.tck.concurrent.common.transaction.Constants; +import ee.jakarta.tck.concurrent.common.transaction.Counter; +import ee.jakarta.tck.concurrent.common.transaction.TransactedTask; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.annotation.sql.DataSourceDefinition; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; @@ -41,9 +46,9 @@ @SuppressWarnings({"serial", "unused"}) @WebServlet(Constants.CONTEXT_PATH) @DataSourceDefinition( - name = Constants.DS_JNDI_NAME, + name = "java:comp/env/jdbc/ManagedExecutorServiceDB", className = "org.apache.derby.jdbc.EmbeddedDataSource", - databaseName = Constants.DS_DB_NAME, + databaseName = "memory:ManagedExecutorServiceDB", properties = { "createDatabase=create" } @@ -52,7 +57,7 @@ public class TransactionServlet extends TestServlet { private static final TestLogger log = TestLogger.get(TransactionServlet.class); - @Resource(lookup = Constants.DS_JNDI_NAME) + @Resource(lookup = "java:comp/env/jdbc/ManagedExecutorServiceDB") private DataSource ds; @Resource(lookup = TestConstants.DefaultManagedScheduledExecutorService) @@ -62,7 +67,9 @@ public class TransactionServlet extends TestServlet { protected void beforeClass() throws RemoteException { log.enter("beforeClass"); - try (Connection conn = Util.getConnection(ds, Constants.USERNAME, Constants.PASSWORD, true); Statement stmt = conn.createStatement()) { + Connections.setDataSource(ds); + + try (Connection conn = Connections.getConnection(true); Statement stmt = conn.createStatement()) { try { stmt.executeUpdate(Constants.SQL_TEMPLATE_DROP); } catch (SQLException e) { @@ -77,23 +84,30 @@ protected void beforeClass() throws RemoteException { public void transactionTest(HttpServletRequest req, HttpServletResponse res) throws Exception { boolean isCommit = Boolean.parseBoolean(req.getParameter(Constants.PARAM_COMMIT)); - Future taskResult = scheduledExecutor.submit(new TransactedTask(isCommit, - Constants.USERNAME, Constants.PASSWORD, Constants.SQL_TEMPLATE_INSERT)); - TestUtil.waitForTaskComplete(taskResult); -} + + Future taskResult = scheduledExecutor.submit( + new TransactedTask(isCommit, Constants.SQL_TEMPLATE_INSERT)); + + Wait.waitForTaskComplete(taskResult); + } public void cancelTest() { - int originTableCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.USERNAME, Constants.PASSWORD, - Constants.SQL_TEMPLATE_INSERT); + int originTableCount = Counter.getCount(); + + CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.SQL_TEMPLATE_INSERT); Future future = scheduledExecutor.submit(cancelledTask); + // then cancel it after transaction begin and - Util.waitForTransactionBegan(cancelledTask); + Wait.waitForTransactionBegan(cancelledTask); + // before it commit. - cancelledTask.cancelTask(); + cancelledTask.cancelTransaction.set(true); + // continue to run if possible. - cancelledTask.resume(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); + cancelledTask.runQuery.set(true);; + + int afterTransacted = Counter.getCount(); + assertEquals(originTableCount, afterTransacted,"task was not properly cancelled"); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionTests.java index c4133446..24dddb38 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/TransactionTests.java @@ -26,11 +26,15 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; +import ee.jakarta.tck.concurrent.common.transaction.Constants; import ee.jakarta.tck.concurrent.framework.TestClient; import ee.jakarta.tck.concurrent.framework.URLBuilder; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; @Web @RunAsClient //Requires client testing due to annotation configuration +@Common({ PACKAGE.TRANSACTION }) public class TransactionTests extends TestClient { @ArquillianResource diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Util.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Util.java deleted file mode 100644 index 8db581e0..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedExecutorService/tx/Util.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedExecutorService.tx; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.TestUtil; - -public class Util { - - private static final TestLogger log = TestLogger.get(Util.class); - - private Util() { - } - - public static Connection getConnection(DataSource ds, String user, String pwd, boolean autoCommit) { - Connection conn = null; - try { - conn = ds.getConnection(); // Try without user password for EE case - if (conn == null) { - conn = ds.getConnection(user, pwd); // For standalone cases - } - if (null != conn) { - conn.setAutoCommit(autoCommit); - } - } catch (SQLException e) { - log.severe("failed to get connection.", e); - } - return conn; - } - - public static int getCount(String tableName, String username, String password) { - Connection conn = getConnection(true, username, password); - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - /** - * get count by specifying connection. the caller should take care of closing - * connection. - * - * @param conn - * @param tableName - * @param username - * @param password - * @return - */ - public static int getCount(Connection conn, String tableName, String username, String password) { - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - public static Connection getConnection(boolean autoCommit, String username, String password) { - DataSource ds; - try { - ds = InitialContext.doLookup(Constants.DS_JNDI_NAME); - } catch (NamingException e) { - throw new RuntimeException(e); - } - Connection conn = Util.getConnection(ds, username, password, autoCommit); - return conn; - } - - public static void waitForTransactionBegan(CancelledTransactedTask pp) { - final long stopTime = System.currentTimeMillis() + Constants.POLL_TIMEOUT.toMillis(); - while (!pp.transactionBegin() && System.currentTimeMillis() < stopTime) { - try { - TestUtil.sleep(Constants.POLL_INTERVAL); - } catch (InterruptedException ignore) { - } - } - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPITests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIFullTests.java similarity index 93% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPITests.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIFullTests.java index da2e2e1f..9eeb64c1 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPITests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIFullTests.java @@ -28,13 +28,13 @@ import jakarta.ejb.EJB; @Full -public class InheritedAPITests { +public class InheritedAPIFullTests { @Deployment(name="InheritedAPITests") public static EnterpriseArchive createDeployment() { JavaArchive inheritedJAR = ShrinkWrap.create(JavaArchive.class, "inheritedapi.jar") - .addClasses(InheritedAPITests.class, CounterEJBProvider.class, TestEjb.class, TestEjbInterface.class) - .addPackages(true, PACKAGE.TASKS.getPackageName(), PACKAGE.COUNTER.getPackageName()) + .addClasses(InheritedAPIFullTests.class, CounterEJBProvider.class, TestEjb.class, TestEjbInterface.class) + .addPackages(true, PACKAGE.TASKS.getPackageName(), PACKAGE.COUNTER.getPackageName(), PACKAGE.FIXED_COUNTER.getPackageName()) .addAsServiceProvider(EJBJNDIProvider.class, CounterEJBProvider.FullProvider.class); EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, "inheritedapi.ear").addAsModules(inheritedJAR); diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIWebTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIWebTests.java index b56a96f3..959acc13 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIWebTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/InheritedAPIWebTests.java @@ -28,7 +28,7 @@ import jakarta.ejb.EJB;; @Web -@Common({PACKAGE.TASKS, PACKAGE.COUNTER}) +@Common({PACKAGE.TASKS, PACKAGE.COUNTER, PACKAGE.FIXED_COUNTER}) public class InheritedAPIWebTests { @Deployment(name="InheritedAPITests") diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/TestEjb.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/TestEjb.java index 5afa812e..2adf623d 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/TestEjb.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/TestEjb.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; +import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; @@ -30,10 +31,12 @@ import ee.jakarta.tck.concurrent.common.counter.CounterInterface; import ee.jakarta.tck.concurrent.common.counter.CounterRunnableTask; +import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; import ee.jakarta.tck.concurrent.common.tasks.CommonTasks; import ee.jakarta.tck.concurrent.framework.EJBJNDIProvider; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Assertions; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.ejb.EJB; import jakarta.ejb.Stateless; @@ -50,16 +53,16 @@ public class TestEjb implements TestEjbInterface { public void testApiSubmit() { try { - Future result = scheduledExecutor.submit(new CommonTasks.SimpleCallable()); - TestUtil.waitTillFutureIsDone(result); + Future result = scheduledExecutor.submit(new CommonTasks.SimpleCallable()); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); result = scheduledExecutor.submit(new CommonTasks.SimpleRunnable()); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); result.get(); result = scheduledExecutor.submit(new CommonTasks.SimpleRunnable(), CommonTasks.SIMPLE_RETURN_STRING); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); } catch (Exception e) { throw new RuntimeException(e); @@ -70,9 +73,7 @@ public void testApiExecute() { try { EJBJNDIProvider nameProvider = ServiceLoader.load(EJBJNDIProvider.class).findFirst().orElseThrow(); scheduledExecutor.execute(new CounterRunnableTask(nameProvider.getEJBJNDIName())); - waitForCounter(1); - } catch (Exception e) { - fail(e.getMessage()); + StaticCounter.waitTillSurpassed(1); }finally { counter.reset(); } @@ -80,21 +81,21 @@ public void testApiExecute() { public void testApiInvokeAll() { try { - List taskList = new ArrayList(); + List> taskList = new ArrayList<>(); taskList.add(new CommonTasks.SimpleArgCallable(1)); taskList.add(new CommonTasks.SimpleArgCallable(2)); taskList.add(new CommonTasks.SimpleArgCallable(3)); - List resultList = scheduledExecutor.invokeAll(taskList); - for (Future each : resultList) { - TestUtil.waitTillFutureIsDone(each); + List> resultList = scheduledExecutor.invokeAll(taskList); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); } assertEquals(resultList.get(0).get(), 1); assertEquals(resultList.get(1).get(), 2); assertEquals(resultList.get(2).get(), 3); resultList = scheduledExecutor.invokeAll(taskList, TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); - for (Future each : resultList) { - TestUtil.waitTillFutureIsDone(each); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); } assertEquals(resultList.get(0).get(), 1); assertEquals(resultList.get(1).get(), 2); @@ -104,13 +105,12 @@ public void testApiInvokeAll() { } try { - List taskList = new ArrayList(); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - List resultList = scheduledExecutor.invokeAll(taskList, TestConstants.PollInterval.getSeconds(), - TimeUnit.SECONDS); - for (Future each : resultList) { - TestUtil.waitTillFutureThrowsException(each, CancellationException.class); + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + List> resultList = scheduledExecutor.invokeAll(taskList, TestConstants.PollInterval.getSeconds(),TimeUnit.SECONDS); + for (Future each : resultList) { + Wait.waitTillFutureThrowsException(each, CancellationException.class); } } catch (Exception ex) { fail(ex.getMessage()); @@ -119,24 +119,24 @@ public void testApiInvokeAll() { public void testApiInvokeAny() { try { - List taskList = new ArrayList(); + List> taskList = new ArrayList<>(); taskList.add(new CommonTasks.SimpleArgCallable(1)); taskList.add(new CommonTasks.SimpleArgCallable(2)); taskList.add(new CommonTasks.SimpleArgCallable(3)); - Object result = scheduledExecutor.invokeAny(taskList); - TestUtil.assertInRange(new Integer[] { 1, 2, 3 }, result); + Integer result = scheduledExecutor.invokeAny(taskList); + Assertions.assertBetween(result, 1, 3); result = scheduledExecutor.invokeAny(taskList, TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); - TestUtil.assertInRange(new Integer[] { 1, 2, 3 }, result); + Assertions.assertBetween(result, 1, 3); } catch (Exception e) { throw new RuntimeException(e); } try { - List taskList = new ArrayList(); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - Object result = scheduledExecutor.invokeAny(taskList, TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + scheduledExecutor.invokeAny(taskList, TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); } catch (TimeoutException e) { return; //expected } catch (Exception ex) { @@ -147,14 +147,14 @@ public void testApiInvokeAny() { public void testApiSchedule() { try { - Future result = scheduledExecutor.schedule(new CommonTasks.SimpleCallable(), + Future result = scheduledExecutor.schedule(new CommonTasks.SimpleCallable(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(CommonTasks.SIMPLE_RETURN_STRING, result.get()); result = scheduledExecutor.schedule(new CommonTasks.SimpleRunnable(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), null); } catch (Exception e) { fail(e.getMessage()); @@ -162,66 +162,42 @@ public void testApiSchedule() { } public void testApiScheduleAtFixedRate() { - ScheduledFuture result = null; + ScheduledFuture result = null; try { EJBJNDIProvider nameProvider = ServiceLoader.load(EJBJNDIProvider.class).findFirst().orElseThrow(); result = scheduledExecutor.scheduleAtFixedRate(new CounterRunnableTask(nameProvider.getEJBJNDIName()), TestConstants.PollInterval.getSeconds(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.sleep(TestConstants.WaitTimeout); - TestUtil.assertIntInRange(TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2, counter.getCount()); + Wait.sleep(TestConstants.WaitTimeout); + Assertions.assertBetween(counter.getCount(), TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2); } catch (Exception e) { fail(e.getMessage()); } finally { - if (result != null) { - result.cancel(true); - // Sleep to ensure cancel take effect. - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (Exception e) { - } - } + if (result != null) { + Wait.waitCancelFuture(result); + } counter.reset(); } } public void testApiScheduleWithFixedDelay() { - ScheduledFuture result = null; + ScheduledFuture result = null; try { EJBJNDIProvider nameProvider = ServiceLoader.load(EJBJNDIProvider.class).findFirst().orElseThrow(); result = scheduledExecutor.scheduleWithFixedDelay( - new CounterRunnableTask(nameProvider.getEJBJNDIName(), TestConstants.PollInterval.toMillis()), //task + new CounterRunnableTask(nameProvider.getEJBJNDIName(), TestConstants.PollInterval), //task TestConstants.PollInterval.getSeconds(), //initial delay TestConstants.PollInterval.getSeconds(), //delay TimeUnit.SECONDS); //Time units - TestUtil.sleep(TestConstants.WaitTimeout); - TestUtil.assertIntInRange((TestConstants.PollsPerTimeout / 2) - 2, (TestConstants.PollsPerTimeout / 2) + 2, counter.getCount()); + Wait.sleep(TestConstants.WaitTimeout); + Assertions.assertBetween(counter.getCount(), (TestConstants.PollsPerTimeout / 2) - 2, (TestConstants.PollsPerTimeout / 2) + 2); } catch (Exception e) { fail(e.getMessage()); } finally { if (result != null) { - result.cancel(true); - // Sleep to ensure cancel take effect. - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (Exception e) { - } + Wait.waitCancelFuture(result); } counter.reset(); } } - private void waitForCounter(int expected) { - long start = System.currentTimeMillis(); - - while (expected != counter.getCount()) { - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (InterruptedException ignore) { - } - - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - throw new RuntimeException("Static counter did not produce expected counter before timeout. Expected: " + expected + " Actual: " + counter.getCount()); - } - } - } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi_servlet/InheritedAPIServletTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/servlet/InheritedAPIServletTests.java similarity index 59% rename from tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi_servlet/InheritedAPIServletTests.java rename to tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/servlet/InheritedAPIServletTests.java index 2c7ee6c0..9fe405bd 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi_servlet/InheritedAPIServletTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/inheritedapi/servlet/InheritedAPIServletTests.java @@ -14,13 +14,15 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.inheritedapi_servlet; +package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.inheritedapi.servlet; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; @@ -37,10 +39,11 @@ import ee.jakarta.tck.concurrent.common.fixed.counter.StaticCounter; import ee.jakarta.tck.concurrent.common.tasks.CommonTasks; import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; import ee.jakarta.tck.concurrent.framework.junit.anno.Common; import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Assertions; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; @@ -70,17 +73,17 @@ public void before() { */ @Test public void testApiSubmit() throws Exception { - Future result = scheduledExecutor.submit(new CommonTasks.SimpleCallable()); - TestUtil.waitTillFutureIsDone(result); + Future result = scheduledExecutor.submit(new CommonTasks.SimpleCallable()); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); result = scheduledExecutor.submit(new CommonTasks.SimpleRunnable()); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); result.get(); result = scheduledExecutor.submit(new CommonTasks.SimpleRunnable(), CommonTasks.SIMPLE_RETURN_STRING); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); } @@ -93,8 +96,12 @@ public void testApiSubmit() throws Exception { */ @Test public void testApiExecute() { - scheduledExecutor.execute(new CounterRunnableTask()); - waitForCounter(1); + try { + scheduledExecutor.execute(new CounterRunnableTask()); + StaticCounter.waitTill(1); + } finally { + StaticCounter.reset(); + } } /* @@ -106,34 +113,38 @@ public void testApiExecute() { */ @Test public void testApiInvokeAll() throws Exception { - List taskList = new ArrayList(); - taskList.add(new CommonTasks.SimpleArgCallable(1)); - taskList.add(new CommonTasks.SimpleArgCallable(2)); - taskList.add(new CommonTasks.SimpleArgCallable(3)); - List resultList = scheduledExecutor.invokeAll(taskList); - for (Future each : resultList) { - TestUtil.waitTillFutureIsDone(each); - } - assertEquals(resultList.get(0).get(), 1); - assertEquals(resultList.get(1).get(), 2); - assertEquals(resultList.get(2).get(), 3); - resultList = scheduledExecutor.invokeAll(taskList, - TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); - for (Future each : resultList) { - TestUtil.waitTillFutureIsDone(each); + try { + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleArgCallable(1)); + taskList.add(new CommonTasks.SimpleArgCallable(2)); + taskList.add(new CommonTasks.SimpleArgCallable(3)); + List> resultList = scheduledExecutor.invokeAll(taskList); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); + } + assertEquals(resultList.get(0).get(), 1); + assertEquals(resultList.get(1).get(), 2); + assertEquals(resultList.get(2).get(), 3); + resultList = scheduledExecutor.invokeAll(taskList, + TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); + for (Future each : resultList) { + Wait.waitTillFutureIsDone(each); + } + assertEquals(resultList.get(0).get(), 1); + assertEquals(resultList.get(1).get(), 2); + assertEquals(resultList.get(2).get(), 3); + } catch (Exception ex) { + fail(ex.getMessage()); } - assertEquals(resultList.get(0).get(), 1); - assertEquals(resultList.get(1).get(), 2); - assertEquals(resultList.get(2).get(), 3); try { - taskList = new ArrayList(); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - resultList = scheduledExecutor.invokeAll(taskList, + List> taskList = new ArrayList<>(); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + List> resultList = scheduledExecutor.invokeAll(taskList, TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - for (Future each : resultList) { - TestUtil.waitTillFutureThrowsException(each, CancellationException.class); + for (Future each : resultList) { + Wait.waitTillFutureThrowsException(each, CancellationException.class); } } catch (Exception ex) { fail(ex.getMessage()); @@ -149,28 +160,23 @@ public void testApiInvokeAll() throws Exception { */ @Test public void testApiInvokeAny() throws Exception { - List taskList = new ArrayList(); + + List> taskList = new ArrayList<>(); taskList.add(new CommonTasks.SimpleArgCallable(1)); taskList.add(new CommonTasks.SimpleArgCallable(2)); taskList.add(new CommonTasks.SimpleArgCallable(3)); - Object result = scheduledExecutor.invokeAny(taskList); - TestUtil.assertInRange(new Integer[] { 1, 2, 3 }, result); - result = scheduledExecutor.invokeAny(taskList, - TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); - TestUtil.assertInRange(new Integer[] { 1, 2, 3 }, result); - - try { - taskList = new ArrayList(); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - taskList.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout.toMillis())); - result = scheduledExecutor.invokeAny(taskList, - TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - } catch (TimeoutException e) { - return; // expected - } catch (Exception ex) { - fail(ex.getMessage()); - } - fail("Task should be cancelled because of timeout"); + Integer result = scheduledExecutor.invokeAny(taskList); + Assertions.assertBetween(result, 1, 3); + + result = scheduledExecutor.invokeAny(taskList, TestConstants.WaitTimeout.getSeconds(), TimeUnit.SECONDS); + Assertions.assertBetween(result, 1, 3); + + assertThrows(TimeoutException.class, () -> { + List> taskList2 = new ArrayList<>(); + taskList2.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + taskList2.add(new CommonTasks.SimpleCallable(TestConstants.WaitTimeout)); + scheduledExecutor.invokeAny(taskList2, TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); + }); } /* @@ -182,14 +188,14 @@ public void testApiInvokeAny() throws Exception { */ @Test public void testApiSchedule() throws Exception { - Future result = scheduledExecutor.schedule(new CommonTasks.SimpleCallable(), + Future result = scheduledExecutor.schedule(new CommonTasks.SimpleCallable(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), CommonTasks.SIMPLE_RETURN_STRING); result = scheduledExecutor.schedule(new CommonTasks.SimpleRunnable(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.waitTillFutureIsDone(result); + Wait.waitTillFutureIsDone(result); assertEquals(result.get(), null); } @@ -202,24 +208,18 @@ public void testApiSchedule() throws Exception { */ @Test public void testApiScheduleAtFixedRate() { - ScheduledFuture result = null; + ScheduledFuture result = null; try { result = scheduledExecutor.scheduleAtFixedRate(new CounterRunnableTask(), TestConstants.PollInterval.getSeconds(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.sleep(TestConstants.WaitTimeout); - TestUtil.assertIntInRange(TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2, - StaticCounter.getCount()); + Wait.sleep(TestConstants.WaitTimeout); + Assertions.assertBetween(StaticCounter.getCount(), TestConstants.PollsPerTimeout - 2, TestConstants.PollsPerTimeout + 2); } catch (Exception e) { fail(e.getMessage()); } finally { if (result != null) { - result.cancel(true); - // Sleep to ensure cancel take effect. - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (Exception e) { - } + Wait.waitCancelFuture(result); } } } @@ -233,40 +233,18 @@ public void testApiScheduleAtFixedRate() { */ @Test public void testApiScheduleWithFixedDelay() { - ScheduledFuture result = null; + ScheduledFuture result = null; try { result = scheduledExecutor.scheduleWithFixedDelay( new CounterRunnableTask(TestConstants.PollInterval), TestConstants.PollInterval.getSeconds(), TestConstants.PollInterval.getSeconds(), TimeUnit.SECONDS); - TestUtil.sleep(TestConstants.WaitTimeout); - TestUtil.assertIntInRange((TestConstants.PollsPerTimeout / 2) - 2, (TestConstants.PollsPerTimeout / 2) + 2, - StaticCounter.getCount()); + Wait.sleep(TestConstants.WaitTimeout); + Assertions.assertBetween(StaticCounter.getCount(), (TestConstants.PollsPerTimeout / 2) - 2, (TestConstants.PollsPerTimeout / 2) + 2); } catch (Exception e) { fail(e.getMessage()); } finally { if (result != null) { - result.cancel(true); - // Sleep to ensure cancel take effect. - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (Exception e) { - } - } - } - } - - private void waitForCounter(int expected) { - long start = System.currentTimeMillis(); - - while (expected != StaticCounter.getCount()) { - try { - TestUtil.sleep(TestConstants.PollInterval); - } catch (InterruptedException ignore) { - } - - if ((System.currentTimeMillis() - start) > TestConstants.WaitTimeout.toMillis()) { - throw new RuntimeException("Static counter did not produce expected counter before timeout. Expected: " - + expected + " Actual: " + StaticCounter.getCount()); + Wait.waitCancelFuture(result); } } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIEJBTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIEJBTests.java index 4e40bf41..464bb09a 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIEJBTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIEJBTests.java @@ -29,9 +29,7 @@ @Web @Common({PACKAGE.TASKS, PACKAGE.FIXED_COUNTER}) public class ForbiddenAPIEJBTests { - - private static final String APP_NAME = "ManagedScheduledExecutorService.ForbiddenAPITests"; - + @Deployment(name="ForbiddenAPITests") public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIServletTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIServletTests.java index 2ea9d49f..658ad1b0 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIServletTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/managed/forbiddenapi/ForbiddenAPIServletTests.java @@ -20,8 +20,6 @@ import java.util.concurrent.TimeUnit; -import javax.naming.InitialContext; - import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityServlet.java index b9c7782b..72efaa30 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityServlet.java @@ -25,7 +25,7 @@ import ee.jakarta.tck.concurrent.common.tasks.CommonTriggers; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServletRequest; @@ -39,9 +39,9 @@ public void managedScheduledExecutorServiceAPISecurityTest(HttpServletRequest re req.login("javajoe", "javajoe"); ManagedScheduledExecutorService executorService = InitialContext.doLookup(TestConstants.DefaultManagedScheduledExecutorService); - ScheduledFuture future = executorService.schedule(new SecurityTestTask(), new CommonTriggers.OnceTrigger()); + ScheduledFuture future = executorService.schedule(new SecurityTestTask(), new CommonTriggers.OnceTrigger()); - Object result = TestUtil.waitForTaskComplete(future); + Object result = Wait.waitForTaskComplete(future); assertEquals(result, TestConstants.SimpleReturnValue); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityTestTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityTestTask.java index f89560bb..dc47a607 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityTestTask.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/security/SecurityTestTask.java @@ -23,7 +23,7 @@ import ee.jakarta.tck.concurrent.framework.EJBJNDIProvider; -public class SecurityTestTask implements Callable { +public class SecurityTestTask implements Callable { public String call() { try { diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/CancelledTransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/CancelledTransactedTask.java deleted file mode 100644 index 78db91b3..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/CancelledTransactedTask.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.tx; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.time.Duration; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; -import jakarta.transaction.UserTransaction; - -public class CancelledTransactedTask implements Runnable { - private volatile boolean runFlag; - - private volatile boolean transactionBegan; - - private volatile boolean cancelled; - - private final String username, password, sqlTemplate; - - public CancelledTransactedTask(String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - } - - public void resume() { - runFlag = true; - } - - public void cancelTask() { - cancelled = true; - } - - public boolean transactionBegin() { - return transactionBegan; - } - - @Override - public void run() { - Connection conn = Util.getConnection(false, username, password); - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - - assertNotNull(ut, "didn't get user transaction inside the submitted task."); - - PreparedStatement pStmt = null; - try { - ut.begin(); - transactionBegan = true; - while (!runFlag) { - TestUtil.sleep(Duration.ofMillis(500)); - } - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-Cancelled-99"; - int newType = 991; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // check if it is cancelled here - if (cancelled) { - ut.rollback(); - return; - } - ut.commit(); - } catch (Exception e) { - try { - ut.rollback(); - } catch (Exception e1) { - //ignore - } - fail(e.getMessage()); - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception e) { - //ignore - } - } - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Constants.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Constants.java deleted file mode 100644 index 3dba83f4..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Constants.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.tx; - -import java.time.Duration; - -public final class Constants { - private Constants() { - }; - - public static final String DS_JNDI_NAME = "java:comp/env/jdbc/ManagedScheduledExecutorServiceDB"; - - public static final String DS_DB_NAME = "memory:ManagedScheduledExecutorServiceDB"; - - public static final String PARAM_COMMIT = "isCommit"; - - public static final String COMMIT_TRUE = "isCommit=true"; - - public static final String COMMIT_FALSE = "isCommit=false"; - - public static final String COMMIT_CANCEL = "isCommit=cancel"; - - public static final String TABLE_P = "concurrencetable"; - - public static final String USERNAME = "user1"; - - public static final String PASSWORD = "password1"; - - public static final String SQL_TEMPLATE_DROP = "drop table concurrencetable"; - - public static final String SQL_TEMPLATE_CREATE = "create table concurrencetable (TYPE_ID int NOT NULL, TYPE_DESC varchar(32), primary key(TYPE_ID))"; - - public static final String SQL_TEMPLATE_INSERT = "insert into concurrencetable values(?, ?)"; - - public static final String SQL_TEMPLATE_DELETE = "delete from concurrencetable"; - - public static final Duration POLL_INTERVAL = Duration.ofSeconds(1); - - public static final Duration POLL_TIMEOUT = Duration.ofSeconds(30); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactedTask.java deleted file mode 100644 index fb678000..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactedTask.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.tx; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestLogger; -import jakarta.transaction.UserTransaction; - -public class TransactedTask implements Runnable { - - private static final TestLogger log = TestLogger.get(TransactedTask.class); - - private final boolean isCommit; - - private final String username, password, sqlTemplate; - - public TransactedTask(boolean commitOrRollback, String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - isCommit = commitOrRollback; - } - - @Override - public void run() { - boolean pass = false; - String tableName = Constants.TABLE_P; - int originCount = Util.getCount(tableName, username, password); - - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - assertNotNull(ut, "didn't get user transaction inside the submitted task."); - - Connection conn = Util.getConnection(false, username, password); - PreparedStatement pStmt = null; - try { - ut.begin(); - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-99"; - int newType = 99; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // commit or roll back transaction. - if (isCommit) { - ut.commit(); - } else { - ut.rollback(); - } - // check status. - int afterTransacted = Util.getCount(tableName, username, password); - if (isCommit) { - pass = (afterTransacted == originCount + 1); - } else { - pass = (afterTransacted == originCount); - } - } catch (Exception e) { - try { - ut.rollback(); - } catch (Exception e1) { - log.finer("Got exception when trying to do rollback on failed test", e1); - } - fail("Got exception when trying to run TransactedTask"); - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception e) { - log.finer("Got exception when trying to close connection and statment", e); - } - } - assertTrue(pass, "didn't get expected result with transacted task."); - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionServlet.java index 1012eb5b..86f23a5e 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionServlet.java @@ -27,10 +27,15 @@ import javax.sql.DataSource; +import ee.jakarta.tck.concurrent.common.transaction.CancelledTransactedTask; +import ee.jakarta.tck.concurrent.common.transaction.Connections; +import ee.jakarta.tck.concurrent.common.transaction.Constants; +import ee.jakarta.tck.concurrent.common.transaction.Counter; +import ee.jakarta.tck.concurrent.common.transaction.TransactedTask; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.annotation.sql.DataSourceDefinition; import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; @@ -39,11 +44,11 @@ import jakarta.servlet.http.HttpServletResponse; @SuppressWarnings({"serial", "unused"}) -@WebServlet("/TransactionServlet") +@WebServlet(Constants.CONTEXT_PATH) @DataSourceDefinition( - name = Constants.DS_JNDI_NAME, + name = "java:comp/env/jdbc/ManagedScheduledExecutorServiceDB", className = "org.apache.derby.jdbc.EmbeddedDataSource", - databaseName = Constants.DS_DB_NAME, + databaseName = "memory:ManagedScheduledExecutorServiceDB", properties = { "createDatabase=create" } @@ -52,7 +57,7 @@ public class TransactionServlet extends TestServlet { private static final TestLogger log = TestLogger.get(TransactionServlet.class); - @Resource(lookup = Constants.DS_JNDI_NAME) + @Resource(lookup = "java:comp/env/jdbc/ManagedScheduledExecutorServiceDB") private DataSource ds; @Resource(lookup = TestConstants.DefaultManagedScheduledExecutorService) @@ -62,7 +67,9 @@ public class TransactionServlet extends TestServlet { protected void beforeClass() throws RemoteException { log.enter("beforeClass"); - try (Connection conn = Util.getConnection(ds, Constants.USERNAME, Constants.PASSWORD, true); Statement stmt = conn.createStatement()) { + Connections.setDataSource(ds); + + try (Connection conn = Connections.getConnection(true); Statement stmt = conn.createStatement()) { try { stmt.executeUpdate(Constants.SQL_TEMPLATE_DROP); } catch (SQLException e) { @@ -78,23 +85,29 @@ protected void beforeClass() throws RemoteException { public void transactionTest(HttpServletRequest req, HttpServletResponse res) throws Exception { boolean isCommit = Boolean.parseBoolean(req.getParameter(Constants.PARAM_COMMIT)); Future taskResult = managedScheduledExecutorService.schedule( - new TransactedTask(isCommit, Constants.USERNAME, Constants.PASSWORD, Constants.SQL_TEMPLATE_INSERT), + new TransactedTask(isCommit, Constants.SQL_TEMPLATE_INSERT), new OnceTrigger()); - TestUtil.waitForTaskComplete(taskResult); + Wait.waitForTaskComplete(taskResult); } public void cancelTest() { - int originTableCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.USERNAME, Constants.PASSWORD, - Constants.SQL_TEMPLATE_INSERT); + int originTableCount = Counter.getCount(); + + CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.SQL_TEMPLATE_INSERT); Future future = managedScheduledExecutorService.schedule(cancelledTask, new OnceTrigger()); - // then cancel it after transaction begin and - Util.waitForTransactionBegan(cancelledTask); - // before it commit. - cancelledTask.cancelTask(); - // continue to run if possible. - cancelledTask.resume(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - assertEquals(originTableCount, afterTransacted, "task was not properly cancelled"); + + + // then cancel it after transaction begin and + Wait.waitForTransactionBegan(cancelledTask); + + // before it commit. + cancelledTask.cancelTransaction.set(true); + + // continue to run if possible. + cancelledTask.runQuery.set(true);; + + int afterTransacted = Counter.getCount(); + + assertEquals(originTableCount, afterTransacted, "task was not properly cancelled"); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionTests.java index bad1063c..eec960c5 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/TransactionTests.java @@ -26,11 +26,15 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; +import ee.jakarta.tck.concurrent.common.transaction.Constants; import ee.jakarta.tck.concurrent.framework.TestClient; import ee.jakarta.tck.concurrent.framework.URLBuilder; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; @Web @RunAsClient //Requires client testing due to annotation configuration +@Common({ PACKAGE.TRANSACTION }) public class TransactionTests extends TestClient { @ArquillianResource @@ -57,7 +61,7 @@ public static WebArchive createDeployment() { @Test @Order(1) public void testRollbackTransactionWithManagedScheduledExecutorService() { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_FALSE).withTestName("transactionTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_FALSE).withTestName("transactionTest")); } /* @@ -75,7 +79,7 @@ public void testRollbackTransactionWithManagedScheduledExecutorService() { @Test //TODO rewrite test logic to avoid duplicate key violation @Order(2) public void testCommitTransactionWithManagedScheduledExecutorService() { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_TRUE).withTestName("transactionTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_TRUE).withTestName("transactionTest")); } /* @@ -93,6 +97,6 @@ public void testCommitTransactionWithManagedScheduledExecutorService() { @Test @Order(3) public void testCancelTransactionWithManagedScheduledExecutorService() { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_CANCEL).withTestName("cancelTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_CANCEL).withTestName("cancelTest")); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Util.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Util.java deleted file mode 100644 index 4804fb26..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedScheduledExecutorService/tx/Util.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedScheduledExecutorService.tx; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.TestUtil; - -public class Util { - - private static final TestLogger log = TestLogger.get(Util.class); - - private Util() { - } - - public static Connection getConnection(DataSource ds, String user, String pwd, boolean autoCommit) { - Connection conn = null; - try { - conn = ds.getConnection(); // Try without user password for EE case - if (conn == null) { - conn = ds.getConnection(user, pwd); // For standalone cases - } - if (null != conn) { - conn.setAutoCommit(autoCommit); - } - } catch (SQLException e) { - log.severe("failed to get connection.", e); - } - return conn; - } - - public static int getCount(String tableName, String username, String password) { - Connection conn = getConnection(true, username, password); - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - /** - * get count by specifying connection. the caller should take care of closing - * connection. - * - * @param conn - * @param tableName - * @param username - * @param password - * @return - */ - public static int getCount(Connection conn, String tableName, String username, String password) { - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - public static Connection getConnection(boolean autoCommit, String username, String password) { - DataSource ds; - try { - ds = InitialContext.doLookup(Constants.DS_JNDI_NAME); - } catch (NamingException e) { - throw new RuntimeException(e); - } - Connection conn = Util.getConnection(ds, username, password, autoCommit); - return conn; - } - - public static void waitForTransactionBegan(CancelledTransactedTask pp) { - final long stopTime = System.currentTimeMillis() + Constants.POLL_TIMEOUT.toMillis(); - while (!pp.transactionBegin() && System.currentTimeMillis() < stopTime) { - try { - TestUtil.sleep(Constants.POLL_INTERVAL); - } catch (InterruptedException ignore) { - } - } - } -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context/SecurityServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context/SecurityServlet.java index 4b858bfc..9744ee5a 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context/SecurityServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context/SecurityServlet.java @@ -23,7 +23,7 @@ import ee.jakarta.tck.concurrent.common.tasks.RunnableTask; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.ejb.EJB; import jakarta.enterprise.concurrent.ManagedThreadFactory; import jakarta.servlet.annotation.WebServlet; @@ -50,7 +50,7 @@ public void jndiClassloaderPropagationTest(HttpServletRequest req, HttpServletRe CounterRunnableWithContext task = new CounterRunnableWithContext(); Thread thread = factory.newThread(task); thread.start(); - TestUtil.waitTillThreadFinish(thread); + Wait.waitTillThreadFinish(thread); assertEquals(task.getCount(), 1); } @@ -63,7 +63,7 @@ public void jndiClassloaderPropagationWithSecurityTest(HttpServletRequest req, H CounterRunnableWithSecurityCheck task = new CounterRunnableWithSecurityCheck(str); Thread thread = factory.newThread(task); thread.start(); - TestUtil.waitTillThreadFinish(thread); + Wait.waitTillThreadFinish(thread); assertEquals(task.getCount(), 1); } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/ContextServletTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/ContextServletTests.java deleted file mode 100644 index 122afd9b..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/ContextServletTests.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.context_servlet; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import javax.naming.InitialContext; - -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.jupiter.api.Test; - -import ee.jakarta.tck.concurrent.common.tasks.RunnableTask; -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; -import ee.jakarta.tck.concurrent.framework.junit.anno.Common; -import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; -import ee.jakarta.tck.concurrent.framework.junit.anno.Web; -import jakarta.enterprise.concurrent.ManagedThreadFactory; - -@Web -@Common({ PACKAGE.TASKS }) -public class ContextServletTests { - - @Deployment(name = "ContextServletTests") - public static WebArchive createDeployment() { - return ShrinkWrap.create(WebArchive.class) - .addAsWebInfResource(ContextServletTests.class.getPackage(), "web.xml", "web.xml"); - } - - private static final String TEST_JNDI_EVN_ENTRY_VALUE = "hello"; - - private static final String TEST_JNDI_EVN_ENTRY_JNDI_NAME = "java:comp/env/ManagedThreadFactory_test_string"; - - private static final String TEST_CLASSLOADER_CLASS_NAME = ContextServletTests.class.getCanonicalName(); - - /* - * @testName: jndiClassloaderPropagationTest - * - * @assertion_ids: CONCURRENCY:SPEC:96.7; CONCURRENCY:SPEC:100; - * CONCURRENCY:SPEC:106; - * - * @test_Strategy: - */ - @Test - public void jndiClassloaderPropagationTest() throws Exception { - ManagedThreadFactory factory = InitialContext.doLookup(TestConstants.DefaultManagedThreadFactory); - - RunnableTask task = new RunnableTask(TEST_JNDI_EVN_ENTRY_JNDI_NAME, TEST_JNDI_EVN_ENTRY_VALUE, - TEST_CLASSLOADER_CLASS_NAME); - Thread thread = factory.newThread(task); - thread.start(); - TestUtil.waitTillThreadFinish(thread); - assertEquals(task.getCount(), 1); - } - -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/web.xml b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/web.xml deleted file mode 100644 index ee24963e..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/context_servlet/web.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - ManagedThreadFactory_test_string - java.lang.String - hello - - diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/CancelledTransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/CancelledTransactedTask.java deleted file mode 100644 index 411f50fd..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/CancelledTransactedTask.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.tx; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.time.Duration; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestUtil; -import jakarta.transaction.UserTransaction; - -public class CancelledTransactedTask implements Runnable { - private volatile boolean runFlag; - - private volatile boolean transactionBegan; - - private volatile boolean cancelled; - - private final String username, password, sqlTemplate; - - public CancelledTransactedTask(String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - } - - public void resume() { - runFlag = true; - } - - public void cancelTask() { - cancelled = true; - } - - public boolean transactionBegin() { - return transactionBegan; - } - - @Override - public void run() { - Connection conn = Util.getConnection(false, username, password); - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - assertNotNull(ut, "didn't get user transaction inside the submitted task."); - - PreparedStatement pStmt = null; - try { - ut.begin(); - transactionBegan = true; - while (!runFlag) { - TestUtil.sleep(Duration.ofMillis(500)); - } - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-Cancelled-99"; - int newType = 991; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // check if it is cancelled here - if (cancelled) { - ut.rollback(); - return; - } - ut.commit(); - } catch (Exception e) { - try { - ut.rollback(); - } catch (Exception ignore) { - } - fail("Caught exception trying to rollback or commit"); - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception ignore) { - } - } - } - -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Constants.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Constants.java deleted file mode 100644 index 9e17a42a..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Constants.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.tx; - -import java.time.Duration; - -public final class Constants { - private Constants() { - }; - - public static final String DS_JNDI_NAME = "java:comp/env/jdbc/ManagedThreadFactoryDB"; - - public static final String DS_DB_NAME = "memory:ManagedThreadFactoryDB"; - - public static final String PARAM_COMMIT = "isCommit"; - - public static final String COMMIT_TRUE = "isCommit=true"; - - public static final String COMMIT_FALSE = "isCommit=false"; - - public static final String COMMIT_CANCEL = "isCommit=cancel"; - - public static final String TABLE_P = "concurrencetable"; - - public static final String USERNAME = "user1"; - - public static final String PASSWORD = "password1"; - - public static final String SQL_TEMPLATE_DROP = "drop table concurrencetable"; - - public static final String SQL_TEMPLATE_CREATE = "create table concurrencetable (TYPE_ID int NOT NULL, TYPE_DESC varchar(32), primary key(TYPE_ID))"; - - public static final String SQL_TEMPLATE_INSERT = "insert into concurrencetable values(?, ?)"; - - public static final String SQL_TEMPLATE_DELETE = "delete from concurrencetable"; - - public static final Duration POLL_INTERVAL = Duration.ofSeconds(1); - - public static final Duration POLL_TIMEOUT = Duration.ofSeconds(30); -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactedTask.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactedTask.java deleted file mode 100644 index 92ee05ad..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactedTask.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2013, 2023 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.tx; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import ee.jakarta.tck.concurrent.framework.TestConstants; -import ee.jakarta.tck.concurrent.framework.TestLogger; -import jakarta.transaction.UserTransaction; - -public class TransactedTask implements Runnable { - - private static final TestLogger log = TestLogger.get(TransactedTask.class); - - private final boolean isCommit; - - private final String username, password, sqlTemplate; - - public TransactedTask(boolean commitOrRollback, String username, String password, String sqlTemplate) { - this.username = username; - this.password = password; - this.sqlTemplate = sqlTemplate; - isCommit = commitOrRollback; - } - - @Override - public void run() { - boolean pass = false; - String tableName = Constants.TABLE_P; - int originCount = Util.getCount(tableName, username, password); - - UserTransaction ut; - try { - ut = InitialContext.doLookup(TestConstants.UserTransaction); - } catch (NamingException e) { - throw new RuntimeException(e); - } - assertNotNull(ut, "didn't get user transaction inside the submitted task."); - - Connection conn = Util.getConnection(false, username, password); - PreparedStatement pStmt = null; - try { - ut.begin(); - pStmt = conn.prepareStatement(sqlTemplate); - String sTypeDesc = "Type-99"; - int newType = 99; - pStmt.setInt(1, newType); - pStmt.setString(2, sTypeDesc); - pStmt.executeUpdate(); - // commit or roll back transaction. - if (isCommit) { - ut.commit(); - } else { - ut.rollback(); - } - // check status. - int afterTransacted = Util.getCount(tableName, username, password); - if (isCommit) { - pass = (afterTransacted == originCount + 1); - } else { - pass = (afterTransacted == originCount); - } - } catch (Exception e) { - try { - ut.rollback(); - } catch (Exception e1) { - log.finer("Got exception when trying to do rollback on failed test", e1); - } - fail("Got exception when trying to run TransactedTask", e); - } finally { - try { - pStmt.close(); - conn.close(); - } catch (Exception e) { - log.finer("Got exception when trying to close connection and statment", e); - } - } - - assertTrue(pass, "didn't get expected result with transacted task."); - } - -} diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionServlet.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionServlet.java index 096ef819..0919d157 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionServlet.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionServlet.java @@ -26,10 +26,15 @@ import javax.sql.DataSource; +import ee.jakarta.tck.concurrent.common.transaction.CancelledTransactedTask; +import ee.jakarta.tck.concurrent.common.transaction.Connections; +import ee.jakarta.tck.concurrent.common.transaction.Constants; +import ee.jakarta.tck.concurrent.common.transaction.Counter; +import ee.jakarta.tck.concurrent.common.transaction.TransactedTask; import ee.jakarta.tck.concurrent.framework.TestConstants; import ee.jakarta.tck.concurrent.framework.TestLogger; import ee.jakarta.tck.concurrent.framework.TestServlet; -import ee.jakarta.tck.concurrent.framework.TestUtil; +import ee.jakarta.tck.concurrent.framework.junit.extensions.Wait; import jakarta.annotation.Resource; import jakarta.annotation.sql.DataSourceDefinition; import jakarta.enterprise.concurrent.ManagedThreadFactory; @@ -37,11 +42,12 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -@WebServlet("/TransactionServlet") +@SuppressWarnings("serial") +@WebServlet(Constants.CONTEXT_PATH) @DataSourceDefinition( - name = Constants.DS_JNDI_NAME, + name = "java:comp/env/jdbc/ManagedThreadFactoryDB", className = "org.apache.derby.jdbc.EmbeddedDataSource", - databaseName = Constants.DS_DB_NAME, + databaseName = "memory:ManagedThreadFactoryDB", properties = { "createDatabase=create" } @@ -50,7 +56,7 @@ public class TransactionServlet extends TestServlet { private static final TestLogger log = TestLogger.get(TransactionServlet.class); - @Resource(lookup = Constants.DS_JNDI_NAME) + @Resource(lookup = "java:comp/env/jdbc/ManagedThreadFactoryDB") private DataSource ds; @Resource(lookup = TestConstants.DefaultManagedThreadFactory) @@ -60,7 +66,9 @@ public class TransactionServlet extends TestServlet { protected void beforeClass() throws RemoteException { log.enter("beforeClass"); - try (Connection conn = Util.getConnection(ds, Constants.USERNAME, Constants.PASSWORD, true); Statement stmt = conn.createStatement()) { + Connections.setDataSource(ds); + + try (Connection conn = Connections.getConnection(true); Statement stmt = conn.createStatement()) { try { stmt.executeUpdate(Constants.SQL_TEMPLATE_DROP); } catch (SQLException e) { @@ -75,25 +83,29 @@ protected void beforeClass() throws RemoteException { public void transactionTest(HttpServletRequest req, HttpServletResponse res) throws Exception { boolean isCommit = Boolean.parseBoolean(req.getParameter(Constants.PARAM_COMMIT)); - Thread thread = threadFactory.newThread(new TransactedTask(isCommit, Constants.USERNAME, Constants.PASSWORD, - Constants.SQL_TEMPLATE_INSERT)); + Thread thread = threadFactory.newThread(new TransactedTask(isCommit, Constants.SQL_TEMPLATE_INSERT)); thread.start(); - TestUtil.waitTillThreadFinish(thread); + Wait.waitTillThreadFinish(thread); } public void cancelTest() { - int originTableCount = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.USERNAME, Constants.PASSWORD, - Constants.SQL_TEMPLATE_INSERT); + int originTableCount = Counter.getCount(); + + CancelledTransactedTask cancelledTask = new CancelledTransactedTask(Constants.SQL_TEMPLATE_INSERT); Thread thread = threadFactory.newThread(cancelledTask); thread.start(); - // then cancel it after transaction begin and - Util.waitForTransactionBegan(cancelledTask); - // before it commit. - cancelledTask.cancelTask(); - // continue to run if possible. - cancelledTask.resume(); - int afterTransacted = Util.getCount(Constants.TABLE_P, Constants.USERNAME, Constants.PASSWORD); - assertEquals(originTableCount, afterTransacted, "task was not properly cancelled"); + + // then cancel it after transaction begin and + Wait.waitForTransactionBegan(cancelledTask); + + // before it commit. + cancelledTask.cancelTransaction.set(true); + + // continue to run if possible. + cancelledTask.runQuery.set(true);; + + int afterTransacted = Counter.getCount(); + + assertEquals(originTableCount, afterTransacted,"task was not properly cancelled"); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionTests.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionTests.java index 06069e85..779a9715 100644 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionTests.java +++ b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/TransactionTests.java @@ -26,11 +26,15 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; +import ee.jakarta.tck.concurrent.common.transaction.Constants; import ee.jakarta.tck.concurrent.framework.TestClient; import ee.jakarta.tck.concurrent.framework.URLBuilder; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common; +import ee.jakarta.tck.concurrent.framework.junit.anno.Common.PACKAGE; import ee.jakarta.tck.concurrent.framework.junit.anno.Web; @Web @RunAsClient //Requires client testing due to annotation configuration +@Common({ PACKAGE.TRANSACTION }) public class TransactionTests extends TestClient { @ArquillianResource @@ -58,7 +62,7 @@ public static WebArchive createDeployment() { @Test @Order(1) public void testRollbackTransactionWithManagedThreadFactory() { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_FALSE).withTestName("transactionTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_FALSE).withTestName("transactionTest")); } /* @@ -78,7 +82,7 @@ public void testRollbackTransactionWithManagedThreadFactory() { @Test //TODO rewrite test logic to avoid duplicate key violation @Order(2) public void testCommitTransactionWithManagedThreadFactory() throws InterruptedException { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_TRUE).withTestName("transactionTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_TRUE).withTestName("transactionTest")); } /* @@ -95,6 +99,6 @@ public void testCommitTransactionWithManagedThreadFactory() throws InterruptedEx @Test @Order(3) public void testCancelTransactionWithManagedThreadFactory() { - runTest(URLBuilder.get().withBaseURL(baseURL).withPaths("TransactionServlet").withQueries(Constants.COMMIT_CANCEL).withTestName("cancelTest")); + runTest(URLBuilder.get().withBaseURL(baseURL).withPaths(Constants.CONTEXT_PATH).withQueries(Constants.COMMIT_CANCEL).withTestName("cancelTest")); } } diff --git a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Util.java b/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Util.java deleted file mode 100644 index fa52eb0e..00000000 --- a/tck/src/main/java/ee/jakarta/tck/concurrent/spec/ManagedThreadFactory/tx/Util.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) 2013, 2022 Oracle and/or its affiliates. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v. 2.0, which is available at - * http://www.eclipse.org/legal/epl-2.0. - * - * This Source Code may also be made available under the following Secondary - * Licenses when the conditions for such availability set forth in the - * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, - * version 2 with the GNU Classpath Exception, which is available at - * https://www.gnu.org/software/classpath/license.html. - * - * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 - */ - -package ee.jakarta.tck.concurrent.spec.ManagedThreadFactory.tx; - -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; - -import ee.jakarta.tck.concurrent.framework.TestLogger; -import ee.jakarta.tck.concurrent.framework.TestUtil; - -public class Util { - - private static final TestLogger log = TestLogger.get(Util.class); - - private Util() { - } - - public static Connection getConnection(DataSource ds, String user, String pwd, boolean autoCommit) { - Connection conn = null; - try { - conn = ds.getConnection(); // Try without user password for EE case - if (conn == null) { - conn = ds.getConnection(user, pwd); // For standalone cases - } - if (null != conn) { - conn.setAutoCommit(autoCommit); - } - } catch (SQLException e) { - log.severe("failed to get connection.", e); - } - return conn; - } - - public static int getCount(String tableName, String username, String password) { - Connection conn = getConnection(true, username, password); - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - if (stmt != null) - stmt.close(); - if (conn != null) - conn.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - /** - * get count by specifying connection. the caller should take care of closing - * connection. - * - * @param conn - * @param tableName - * @param username - * @param password - * @return - */ - public static int getCount(Connection conn, String tableName, String username, String password) { - Statement stmt = null; - try { - final String queryStr = "select count(*) from " + tableName; - stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery(queryStr); - if (rs.next()) { - return rs.getInt(1); - } - } catch (SQLException e1) { - e1.printStackTrace(); - } finally { - try { - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - return -1; - } - - public static Connection getConnection(boolean autoCommit, String username, String password) { - DataSource ds; - try { - ds = InitialContext.doLookup(Constants.DS_JNDI_NAME); - } catch (NamingException e) { - throw new RuntimeException(e); - } - Connection conn = Util.getConnection(ds, username, password, autoCommit); - return conn; - } - - public static void waitForTransactionBegan(CancelledTransactedTask pp) { - final long stopTime = System.currentTimeMillis() + Constants.POLL_TIMEOUT.toMillis(); - while (!pp.transactionBegin() && System.currentTimeMillis() < stopTime) { - try { - TestUtil.sleep(Constants.POLL_INTERVAL); - } catch (InterruptedException ignore) { - } - } - } -}